@qratilabs/qrati-connect 2.27.1 → 2.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/element/{B0sEsGHn.js → 2PuRbItp.js} +7 -7
- package/element/{B5RetLW0.js → 3uWxzKri.js} +51 -49
- package/element/{DyemeRjE2.js → 5z04gCoQ2.js} +1 -1
- package/element/{B9ImRAum.js → 7zeKIiiL.js} +1 -1
- package/element/{MU5QuIq0.js → B01ceTPt.js} +1 -1
- package/element/{C8meSsHD.js → B7YFs6p5.js} +1 -1
- package/element/BB90a5r62.js +93 -0
- package/element/{DSx5wvUb2.js → BHmNrbtm2.js} +1 -1
- package/element/{p0Q_2x6C.js → BIibcFd-.js} +1 -1
- package/element/BL2ZRdn9.js +4 -0
- package/element/{DZGp2V2-.js → BMibcq6T.js} +1 -1
- package/element/BUDCYszs.js +1 -0
- package/element/{DdYePHxG.js → BcAwTWQC.js} +1 -1
- package/element/{DVFC5Z2L2.js → BeUiRRWZ2.js} +31 -31
- package/element/{BdkTKcG52.js → BhOaopIk2.js} +5 -5
- package/element/C6et9sp52.js +3 -0
- package/element/{C4DSwLWc.js → C6ph3KPL.js} +1 -1
- package/element/{DOOdI-Oh.js → C8ixb9k4.js} +1 -1
- package/element/{Bspyv2wJ2.js → CKwlnGWW2.js} +2 -2
- package/element/CMYKP_Yn.js +4 -0
- package/element/CZK4LCzr2.js +3 -0
- package/element/CbTft8Na.js +3 -0
- package/element/CfTxXwtG2.js +36 -0
- package/element/{DlAI3J0X.js → CgaiV8EU.js} +1 -1
- package/element/{Vk429P022.js → Cr4OmKxk2.js} +1 -1
- package/element/{DvisvxzJ.js → CrF08YS6.js} +1 -1
- package/element/CtApMHPf.js +11 -0
- package/element/{BKENYwOQ.js → CxJgMv2R.js} +1 -1
- package/element/{DGZEznLT2.js → D34k0bDj2.js} +1 -1
- package/element/DBlhTxUx2.js +16 -0
- package/element/{CeHBrY_i.js → DUEaNsCB.js} +1 -1
- package/element/DUWOb-5c.js +1 -0
- package/element/{DmIYOIw1.js → DZwpw1jG.js} +1 -1
- package/element/{BspExsK7.js → Da7cHmvl.js} +2 -2
- package/element/{QDuBhueG.js → DlNQukHq.js} +1 -1
- package/element/DmVgPRH5.js +14 -0
- package/element/{CBM5QMn8.js → DtcmI8yd2.js} +1 -1
- package/element/F4i1Y9K7.js +3 -0
- package/element/{DLF5ysgi.js → JFF45CMp.js} +1 -1
- package/element/{CUBxHQ8u.js → KdgQ7jUn.js} +1 -1
- package/element/{C6YE4WUG2.js → cePYhOkN2.js} +4 -4
- package/element/{D_FNRN5A2.js → hiapcVVA2.js} +1 -1
- package/element/{CKQOToSD.js → tJ2MS5HS.js} +3 -3
- package/element/{1eQ9Ef0M2.js → vA5CQmOb2.js} +2 -2
- package/element/web.es.js +39 -39
- package/package.json +1 -1
- package/element/BLeZg2Bz.js +0 -1
- package/element/BmsDSHUi.js +0 -4
- package/element/BqiJLitq2.js +0 -3
- package/element/C6MqLLDX.js +0 -3
- package/element/CfTdZB8y.js +0 -4
- package/element/CgxypkdG.js +0 -3
- package/element/Cl0CwL5p.js +0 -9
- package/element/DRPgs6nu2.js +0 -16
- package/element/DWqIpaZ02.js +0 -2
- package/element/SgRzjPnr.js +0 -14
- package/element/aXvUP7X72.js +0 -93
- package/element/qBKIp1ZW2.js +0 -36
- /package/element/{DPg_DKOi2.js → DPg_DKOi.js} +0 -0
|
@@ -1,36 +1,38 @@
|
|
|
1
|
-
import{r as e,t}from"./DdACKOZr.js";import{E as r,_ as i,c as n,d as o,f as a,g as s,h as l,o as d,p as c,s as u,t as h,v as p,y as m}from"./DrrpB4Om.js";import{i as g,n as f}from"./
|
|
2
|
-
return h("label",{className:g("flex items-center gap-2",a&&"cursor-not-allowed opacity-50",!a&&"cursor-pointer"),children:[/* @__PURE__ */h("button",{type:"button",role:"switch","aria-checked":s,disabled:a,"data-state":l,onBlur:i,onClick:()=>!a&&r?.(!s),className:g("peer relative inline-flex h-6 w-11 shrink-0 items-center rounded-full border-2 transition-colors","border-border bg-muted","focus-visible:ring-2 focus-visible:ring-offset-2","data-[state=checked]:border-primary data-[state=checked]:bg-primary","disabled:cursor-not-allowed disabled:opacity-50",!a&&"cursor-pointer",o),children:/* @__PURE__ */h("span",{"data-state":l,className:g("pointer-events-none block size-5 translate-x-0 rounded-full shadow transition-transform","border-border bg-background border","data-[state=checked]:bg-primary-foreground data-[state=checked]:translate-x-5 data-[state=checked]:border-transparent")})}),n&&/* @__PURE__ */h("span",{className:"text-sm font-medium",children:n})]})}var ie=["jpg","jpeg","png","webp","heic","tiff","bmp","avif"],ne=["mp4","webm","ogg","mov","avi","flv","wmv","mkv","3gp","m4v","mpg","mpeg"];function oe({open:e,oversizedUids:t,onClose:r,onRemoveAndUpload:i}){const n=Object.values(t),o=n.filter(e=>"image"===e).length,a=n.filter(e=>"video"===e).length,s=[];return o>0&&s.push(`${o} image${o>1?"s":""}`),a>0&&s.push(`${a} video${a>1?"s":""}`),/* @__PURE__ */h(X,{open:e,onOpenChange:e=>!e&&r(),children:/* @__PURE__ */h(V,{children:[/* @__PURE__ */h(B,{children:[/* @__PURE__ */h(W,{children:"Some files are too large"}),/* @__PURE__ */h(G,{children:[s.join(" and ")," exceed",1===n.length?"s":""," the size limit (25 MB for images, 250 MB for videos) and won't be uploaded."]})]}),/* @__PURE__ */h(H,{children:/* @__PURE__ */h(
|
|
3
|
-
return h(X,{open:e,onOpenChange:e=>!e&&i(),children:/* @__PURE__ */h(V,{children:[/* @__PURE__ */h(B,{children:[/* @__PURE__ */h(W,{children:"Resume your upload?"}),/* @__PURE__ */h(G,{children:["We found ",t," unfinished upload",t>1?"s":""," from your last visit. Resume where you left off, or remove ",t>1?"them":"it"," and start over."]})]}),/* @__PURE__ */h(H,{children:[/* @__PURE__ */h(
|
|
1
|
+
import{r as e,t}from"./DdACKOZr.js";import{E as r,_ as i,c as n,d as o,f as a,g as s,h as l,o as d,p as c,s as u,t as h,v as p,y as m}from"./DrrpB4Om.js";import{i as g,n as f}from"./tJ2MS5HS.js";import{t as v}from"./DmpmrPE5.js";import{b,i as y,p as w,s as x,x as S,y as T}from"./DUWOb-5c.js";import{c as C,l as F,n as k,u as _}from"./BcAwTWQC.js";import{t as E}from"./DZwpw1jG.js";import{t as M}from"./DPg_DKOi.js";import{t as U}from"./BkIDQGIs.js";import{t as R}from"./CAETItHr.js";import{n as I}from"./C8ixb9k4.js";import{r as N}from"./DGGc10Cy.js";import{t as O}from"./DtcmI8yd2.js";import{t as P}from"./5z04gCoQ2.js";import{a as q,c as A,i as D,o as L,r as j,s as z,t as $}from"./CBLQRRGX2.js";import{a as B,i as H,n as V,o as W,r as G,t as X}from"./Cr4OmKxk2.js";import{t as Y}from"./N4HKgEC52.js";import{n as Q,r as K,t as J}from"./hiapcVVA2.js";var Z=/* @__PURE__ */new Uint8Array(16),ee=[];for(let un=0;un<256;++un)ee.push((un+256).toString(16).slice(1));function te(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){const i=(e=e||{}).random??e.rng?.()??crypto.getRandomValues(Z);if(i.length<16)throw new Error("Random bytes length must be >= 16");if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){if((r=r||0)<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=i[e];return t}return function(e,t=0){return(ee[e[t+0]]+ee[e[t+1]]+ee[e[t+2]]+ee[e[t+3]]+"-"+ee[e[t+4]]+ee[e[t+5]]+"-"+ee[e[t+6]]+ee[e[t+7]]+"-"+ee[e[t+8]]+ee[e[t+9]]+"-"+ee[e[t+10]]+ee[e[t+11]]+ee[e[t+12]]+ee[e[t+13]]+ee[e[t+14]]+ee[e[t+15]]).toLowerCase()}(i)}(e,t,r):crypto.randomUUID()}function re({checked:e,defaultChecked:t,onChange:r,onBlur:i,label:n,className:o,disabled:a}){const s=e??t??!1,l=s?"checked":"unchecked";/* @__PURE__ */
|
|
2
|
+
return h("label",{className:g("flex items-center gap-2",a&&"cursor-not-allowed opacity-50",!a&&"cursor-pointer"),children:[/* @__PURE__ */h("button",{type:"button",role:"switch","aria-checked":s,disabled:a,"data-state":l,onBlur:i,onClick:()=>!a&&r?.(!s),className:g("peer relative inline-flex h-6 w-11 shrink-0 items-center rounded-full border-2 transition-colors","border-border bg-muted","focus-visible:ring-2 focus-visible:ring-offset-2","data-[state=checked]:border-primary data-[state=checked]:bg-primary","disabled:cursor-not-allowed disabled:opacity-50",!a&&"cursor-pointer",o),children:/* @__PURE__ */h("span",{"data-state":l,className:g("pointer-events-none block size-5 translate-x-0 rounded-full shadow transition-transform","border-border bg-background border","data-[state=checked]:bg-primary-foreground data-[state=checked]:translate-x-5 data-[state=checked]:border-transparent")})}),n&&/* @__PURE__ */h("span",{className:"text-sm font-medium",children:n})]})}var ie=["jpg","jpeg","png","webp","heic","tiff","bmp","avif"],ne=["mp4","webm","ogg","mov","avi","flv","wmv","mkv","3gp","m4v","mpg","mpeg"];function oe({open:e,oversizedUids:t,onClose:r,onRemoveAndUpload:i}){const n=Object.values(t),o=n.filter(e=>"image"===e).length,a=n.filter(e=>"video"===e).length,s=[];return o>0&&s.push(`${o} image${o>1?"s":""}`),a>0&&s.push(`${a} video${a>1?"s":""}`),/* @__PURE__ */h(X,{open:e,onOpenChange:e=>!e&&r(),children:/* @__PURE__ */h(V,{children:[/* @__PURE__ */h(B,{children:[/* @__PURE__ */h(W,{children:"Some files are too large"}),/* @__PURE__ */h(G,{children:[s.join(" and ")," exceed",1===n.length?"s":""," the size limit (25 MB for images, 250 MB for videos) and won't be uploaded."]})]}),/* @__PURE__ */h(H,{children:/* @__PURE__ */h(P,{onClick:i,children:"Remove and Upload"})})]})})}function ae({open:e,count:t,onResume:r,onDiscard:i}){/* @__PURE__ */
|
|
3
|
+
return h(X,{open:e,onOpenChange:e=>!e&&i(),children:/* @__PURE__ */h(V,{children:[/* @__PURE__ */h(B,{children:[/* @__PURE__ */h(W,{children:"Resume your upload?"}),/* @__PURE__ */h(G,{children:["We found ",t," unfinished upload",t>1?"s":""," from your last visit. Resume where you left off, or remove ",t>1?"them":"it"," and start over."]})]}),/* @__PURE__ */h(H,{children:[/* @__PURE__ */h(P,{variant:"outlined",onClick:i,children:"Remove All"}),/* @__PURE__ */h(P,{onClick:r,children:"Resume"})]})]})})}var se="error";function le(e){try{const t=JSON.stringify(e);fetch(y.REPORT_ERROR,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0}).catch(()=>{})}catch{}}function de(e,t){const r=e instanceof Error?e.message:String(e),i=e instanceof Error?e.stack:void 0;console.error(`[${t?.component??"app"}]`,r,t?.extra??""),le({message:r,stack:i,level:t?.level??se,component:t?.component,tags:t?.tags,extra:t?.extra,url:"undefined"!=typeof window?window.location.href:void 0,userAgent:"undefined"!=typeof navigator?navigator.userAgent:void 0})}function ce(e,t="info",r){t===se||"fatal"===t?console.error(`[${r?.component??"app"}]`,e,r?.extra??""):console.warn(`[${r?.component??"app"}]`,e,r?.extra??""),le({message:e,level:t,component:r?.component,tags:r?.tags,extra:r?.extra,url:"undefined"!=typeof window?window.location.href:void 0,userAgent:"undefined"!=typeof navigator?navigator.userAgent:void 0})}var ue=["6a385dabb04f4d8783b14fe1","69ada0f82889f080a9ca53df"],he=({open:e,onClose:t,onSuccess:r})=>{const{t:i}=N(),[n,o]=l(!1),a=f(),s=a.props?.organizationId??a.organization?._id,{user:d,updateUser:c}=a,u=!!s&&ue.includes(s.trim()),p=u?"https://qrati.com/terms-of-use-wedding-private-events":"https://qrati.com/terms-of-use",m=u?"https://qrati.com/privacy-policy-wedding-private-events":"https://qrati.com/privacy-policy";/* @__PURE__ */
|
|
4
4
|
return h(X,{open:e,onOpenChange:e=>!e&&t(),children:/* @__PURE__ */h(V,{children:/* @__PURE__ */h("div",{className:"mx-auto max-w-sm p-4 text-center sm:max-w-lg",children:[
|
|
5
5
|
/* @__PURE__ */h(W,{children:i("upload.terms_title","Terms & Conditions")}),
|
|
6
6
|
/* @__PURE__ */h(G,{hidden:!0,children:i("upload.terms_description","Please accept our terms to proceed")}),
|
|
7
7
|
/* @__PURE__ */h("div",{className:"mt-4 mb-6",children:/* @__PURE__ */h("p",{className:"bg-background text-base",children:[i("upload.terms_prompt","I agree to the")," ",
|
|
8
8
|
/* @__PURE__ */h("a",{href:p,className:"text-info inline-flex items-center gap-1 underline",target:"_blank",rel:"noopener noreferrer",children:i("upload.terms_of_use","Terms of Use")})," ",i("upload.and","and")," ",
|
|
9
9
|
/* @__PURE__ */h("a",{href:m,className:"text-info inline-flex items-center gap-1 underline",target:"_blank",rel:"noopener noreferrer",children:i("upload.privacy_policy","Privacy Policy")})," "]})}),
|
|
10
|
-
/* @__PURE__ */h(
|
|
10
|
+
/* @__PURE__ */h(P,{fullWidth:!0,color:"success",disabled:n,loading:n,onClick:async()=>{o(!0);try{const e=await v.post(y.ACCEPT_TERMS,{headers:{"x-org-id":s,Authorization:d?.token?`Bearer ${d.token}`:void 0}}).json();if(e.error)throw new Error(e.error);await c({tcAccepted:!0}),o(!1),r()}catch(e){de(e instanceof Error?e:new Error(String(e)),{component:"TermsAndConditionsModal",tags:["upload","terms-accept"]}),I.error(i("upload.accept_failed","Failed to accept terms"))}o(!1)},children:i("button.accept","Accept")})]})})})},pe=({event:e,locationState:t})=>{const{t:r}=N();/* @__PURE__ */
|
|
11
11
|
return h("div",{className:"mx-auto mt-24 w-fit max-w-xl space-y-8",children:[
|
|
12
12
|
/* @__PURE__ */h(E,{variant:"h3",align:"center",children:r("upload.event_closed","Upload Closed")}),
|
|
13
|
-
/* @__PURE__ */h(E,{variant:"h5",align:"center",color:"muted",children:r("upload.closed_description","This event is no longer accepting uploads.")}),e?.status!==w.CLOSED&&/* @__PURE__ */h("div",{className:"flex flex-row justify-end",children:/* @__PURE__ */h(k,{to:S.PUBLIC_EVENTS,state:t,children:/* @__PURE__ */h(N,{children:r("button.back_to_events","Back to Events")})})})]})};function ce(e,t){let r=0;const i=[],n=()=>{if(r>=e)return;const t=i.shift();t&&t()};return function(e){return new Promise((o,a)=>{i.push(()=>{r++;const i=()=>function(e){let t;return Promise.race([e.finally(()=>clearTimeout(t)),new Promise((e,r)=>{t=setTimeout(()=>r(/* @__PURE__ */new Error("media task timed out")),3e4)})])}(e()).then(o,a).finally(()=>{r--,n()});t?setTimeout(i,0):i()}),n()})}}var ue=ce(2,!1),he=ce(1,!0),pe="error";function me(e){try{const t=JSON.stringify(e);fetch(y.REPORT_ERROR,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0}).catch(()=>{})}catch{}}function ge(e,t){const r=e instanceof Error?e.message:String(e),i=e instanceof Error?e.stack:void 0;console.error(`[${t?.component??"app"}]`,r,t?.extra??""),me({message:r,stack:i,level:t?.level??pe,component:t?.component,tags:t?.tags,extra:t?.extra,url:"undefined"!=typeof window?window.location.href:void 0,userAgent:"undefined"!=typeof navigator?navigator.userAgent:void 0})}function fe(e,t="info",r){t===pe||"fatal"===t?console.error(`[${r?.component??"app"}]`,e,r?.extra??""):console.warn(`[${r?.component??"app"}]`,e,r?.extra??""),me({message:e,level:t,component:r?.component,tags:r?.tags,extra:r?.extra,url:"undefined"!=typeof window?window.location.href:void 0,userAgent:"undefined"!=typeof navigator?navigator.userAgent:void 0})}function ve(e,t,r,i,n,o,a,s,l,d,c,u,h,p,m,g,f,v,b,y){return w=>{const{data:x,width:S,height:T}=w,C=new Uint8ClampedArray(x.length);for(let F=0;F<x.length;F+=4){const w=x[F],S=x[F+1],T=x[F+2],k=x[F+3];C[F]=Math.min(255,Math.max(0,Math.round(e*w+t*S+r*T+i*k+255*n))),C[F+1]=Math.min(255,Math.max(0,Math.round(o*w+a*S+s*T+l*k+255*d))),C[F+2]=Math.min(255,Math.max(0,Math.round(c*w+u*S+h*T+p*k+255*m))),C[F+3]=Math.min(255,Math.max(0,Math.round(g*w+f*S+v*T+b*k+255*y)))}return new ImageData(C,S,T)}}function be(e,t,r,i){const n=Math.cos(i*Math.PI/180),o=Math.sin(i*Math.PI/180);return{r:(.299+.701*n+.168*o)*e,g:(.587-.587*n+.33*o)*t,b:(.114-.114*n-.497*o)*r}}function ye(e){let t=255,r=0,i=0;for(let n=1;n<e.length;n++){const o=e[n]-e[n-1];o>i&&(i=o,t=e[n],r=e[n-1])}return{low:r,high:t}}var we="\nprecision highp float;\nuniform sampler2D u_image;\nuniform vec4 u_row0; uniform float u_off0;\nuniform vec4 u_row1; uniform float u_off1;\nuniform vec4 u_row2; uniform float u_off2;\nuniform vec4 u_row3; uniform float u_off3;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n gl_FragColor = clamp(vec4(\n dot(u_row0, c) + u_off0,\n dot(u_row1, c) + u_off1,\n dot(u_row2, c) + u_off2,\n dot(u_row3, c) + u_off3\n ), 0.0, 1.0);\n}".trim(),xe=[{id:"underwater-correction",name:"Underwater Color Correction",description:"Restores colors absorbed by water — boosts red channel via histogram normalization",category:"color-correction",analyze(e){const t=function(e,t,r){const i=t*r,n=i/2e3,o=/* @__PURE__ */new Int32Array(256),a=/* @__PURE__ */new Int32Array(256),s=/* @__PURE__ */new Int32Array(256);let l=0,d=0,c=0;for(let M=0;M<e.length;M+=4)l+=e[M],d+=e[M+1],c+=e[M+2];const u=l/i,h=d/i,p=c/i;let m=0,g=u;for(;g<60;){const e=be(u,h,p,m);if(g=e.r+e.g+e.b,m++,m>120){g=60;break}}for(let M=0;M<e.length;M+=4){const t=be(e[M],e[M+1],e[M+2],m);o[Math.min(255,Math.max(0,Math.round(t.r+t.g+t.b)))]++,a[e[M+1]]++,s[e[M+2]]++}const f=[0],v=[0],b=[0];for(let M=0;M<256;M++)o[M]-n<2&&f.push(M),a[M]-n<2&&v.push(M),s[M]-n<2&&b.push(M);f.push(255),v.push(255),b.push(255);const y=ye(f),w=ye(v),x=ye(b),S=256/Math.max(1,y.high-y.low),T=256/Math.max(1,w.high-w.low),C=256/Math.max(1,x.high-x.low),F=-y.low/256*S,k=-w.low/256*T,_=-x.low/256*C,E=be(1,1,1,m);return{rR:E.r*S,rG:E.g*S,rB:E.b*S*1.2,rA:0,rOff:F,gR:0,gG:T,gB:0,gA:0,gOff:k,bR:0,bG:0,bB:C,bA:0,bOff:_,aR:0,aG:0,aB:0,aA:1,aOff:0}}(e.data,e.width,e.height);return{u_row0:[t.rR,t.rG,t.rB,t.rA],u_off0:t.rOff,u_row1:[t.gR,t.gG,t.gB,t.gA],u_off1:t.gOff,u_row2:[t.bR,t.bG,t.bB,t.bA],u_off2:t.bOff,u_row3:[t.aR,t.aG,t.aB,t.aA],u_off3:t.aOff}},fragShader:we,buildCpuTransform(e){const t=e.u_row0,r=e.u_row1,i=e.u_row2,n=e.u_row3;return ve(t[0],t[1],t[2],t[3],e.u_off0,r[0],r[1],r[2],r[3],e.u_off1,i[0],i[1],i[2],i[3],e.u_off2,n[0],n[1],n[2],n[3],e.u_off3)},defaultVariables:{},variableSchema:[]},{id:"vignette",name:"Vignette Effect",description:"Darken image corners for dramatic effect",category:"stylistic",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_vignette_strength;\nuniform float u_vignette_radius;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float factor = 1.0;\n if (dist > u_vignette_radius) {\n float falloff = max(0.001, 1.414 - u_vignette_radius);\n float t = (dist - u_vignette_radius) / falloff;\n factor = 1.0 - clamp(t * u_vignette_strength, 0.0, 0.8);\n }\n gl_FragColor = vec4(c.rgb * factor, c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_vignette_strength??.5,r=e.u_vignette_radius??.7,i=new Float32Array(4096);for(let n=0;n<64;n++)for(let e=0;e<64;e++){const o=e/63*2-1,a=n/63*2-1,s=Math.sqrt(o*o+a*a);let l=1;if(s>r){const e=Math.max(.001,1.414-r);l=1-Math.min(.8,(s-r)/e*t)}i[64*n+e]=l}return e=>{const{data:t,width:r,height:n}=e,o=new Uint8ClampedArray(t.length);for(let a=0;a<n;a++)for(let e=0;e<r;e++){const s=4*(a*r+e),l=Math.round(e/Math.max(1,r-1)*63),d=Math.round(a/Math.max(1,n-1)*63),c=i[64*Math.min(63,d)+Math.min(63,l)];o[s]=Math.round(t[s]*c),o[s+1]=Math.round(t[s+1]*c),o[s+2]=Math.round(t[s+2]*c),o[s+3]=t[s+3]}return new ImageData(o,r,n)}},defaultVariables:{vignette_strength:.5,vignette_radius:.7},variableSchema:[{key:"vignette_strength",type:"number",label:"Vignette strength",min:0,max:1,step:.05,default:.5},{key:"vignette_radius",type:"number",label:"Vignette radius",min:0,max:1,step:.05,default:.7}]},{id:"sepia",name:"Sepia Tone",description:"Apply warm sepia tone for vintage look",category:"stylistic",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_sepia_intensity;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n float gray = dot(c.rgb, vec3(0.299, 0.587, 0.114));\n vec3 sepia = vec3(\n min(1.0, gray + 40.0 / 255.0),\n min(1.0, gray + 20.0 / 255.0),\n max(0.0, gray - 30.0 / 255.0)\n );\n gl_FragColor = vec4(mix(c.rgb, sepia, u_sepia_intensity), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_sepia_intensity??.8;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length);for(let a=0;a<r.length;a+=4){const e=r[a],i=r[a+1],n=r[a+2],s=.299*e+.587*i+.114*n,l=Math.min(255,s+40),d=Math.min(255,s+20),c=Math.max(0,s-30);o[a]=Math.round(e*(1-t)+l*t),o[a+1]=Math.round(i*(1-t)+d*t),o[a+2]=Math.round(n*(1-t)+c*t),o[a+3]=r[a+3]}return new ImageData(o,i,n)}},defaultVariables:{sepia_intensity:.8},variableSchema:[{key:"sepia_intensity",type:"number",label:"Sepia intensity",min:0,max:1,step:.05,default:.8}]},{id:"auto-white-balance",name:"Auto White Balance",description:"Grey-world white balance — equalises channel averages from image analysis",category:"color-correction",analyze(e){const t=e.data,r=e.width*e.height;let i=0,n=0,o=0;for(let c=0;c<t.length;c+=4)i+=t[c],n+=t[c+1],o+=t[c+2];const a=i/r,s=n/r,l=o/r,d=(a+s+l)/3;return{u_gain_r:d/Math.max(1,a),u_gain_g:d/Math.max(1,s),u_gain_b:d/Math.max(1,l)}},fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_gain_r;\nuniform float u_gain_g;\nuniform float u_gain_b;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n gl_FragColor = vec4(\n clamp(c.r * u_gain_r, 0.0, 1.0),\n clamp(c.g * u_gain_g, 0.0, 1.0),\n clamp(c.b * u_gain_b, 0.0, 1.0),\n c.a\n );\n}".trim(),buildCpuTransform:e=>ve(e.u_gain_r??1,0,0,0,0,0,e.u_gain_g??1,0,0,0,0,0,e.u_gain_b??1,0,0,0,0,0,1,0),defaultVariables:{},variableSchema:[]},{id:"grayscale",name:"Black & White",description:"Convert image to grayscale using luminance weights",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n float gray = dot(c.rgb, vec3(0.299, 0.587, 0.114));\n gl_FragColor = vec4(vec3(gray), c.a);\n}".trim(),buildCpuTransform:()=>e=>{const{data:t,width:r,height:i}=e,n=new Uint8ClampedArray(t.length);for(let o=0;o<t.length;o+=4){const e=.299*t[o]+.587*t[o+1]+.114*t[o+2];n[o]=n[o+1]=n[o+2]=Math.round(e),n[o+3]=t[o+3]}return new ImageData(n,r,i)},defaultVariables:{},variableSchema:[]},{id:"invert",name:"Invert Colors",description:"Invert all color channels for a negative effect",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n gl_FragColor = vec4(1.0 - c.rgb, c.a);\n}".trim(),buildCpuTransform:()=>e=>{const{data:t,width:r,height:i}=e,n=new Uint8ClampedArray(t.length);for(let o=0;o<t.length;o+=4)n[o]=255-t[o],n[o+1]=255-t[o+1],n[o+2]=255-t[o+2],n[o+3]=t[o+3];return new ImageData(n,r,i)},defaultVariables:{},variableSchema:[]},{id:"brightness-contrast",name:"Brightness & Contrast",description:"Adjust overall brightness and contrast",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_brightness;\nuniform float u_contrast;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n vec3 col = c.rgb + u_brightness;\n col = (col - 0.5) * u_contrast + 0.5;\n gl_FragColor = vec4(clamp(col, 0.0, 1.0), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_brightness??0,r=e.u_contrast??1;return e=>{const{data:i,width:n,height:o}=e,a=new Uint8ClampedArray(i.length);for(let s=0;s<i.length;s+=4){for(let e=0;e<3;e++){let n=i[s+e]/255+t;n=(n-.5)*r+.5,a[s+e]=Math.min(255,Math.max(0,Math.round(255*n)))}a[s+3]=i[s+3]}return new ImageData(a,n,o)}},defaultVariables:{brightness:0,contrast:1},variableSchema:[{key:"brightness",type:"number",label:"Brightness",min:-.5,max:.5,step:.05,default:0},{key:"contrast",type:"number",label:"Contrast",min:0,max:2,step:.05,default:1}]},{id:"saturation",name:"Saturation",description:"Increase or decrease color saturation",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_saturation;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n float gray = dot(c.rgb, vec3(0.299, 0.587, 0.114));\n gl_FragColor = vec4(mix(vec3(gray), c.rgb, u_saturation), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_saturation??1;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length);for(let a=0;a<r.length;a+=4){const e=r[a],i=r[a+1],n=r[a+2],s=.299*e+.587*i+.114*n;o[a]=Math.round(s+(e-s)*t),o[a+1]=Math.round(s+(i-s)*t),o[a+2]=Math.round(s+(n-s)*t),o[a+3]=r[a+3]}return new ImageData(o,i,n)}},defaultVariables:{saturation:1.2},variableSchema:[{key:"saturation",type:"number",label:"Saturation",min:0,max:2,step:.05,default:1.2}]},{id:"hue-rotate",name:"Hue Shift",description:"Rotate the hue of all colors",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_hue_shift;\nvarying vec2 v_texCoord;\n\nvec3 hueShift(vec3 color, float hue) {\n vec3 k = vec3(0.57735, 0.57735, 0.57735);\n float cosAngle = cos(hue);\n float sinAngle = sin(hue);\n return color * cosAngle + cross(k, color) * sinAngle + k * dot(k, color) * (1.0 - cosAngle);\n}\n\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n float rad = u_hue_shift * 3.14159265 / 180.0;\n gl_FragColor = vec4(hueShift(c.rgb, rad), c.a);\n}".trim(),buildCpuTransform(e){const t=(e.u_hue_shift??0)*Math.PI/180,r=Math.cos(t),i=Math.sin(t),n=1/Math.sqrt(3);return e=>{const{data:t,width:o,height:a}=e,s=new Uint8ClampedArray(t.length);for(let l=0;l<t.length;l+=4){const e=t[l]/255,o=t[l+1]/255,a=t[l+2]/255,d=n*(e+o+a),c=e*r+n*(a-o)*i+n*d*(1-r),u=o*r+n*(e-a)*i+n*d*(1-r),h=a*r+n*(o-e)*i+n*d*(1-r);s[l]=Math.min(255,Math.max(0,Math.round(255*c))),s[l+1]=Math.min(255,Math.max(0,Math.round(255*u))),s[l+2]=Math.min(255,Math.max(0,Math.round(255*h))),s[l+3]=t[l+3]}return new ImageData(s,o,a)}},defaultVariables:{hue_shift:30},variableSchema:[{key:"hue_shift",type:"number",label:"Hue shift",min:0,max:360,step:5,default:30}]},{id:"gaussian-blur",name:"Soft Blur",description:"Apply a gentle Gaussian-like blur",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_blur_radius;\nuniform vec2 u_resolution;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec2 off = u_blur_radius / u_resolution;\n vec4 sum = texture2D(u_image, v_texCoord) * 0.25;\n sum += texture2D(u_image, v_texCoord + vec2(off.x, 0.0)) * 0.125;\n sum += texture2D(u_image, v_texCoord - vec2(off.x, 0.0)) * 0.125;\n sum += texture2D(u_image, v_texCoord + vec2(0.0, off.y)) * 0.125;\n sum += texture2D(u_image, v_texCoord - vec2(0.0, off.y)) * 0.125;\n sum += texture2D(u_image, v_texCoord + vec2(off.x, off.y)) * 0.0625;\n sum += texture2D(u_image, v_texCoord - vec2(off.x, off.y)) * 0.0625;\n sum += texture2D(u_image, v_texCoord + vec2(off.x, -off.y)) * 0.0625;\n sum += texture2D(u_image, v_texCoord - vec2(off.x, -off.y)) * 0.0625;\n gl_FragColor = sum;\n}".trim(),buildCpuTransform(e){const t=Math.max(1,Math.round(e.u_blur_radius??2)),r=[[0,0],[t,0],[-t,0],[0,t],[0,-t],[t,t],[-t,-t],[t,-t],[-t,t]],i=[.25,.125,.125,.125,.125,.0625,.0625,.0625,.0625];return e=>{const{data:t,width:n,height:o}=e,a=new Uint8ClampedArray(t.length);for(let s=0;s<o;s++)for(let e=0;e<n;e++){let l=0,d=0,c=0,u=0;for(let a=0;a<9;a++){const h=Math.min(n-1,Math.max(0,e+r[a][0])),p=4*(Math.min(o-1,Math.max(0,s+r[a][1]))*n+h),m=i[a];l+=t[p]*m,d+=t[p+1]*m,c+=t[p+2]*m,u+=t[p+3]*m}const h=4*(s*n+e);a[h]=Math.round(l),a[h+1]=Math.round(d),a[h+2]=Math.round(c),a[h+3]=Math.round(u)}return new ImageData(a,n,o)}},defaultVariables:{blur_radius:2},variableSchema:[{key:"blur_radius",type:"number",label:"Blur radius",min:0,max:8,step:.5,default:2}]},{id:"sharpen",name:"Sharpen",description:"Enhance edge detail for a crisper look",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_sharpen_amount;\nuniform vec2 u_resolution;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec2 off = 1.0 / u_resolution;\n vec4 c = texture2D(u_image, v_texCoord);\n vec4 left = texture2D(u_image, v_texCoord + vec2(-off.x, 0.0));\n vec4 right = texture2D(u_image, v_texCoord + vec2(off.x, 0.0));\n vec4 up = texture2D(u_image, v_texCoord + vec2(0.0, off.y));\n vec4 down = texture2D(u_image, v_texCoord + vec2(0.0, -off.y));\n vec4 edge = left + right + up + down - 4.0 * c;\n gl_FragColor = vec4(clamp(c.rgb - edge.rgb * u_sharpen_amount, 0.0, 1.0), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_sharpen_amount??.8;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length),a=(e,t,o)=>r[4*(Math.min(n-1,Math.max(0,e))*i+Math.min(i-1,Math.max(0,t)))+o];for(let s=0;s<n;s++)for(let e=0;e<i;e++){const n=4*(s*i+e);for(let i=0;i<3;i++){const l=r[n+i],d=a(s,e-1,i)+a(s,e+1,i)+a(s+1,e,i)+a(s-1,e,i)-4*l;o[n+i]=Math.min(255,Math.max(0,Math.round(l-d*t)))}o[n+3]=r[n+3]}return new ImageData(o,i,n)}},defaultVariables:{sharpen_amount:.8},variableSchema:[{key:"sharpen_amount",type:"number",label:"Sharpen amount",min:0,max:3,step:.1,default:.8}]},{id:"edge-detect",name:"Edge Detect",description:"Highlight edges using gradient detection",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_edge_intensity;\nuniform vec2 u_resolution;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec2 off = 1.0 / u_resolution;\n vec4 c = texture2D(u_image, v_texCoord);\n vec4 left = texture2D(u_image, v_texCoord + vec2(-off.x, 0.0));\n vec4 right = texture2D(u_image, v_texCoord + vec2(off.x, 0.0));\n vec4 up = texture2D(u_image, v_texCoord + vec2(0.0, off.y));\n vec4 down = texture2D(u_image, v_texCoord + vec2(0.0, -off.y));\n vec3 edge = abs(left.rgb - right.rgb) + abs(up.rgb - down.rgb);\n float gray = dot(edge, vec3(0.299, 0.587, 0.114));\n vec3 result = mix(c.rgb, vec3(gray), u_edge_intensity);\n gl_FragColor = vec4(result, c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_edge_intensity??1;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length),a=(e,t,o)=>r[4*(Math.min(n-1,Math.max(0,e))*i+Math.min(i-1,Math.max(0,t)))+o]/255;for(let s=0;s<n;s++)for(let e=0;e<i;e++){const n=4*(s*i+e),l=.299*(Math.abs(a(s,e-1,0)-a(s,e+1,0))+Math.abs(a(s+1,e,0)-a(s-1,e,0)))+.587*(Math.abs(a(s,e-1,1)-a(s,e+1,1))+Math.abs(a(s+1,e,1)-a(s-1,e,1)))+.114*(Math.abs(a(s,e-1,2)-a(s,e+1,2))+Math.abs(a(s+1,e,2)-a(s-1,e,2)));for(let e=0;e<3;e++){const i=r[n+e]/255;o[n+e]=Math.min(255,Math.max(0,Math.round(255*(i*(1-t)+l*t))))}o[n+3]=r[n+3]}return new ImageData(o,i,n)}},defaultVariables:{edge_intensity:1},variableSchema:[{key:"edge_intensity",type:"number",label:"Edge intensity",min:0,max:1,step:.05,default:1}]},{id:"warm-tone",name:"Warm Tone",description:"Add warm orange-yellow tones",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_warmth;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n vec3 warm = c.rgb + vec3(0.08, 0.03, -0.05) * u_warmth;\n gl_FragColor = vec4(clamp(warm, 0.0, 1.0), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_warmth??.5;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length);for(let a=0;a<r.length;a+=4)o[a]=Math.min(255,Math.max(0,Math.round(r[a]+20.4*t))),o[a+1]=Math.min(255,Math.max(0,Math.round(r[a+1]+7.65*t))),o[a+2]=Math.min(255,Math.max(0,Math.round(r[a+2]-12.75*t))),o[a+3]=r[a+3];return new ImageData(o,i,n)}},defaultVariables:{warmth:.5},variableSchema:[{key:"warmth",type:"number",label:"Warmth",min:0,max:1,step:.05,default:.5}]},{id:"cool-tone",name:"Cool Tone",description:"Add cool blue-cyan tones",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_coolness;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n vec3 cool = c.rgb + vec3(-0.05, 0.02, 0.08) * u_coolness;\n gl_FragColor = vec4(clamp(cool, 0.0, 1.0), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_coolness??.5;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length);for(let a=0;a<r.length;a+=4)o[a]=Math.min(255,Math.max(0,Math.round(r[a]-12.75*t))),o[a+1]=Math.min(255,Math.max(0,Math.round(r[a+1]+5.1*t))),o[a+2]=Math.min(255,Math.max(0,Math.round(r[a+2]+20.4*t))),o[a+3]=r[a+3];return new ImageData(o,i,n)}},defaultVariables:{coolness:.5},variableSchema:[{key:"coolness",type:"number",label:"Coolness",min:0,max:1,step:.05,default:.5}]},{id:"custom-script",name:"Custom Shader",description:"Write a custom GLSL fragment shader",category:"custom",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform vec2 u_resolution;\nvarying vec2 v_texCoord;\nvoid main() {\n // Your custom shader here.\n // Example — invert colours:\n // vec4 c = texture2D(u_image, v_texCoord);\n // gl_FragColor = vec4(1.0 - c.rgb, c.a);\n gl_FragColor = texture2D(u_image, v_texCoord);\n}".trim(),defaultVariables:{},variableSchema:[]}],Se="\nattribute vec2 a_position;\nvarying vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n v_texCoord = a_position * 0.5 + 0.5;\n}".trim(),Te=new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),Ce=null,Fe=null,ke=null;function _e(e,t,r){const i=e.createShader(t);if(!i)return null;if(e.shaderSource(i,r),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){const r=e.getShaderInfoLog(i);return console.warn("[webgl-filter] shader error:",r),ge(/* @__PURE__ */new Error(`WebGL shader compilation failed: ${r}`),{component:"webgl-filter-engine",tags:["upload","filter","webgl","shader"],extra:{shaderType:t===e.VERTEX_SHADER?"vertex":"fragment"}}),e.deleteShader(i),null}return i}function Ee(e,t){const r=_e(e,e.VERTEX_SHADER,Se),i=_e(e,e.FRAGMENT_SHADER,t);if(!r||!i)return e.deleteShader(r),e.deleteShader(i),null;const n=e.createProgram();if(e.attachShader(n,r),e.attachShader(n,i),e.linkProgram(n),e.deleteShader(r),e.deleteShader(i),!e.getProgramParameter(n,e.LINK_STATUS)){const r=e.getProgramInfoLog(n);return console.warn("[webgl-filter] link error:",r),ge(/* @__PURE__ */new Error(`WebGL program link failed: ${r}`),{component:"webgl-filter-engine",tags:["upload","filter","webgl","link"],extra:{fragmentLength:t.length}}),e.deleteProgram(n),null}return n}function Me(e){const t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),t}function Ue(e,t,r){const i=Me(e);e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,r,0,e.RGBA,e.UNSIGNED_BYTE,null);const n=e.createFramebuffer();return e.bindFramebuffer(e.FRAMEBUFFER,n),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.bindFramebuffer(e.FRAMEBUFFER,null),{fbo:n,tex:i}}function Re(e,t,r){for(const[i,n]of Object.entries(r)){const r=e.getUniformLocation(t,i);if(r)if("number"!=typeof n)switch(n.length){case 2:e.uniform2fv(r,n);break;case 3:e.uniform3fv(r,n);break;case 4:e.uniform4fv(r,n)}else e.uniform1f(r,n)}}function Ie(e){const t=e.config,r=t?.templateId,i=t?.fragShader;if(r){const e=(n=r,xe.find(e=>e.id===n));return{def:e??null,fragShader:e?.fragShader??null}}var n;return i?{def:null,fragShader:i}:{def:null,fragShader:null}}function Pe(e){const t=e.config?.variables??{},r={};for(const[i,n]of Object.entries(t))"number"==typeof n&&(r[`u_${i}`]=n);return r}async function Ne(e,t,r,i="image/webp",n=.85){const o=Date.now(),a=t.filter(e=>e.enabled);if(!a.length)return{blob:e,appliedFilters:[],width:0,height:0,processingTime:0};const s=await createImageBitmap(e);let l=s.width,d=s.height;if(l>r||d>r){const e=Math.min(r/l,r/d);l=Math.round(l*e),d=Math.round(d*e)}const c=Math.min(150,l),u=Math.max(1,Math.round(c*d/l)),h=new OffscreenCanvas(c,u).getContext("2d");h.drawImage(s,0,0,c,u);const p=h.getImageData(0,0,c,u);let m;if(s.width!==l||s.height!==d){const e=new OffscreenCanvas(l,d);e.getContext("2d").drawImage(s,0,0,l,d),s.close(),m=await createImageBitmap(e,{imageOrientation:"flipY"})}else m=await createImageBitmap(s,{imageOrientation:"flipY"}),s.close();const g=Ce??new OffscreenCanvas(l,d);g.width===l&&g.height===d||(g.width=l,g.height=d),Ce=g;let f=Fe;if(f||(f=g.getContext("webgl",{preserveDrawingBuffer:!0,alpha:!0})||g.getContext("experimental-webgl",{preserveDrawingBuffer:!0,alpha:!0}),Fe=f),!f||f.isContextLost())return m.close(),Fe=null,Ce=null,async function(e,t,r,i,n,o,a="image/webp",s=.85){const l=new OffscreenCanvas(r,i),d=l.getContext("2d"),c=await createImageBitmap(e);d.drawImage(c,0,0,r,i),c.close();const u=[];for(const h of t){const{def:e}=Ie(h);if(!e?.buildCpuTransform)continue;const t=e.analyze?e.analyze(n,h.config?.variables??{}):{},o={},a=h.config?.variables??{};for(const[r,i]of Object.entries(a))"number"==typeof i&&(o[`u_${r}`]=i);const s=e.buildCpuTransform({...t,...o},r,i),l=d.getImageData(0,0,r,i);d.putImageData(s(l),0,0),u.push(h.id)}return u.length?{blob:await l.convertToBlob({type:a,quality:s}),appliedFilters:u,width:r,height:i,processingTime:Date.now()-o}:{blob:e,appliedFilters:[],width:r,height:i,processingTime:Date.now()-o}}(e,a,l,d,p,o,i,n);const v=Me(f);f.bindTexture(f.TEXTURE_2D,v),f.texImage2D(f.TEXTURE_2D,0,f.RGBA,f.RGBA,f.UNSIGNED_BYTE,m),m.close(),f.viewport(0,0,l,d);const b=[Ue(f,l,d),Ue(f,l,d)],y=f.createBuffer();f.bindBuffer(f.ARRAY_BUFFER,y),f.bufferData(f.ARRAY_BUFFER,Te,f.STATIC_DRAW);const w=ke??/* @__PURE__ */new Map;ke=w;const x=[];let S=v,T=0;try{for(let e=0;e<a.length;e++){const t=a[e],r=e===a.length-1,{def:i,fragShader:n}=Ie(t);if(!n)continue;const o=t.config?.templateId??n;w.has(o)||w.set(o,Ee(f,n));const s=w.get(o);if(!s)continue;f.useProgram(s);const c=f.getAttribLocation(s,"a_position");f.bindBuffer(f.ARRAY_BUFFER,y),f.enableVertexAttribArray(c),f.vertexAttribPointer(c,2,f.FLOAT,!1,0,0),f.activeTexture(f.TEXTURE0),f.bindTexture(f.TEXTURE_2D,S),f.uniform1i(f.getUniformLocation(s,"u_image"),0);const u=f.getUniformLocation(s,"u_resolution");if(u&&f.uniform2f(u,l,d),Re(f,s,Pe(t)),i?.analyze&&Re(f,s,i.analyze(p,t.config?.variables??{})),r)f.bindFramebuffer(f.FRAMEBUFFER,null),f.drawArrays(f.TRIANGLES,0,6);else{const e=b[T];f.bindFramebuffer(f.FRAMEBUFFER,e.fbo),f.drawArrays(f.TRIANGLES,0,6),S=e.tex,T=1-T}x.push(t.id)}return x.length?{blob:await g.convertToBlob({type:i,quality:n}),appliedFilters:x,width:l,height:d,processingTime:Date.now()-o}:{blob:e,appliedFilters:[],width:l,height:d,processingTime:Date.now()-o}}finally{for(const{fbo:e,tex:t}of b)f.deleteFramebuffer(e),f.deleteTexture(t);f.deleteTexture(v),f.deleteBuffer(y)}}async function qe(e,t,r,i){const n=Date.now(),o=e.filter(e=>e.enabled),a=e=>e;if(!o.length)return{transform:a,appliedFilters:[],processingTime:0};let s=null;try{const e=await createImageBitmap(t),r=Math.min(64,e.width),i=Math.round(r*e.height/e.width),n=new OffscreenCanvas(r,Math.max(1,i)).getContext("2d");n.drawImage(e,0,0,r,Math.max(1,i)),e.close(),s=n.getImageData(0,0,r,Math.max(1,i))}catch{}const l=[],d=[];for(const u of o){const{def:e}=Ie(u);if(!e?.buildCpuTransform)continue;const t=u.config?.variables??{},n=e.analyze&&s?e.analyze(s,t):{},o={};for(const[r,i]of Object.entries(t))"number"==typeof i&&(o[`u_${r}`]=i);try{const t=e.buildCpuTransform({...n,...o},r,i);l.push(t),d.push(u.id)}catch(c){console.warn(`[webgl-filter] buildCpuTransform failed for ${u.id}:`,c),ge(c instanceof Error?c:/* @__PURE__ */new Error(`buildCpuTransform failed for ${u.id}`),{component:"webgl-filter-engine",tags:["upload","filter","cpu-transform"],extra:{filterId:u.id}})}}return l.length?{transform:1===l.length?l[0]:e=>l.reduce((e,t)=>t(e),e),appliedFilters:d,processingTime:Date.now()-n}:{transform:a,appliedFilters:[],processingTime:Date.now()-n}}var Oe=800;async function Ae(e){return new Promise((t,r)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>r(/* @__PURE__ */new Error("FileReader failed")),i.readAsDataURL(e)})}async function De(e,t){const r=Date.now(),i=t.filter(e=>e.enabled),n=await D(e);let o,a;const s=await createImageBitmap(n,{resizeWidth:Oe});if(o=s.width,a=s.height,a>Oe){const e=Oe/a;o=Math.round(o*e),a=Oe}const l=new OffscreenCanvas(o,a);l.getContext("2d").drawImage(s,0,0,o,a),s.close();const d=await l.convertToBlob({type:"image/jpeg",quality:.92}),c=await Ae(d);if(!i.length)return{original:c,processed:c,appliedFilters:[],failedFilters:[],totalExecutionTime:Date.now()-r};let u=c;const h=[],p=[];try{const e=await Ne(d,i,Oe,"image/jpeg",.92);e.appliedFilters.length>0&&(u=await Ae(e.blob),h.push(...e.appliedFilters));for(const t of i)e.appliedFilters.includes(t.id)||p.push({id:t.id,error:"Filter not applied"})}catch(m){for(const e of i)p.push({id:e.id,error:m instanceof Error?m.message:"Unknown error"});ge(m instanceof Error?m:/* @__PURE__ */new Error("Filter preview failed"),{component:"client-filter-engine",tags:["upload","filter-preview","webgl"],extra:{filterCount:i.length,failedFilters:p.map(e=>e.id)}})}return{original:c,processed:u,appliedFilters:h,failedFilters:p,totalExecutionTime:Date.now()-r}}function Le({label:e,info:t,className:r,error:i,disabled:n,id:o,...a}){const l=s(),d=o??l,c=[t?`${d}-info`:null,i?`${d}-error`:null].filter(Boolean);/* @__PURE__ */
|
|
13
|
+
/* @__PURE__ */h(E,{variant:"h5",align:"center",color:"muted",children:r("upload.closed_description","This event is no longer accepting uploads.")}),e?.status!==w.CLOSED&&/* @__PURE__ */h("div",{className:"flex flex-row justify-end",children:/* @__PURE__ */h(k,{to:S.PUBLIC_EVENTS,state:t,children:/* @__PURE__ */h(P,{children:r("button.back_to_events","Back to Events")})})})]})};function me(e,t){let r=0;const i=[],n=()=>{if(r>=e)return;const t=i.shift();t&&t()};return function(e){return new Promise((o,a)=>{i.push(()=>{r++;const i=()=>function(e){let t;return Promise.race([e.finally(()=>clearTimeout(t)),new Promise((e,r)=>{t=setTimeout(()=>r(/* @__PURE__ */new Error("media task timed out")),3e4)})])}(e()).then(o,a).finally(()=>{r--,n()});t?setTimeout(i,0):i()}),n()})}}var ge=me(2,!1),fe=me(1,!0);function ve(e,t,r,i,n,o,a,s,l,d,c,u,h,p,m,g,f,v,b,y){return w=>{const{data:x,width:S,height:T}=w,C=new Uint8ClampedArray(x.length);for(let F=0;F<x.length;F+=4){const w=x[F],S=x[F+1],T=x[F+2],k=x[F+3];C[F]=Math.min(255,Math.max(0,Math.round(e*w+t*S+r*T+i*k+255*n))),C[F+1]=Math.min(255,Math.max(0,Math.round(o*w+a*S+s*T+l*k+255*d))),C[F+2]=Math.min(255,Math.max(0,Math.round(c*w+u*S+h*T+p*k+255*m))),C[F+3]=Math.min(255,Math.max(0,Math.round(g*w+f*S+v*T+b*k+255*y)))}return new ImageData(C,S,T)}}function be(e,t,r,i){const n=Math.cos(i*Math.PI/180),o=Math.sin(i*Math.PI/180);return{r:(.299+.701*n+.168*o)*e,g:(.587-.587*n+.33*o)*t,b:(.114-.114*n-.497*o)*r}}function ye(e){let t=255,r=0,i=0;for(let n=1;n<e.length;n++){const o=e[n]-e[n-1];o>i&&(i=o,t=e[n],r=e[n-1])}return{low:r,high:t}}var we="\nprecision highp float;\nuniform sampler2D u_image;\nuniform vec4 u_row0; uniform float u_off0;\nuniform vec4 u_row1; uniform float u_off1;\nuniform vec4 u_row2; uniform float u_off2;\nuniform vec4 u_row3; uniform float u_off3;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n gl_FragColor = clamp(vec4(\n dot(u_row0, c) + u_off0,\n dot(u_row1, c) + u_off1,\n dot(u_row2, c) + u_off2,\n dot(u_row3, c) + u_off3\n ), 0.0, 1.0);\n}".trim(),xe=[{id:"underwater-correction",name:"Underwater Color Correction",description:"Restores colors absorbed by water — boosts red channel via histogram normalization",category:"color-correction",analyze(e,t){const r=t.blue_boost??1,i=t.hue_shift??0,n=t.intensity??1,o=function(e,t,r,i=1,n=0){const o=t*r,a=o/2e3,s=/* @__PURE__ */new Int32Array(256),l=/* @__PURE__ */new Int32Array(256),d=/* @__PURE__ */new Int32Array(256);let c=0,u=0,h=0;for(let I=0;I<e.length;I+=4)c+=e[I],u+=e[I+1],h+=e[I+2];const p=c/o,m=u/o,g=h/o;let f=0,v=p;for(;v<60;){const e=be(p,m,g,f);if(v=e.r+e.g+e.b,f++,f>120){v=60;break}}const b=f+n;for(let I=0;I<e.length;I+=4){const t=be(e[I],e[I+1],e[I+2],b);s[Math.min(255,Math.max(0,Math.round(t.r+t.g+t.b)))]++,l[e[I+1]]++,d[e[I+2]]++}const y=[0],w=[0],x=[0];for(let I=0;I<256;I++)s[I]-a<2&&y.push(I),l[I]-a<2&&w.push(I),d[I]-a<2&&x.push(I);y.push(255),w.push(255),x.push(255);const S=ye(y),T=ye(w),C=ye(x),F=256/Math.max(1,S.high-S.low),k=256/Math.max(1,T.high-T.low),_=256/Math.max(1,C.high-C.low),E=-S.low/256*F,M=-T.low/256*k,U=-C.low/256*_,R=be(1,1,1,b);return{rR:R.r*F,rG:R.g*F,rB:R.b*F,rA:0,rOff:E,gR:0,gG:k,gB:0,gA:0,gOff:M,bR:0,bG:0,bB:_*i,bA:0,bOff:U,aR:0,aG:0,aB:0,aA:1,aOff:0}}(e.data,e.width,e.height,r,i);return{u_row0:[1*(1-n)+o.rR*n,o.rG*n,o.rB*n,o.rA*n],u_off0:o.rOff*n,u_row1:[o.gR*n,1*(1-n)+o.gG*n,o.gB*n,o.gA*n],u_off1:o.gOff*n,u_row2:[o.bR*n,o.bG*n,1*(1-n)+o.bB*n,o.bA*n],u_off2:o.bOff*n,u_row3:[o.aR,o.aG,o.aB,o.aA],u_off3:o.aOff}},fragShader:we,buildCpuTransform(e){const t=e.u_row0,r=e.u_row1,i=e.u_row2,n=e.u_row3;return ve(t[0],t[1],t[2],t[3],e.u_off0,r[0],r[1],r[2],r[3],e.u_off1,i[0],i[1],i[2],i[3],e.u_off2,n[0],n[1],n[2],n[3],e.u_off3)},defaultVariables:{intensity:1,blue_boost:1,hue_shift:0},variableSchema:[{key:"intensity",type:"number",label:"Intensity",min:0,max:1,step:.05,default:1},{key:"blue_boost",type:"number",label:"Blue boost",min:.5,max:2,step:.05,default:1},{key:"hue_shift",type:"number",label:"Hue shift",min:-30,max:30,step:1,default:0}]},{id:"vignette",name:"Vignette Effect",description:"Darken image corners for dramatic effect",category:"stylistic",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_vignette_strength;\nuniform float u_vignette_radius;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float factor = 1.0;\n if (dist > u_vignette_radius) {\n float falloff = max(0.001, 1.414 - u_vignette_radius);\n float t = (dist - u_vignette_radius) / falloff;\n factor = 1.0 - clamp(t * u_vignette_strength, 0.0, 0.8);\n }\n gl_FragColor = vec4(c.rgb * factor, c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_vignette_strength??.5,r=e.u_vignette_radius??.7,i=new Float32Array(4096);for(let n=0;n<64;n++)for(let e=0;e<64;e++){const o=e/63*2-1,a=n/63*2-1,s=Math.sqrt(o*o+a*a);let l=1;if(s>r){const e=Math.max(.001,1.414-r);l=1-Math.min(.8,(s-r)/e*t)}i[64*n+e]=l}return e=>{const{data:t,width:r,height:n}=e,o=new Uint8ClampedArray(t.length);for(let a=0;a<n;a++)for(let e=0;e<r;e++){const s=4*(a*r+e),l=Math.round(e/Math.max(1,r-1)*63),d=Math.round(a/Math.max(1,n-1)*63),c=i[64*Math.min(63,d)+Math.min(63,l)];o[s]=Math.round(t[s]*c),o[s+1]=Math.round(t[s+1]*c),o[s+2]=Math.round(t[s+2]*c),o[s+3]=t[s+3]}return new ImageData(o,r,n)}},defaultVariables:{vignette_strength:.5,vignette_radius:.7},variableSchema:[{key:"vignette_strength",type:"number",label:"Vignette strength",min:0,max:1,step:.05,default:.5},{key:"vignette_radius",type:"number",label:"Vignette radius",min:0,max:1,step:.05,default:.7}]},{id:"sepia",name:"Sepia Tone",description:"Apply warm sepia tone for vintage look",category:"stylistic",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_sepia_intensity;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n float gray = dot(c.rgb, vec3(0.299, 0.587, 0.114));\n vec3 sepia = vec3(\n min(1.0, gray + 40.0 / 255.0),\n min(1.0, gray + 20.0 / 255.0),\n max(0.0, gray - 30.0 / 255.0)\n );\n gl_FragColor = vec4(mix(c.rgb, sepia, u_sepia_intensity), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_sepia_intensity??.8;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length);for(let a=0;a<r.length;a+=4){const e=r[a],i=r[a+1],n=r[a+2],s=.299*e+.587*i+.114*n,l=Math.min(255,s+40),d=Math.min(255,s+20),c=Math.max(0,s-30);o[a]=Math.round(e*(1-t)+l*t),o[a+1]=Math.round(i*(1-t)+d*t),o[a+2]=Math.round(n*(1-t)+c*t),o[a+3]=r[a+3]}return new ImageData(o,i,n)}},defaultVariables:{sepia_intensity:.8},variableSchema:[{key:"sepia_intensity",type:"number",label:"Sepia intensity",min:0,max:1,step:.05,default:.8}]},{id:"auto-white-balance",name:"Auto White Balance",description:"Grey-world white balance — equalises channel averages from image analysis",category:"color-correction",analyze(e){const t=e.data,r=e.width*e.height;let i=0,n=0,o=0;for(let c=0;c<t.length;c+=4)i+=t[c],n+=t[c+1],o+=t[c+2];const a=i/r,s=n/r,l=o/r,d=(a+s+l)/3;return{u_gain_r:d/Math.max(1,a),u_gain_g:d/Math.max(1,s),u_gain_b:d/Math.max(1,l)}},fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_gain_r;\nuniform float u_gain_g;\nuniform float u_gain_b;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n gl_FragColor = vec4(\n clamp(c.r * u_gain_r, 0.0, 1.0),\n clamp(c.g * u_gain_g, 0.0, 1.0),\n clamp(c.b * u_gain_b, 0.0, 1.0),\n c.a\n );\n}".trim(),buildCpuTransform:e=>ve(e.u_gain_r??1,0,0,0,0,0,e.u_gain_g??1,0,0,0,0,0,e.u_gain_b??1,0,0,0,0,0,1,0),defaultVariables:{},variableSchema:[]},{id:"grayscale",name:"Black & White",description:"Convert image to grayscale using luminance weights",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n float gray = dot(c.rgb, vec3(0.299, 0.587, 0.114));\n gl_FragColor = vec4(vec3(gray), c.a);\n}".trim(),buildCpuTransform:()=>e=>{const{data:t,width:r,height:i}=e,n=new Uint8ClampedArray(t.length);for(let o=0;o<t.length;o+=4){const e=.299*t[o]+.587*t[o+1]+.114*t[o+2];n[o]=n[o+1]=n[o+2]=Math.round(e),n[o+3]=t[o+3]}return new ImageData(n,r,i)},defaultVariables:{},variableSchema:[]},{id:"invert",name:"Invert Colors",description:"Invert all color channels for a negative effect",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n gl_FragColor = vec4(1.0 - c.rgb, c.a);\n}".trim(),buildCpuTransform:()=>e=>{const{data:t,width:r,height:i}=e,n=new Uint8ClampedArray(t.length);for(let o=0;o<t.length;o+=4)n[o]=255-t[o],n[o+1]=255-t[o+1],n[o+2]=255-t[o+2],n[o+3]=t[o+3];return new ImageData(n,r,i)},defaultVariables:{},variableSchema:[]},{id:"brightness-contrast",name:"Brightness & Contrast",description:"Adjust overall brightness and contrast",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_brightness;\nuniform float u_contrast;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n vec3 col = c.rgb + u_brightness;\n col = (col - 0.5) * u_contrast + 0.5;\n gl_FragColor = vec4(clamp(col, 0.0, 1.0), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_brightness??0,r=e.u_contrast??1;return e=>{const{data:i,width:n,height:o}=e,a=new Uint8ClampedArray(i.length);for(let s=0;s<i.length;s+=4){for(let e=0;e<3;e++){let n=i[s+e]/255+t;n=(n-.5)*r+.5,a[s+e]=Math.min(255,Math.max(0,Math.round(255*n)))}a[s+3]=i[s+3]}return new ImageData(a,n,o)}},defaultVariables:{brightness:0,contrast:1},variableSchema:[{key:"brightness",type:"number",label:"Brightness",min:-.5,max:.5,step:.05,default:0},{key:"contrast",type:"number",label:"Contrast",min:0,max:2,step:.05,default:1}]},{id:"saturation",name:"Saturation",description:"Increase or decrease color saturation",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_saturation;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n float gray = dot(c.rgb, vec3(0.299, 0.587, 0.114));\n gl_FragColor = vec4(mix(vec3(gray), c.rgb, u_saturation), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_saturation??1;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length);for(let a=0;a<r.length;a+=4){const e=r[a],i=r[a+1],n=r[a+2],s=.299*e+.587*i+.114*n;o[a]=Math.round(s+(e-s)*t),o[a+1]=Math.round(s+(i-s)*t),o[a+2]=Math.round(s+(n-s)*t),o[a+3]=r[a+3]}return new ImageData(o,i,n)}},defaultVariables:{saturation:1.2},variableSchema:[{key:"saturation",type:"number",label:"Saturation",min:0,max:2,step:.05,default:1.2}]},{id:"hue-rotate",name:"Hue Shift",description:"Rotate the hue of all colors",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_hue_shift;\nvarying vec2 v_texCoord;\n\nvec3 hueShift(vec3 color, float hue) {\n vec3 k = vec3(0.57735, 0.57735, 0.57735);\n float cosAngle = cos(hue);\n float sinAngle = sin(hue);\n return color * cosAngle + cross(k, color) * sinAngle + k * dot(k, color) * (1.0 - cosAngle);\n}\n\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n float rad = u_hue_shift * 3.14159265 / 180.0;\n gl_FragColor = vec4(hueShift(c.rgb, rad), c.a);\n}".trim(),buildCpuTransform(e){const t=(e.u_hue_shift??0)*Math.PI/180,r=Math.cos(t),i=Math.sin(t),n=1/Math.sqrt(3);return e=>{const{data:t,width:o,height:a}=e,s=new Uint8ClampedArray(t.length);for(let l=0;l<t.length;l+=4){const e=t[l]/255,o=t[l+1]/255,a=t[l+2]/255,d=n*(e+o+a),c=e*r+n*(a-o)*i+n*d*(1-r),u=o*r+n*(e-a)*i+n*d*(1-r),h=a*r+n*(o-e)*i+n*d*(1-r);s[l]=Math.min(255,Math.max(0,Math.round(255*c))),s[l+1]=Math.min(255,Math.max(0,Math.round(255*u))),s[l+2]=Math.min(255,Math.max(0,Math.round(255*h))),s[l+3]=t[l+3]}return new ImageData(s,o,a)}},defaultVariables:{hue_shift:30},variableSchema:[{key:"hue_shift",type:"number",label:"Hue shift",min:0,max:360,step:5,default:30}]},{id:"gaussian-blur",name:"Soft Blur",description:"Apply a gentle Gaussian-like blur",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_blur_radius;\nuniform vec2 u_resolution;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec2 off = u_blur_radius / u_resolution;\n vec4 sum = texture2D(u_image, v_texCoord) * 0.25;\n sum += texture2D(u_image, v_texCoord + vec2(off.x, 0.0)) * 0.125;\n sum += texture2D(u_image, v_texCoord - vec2(off.x, 0.0)) * 0.125;\n sum += texture2D(u_image, v_texCoord + vec2(0.0, off.y)) * 0.125;\n sum += texture2D(u_image, v_texCoord - vec2(0.0, off.y)) * 0.125;\n sum += texture2D(u_image, v_texCoord + vec2(off.x, off.y)) * 0.0625;\n sum += texture2D(u_image, v_texCoord - vec2(off.x, off.y)) * 0.0625;\n sum += texture2D(u_image, v_texCoord + vec2(off.x, -off.y)) * 0.0625;\n sum += texture2D(u_image, v_texCoord - vec2(off.x, -off.y)) * 0.0625;\n gl_FragColor = sum;\n}".trim(),buildCpuTransform(e){const t=Math.max(1,Math.round(e.u_blur_radius??2)),r=[[0,0],[t,0],[-t,0],[0,t],[0,-t],[t,t],[-t,-t],[t,-t],[-t,t]],i=[.25,.125,.125,.125,.125,.0625,.0625,.0625,.0625];return e=>{const{data:t,width:n,height:o}=e,a=new Uint8ClampedArray(t.length);for(let s=0;s<o;s++)for(let e=0;e<n;e++){let l=0,d=0,c=0,u=0;for(let a=0;a<9;a++){const h=Math.min(n-1,Math.max(0,e+r[a][0])),p=4*(Math.min(o-1,Math.max(0,s+r[a][1]))*n+h),m=i[a];l+=t[p]*m,d+=t[p+1]*m,c+=t[p+2]*m,u+=t[p+3]*m}const h=4*(s*n+e);a[h]=Math.round(l),a[h+1]=Math.round(d),a[h+2]=Math.round(c),a[h+3]=Math.round(u)}return new ImageData(a,n,o)}},defaultVariables:{blur_radius:2},variableSchema:[{key:"blur_radius",type:"number",label:"Blur radius",min:0,max:8,step:.5,default:2}]},{id:"sharpen",name:"Sharpen",description:"Enhance edge detail for a crisper look",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_sharpen_amount;\nuniform vec2 u_resolution;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec2 off = 1.0 / u_resolution;\n vec4 c = texture2D(u_image, v_texCoord);\n vec4 left = texture2D(u_image, v_texCoord + vec2(-off.x, 0.0));\n vec4 right = texture2D(u_image, v_texCoord + vec2(off.x, 0.0));\n vec4 up = texture2D(u_image, v_texCoord + vec2(0.0, off.y));\n vec4 down = texture2D(u_image, v_texCoord + vec2(0.0, -off.y));\n vec4 edge = left + right + up + down - 4.0 * c;\n gl_FragColor = vec4(clamp(c.rgb - edge.rgb * u_sharpen_amount, 0.0, 1.0), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_sharpen_amount??.8;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length),a=(e,t,o)=>r[4*(Math.min(n-1,Math.max(0,e))*i+Math.min(i-1,Math.max(0,t)))+o];for(let s=0;s<n;s++)for(let e=0;e<i;e++){const n=4*(s*i+e);for(let i=0;i<3;i++){const l=r[n+i],d=a(s,e-1,i)+a(s,e+1,i)+a(s+1,e,i)+a(s-1,e,i)-4*l;o[n+i]=Math.min(255,Math.max(0,Math.round(l-d*t)))}o[n+3]=r[n+3]}return new ImageData(o,i,n)}},defaultVariables:{sharpen_amount:.8},variableSchema:[{key:"sharpen_amount",type:"number",label:"Sharpen amount",min:0,max:3,step:.1,default:.8}]},{id:"edge-detect",name:"Edge Detect",description:"Highlight edges using gradient detection",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_edge_intensity;\nuniform vec2 u_resolution;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec2 off = 1.0 / u_resolution;\n vec4 c = texture2D(u_image, v_texCoord);\n vec4 left = texture2D(u_image, v_texCoord + vec2(-off.x, 0.0));\n vec4 right = texture2D(u_image, v_texCoord + vec2(off.x, 0.0));\n vec4 up = texture2D(u_image, v_texCoord + vec2(0.0, off.y));\n vec4 down = texture2D(u_image, v_texCoord + vec2(0.0, -off.y));\n vec3 edge = abs(left.rgb - right.rgb) + abs(up.rgb - down.rgb);\n float gray = dot(edge, vec3(0.299, 0.587, 0.114));\n vec3 result = mix(c.rgb, vec3(gray), u_edge_intensity);\n gl_FragColor = vec4(result, c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_edge_intensity??1;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length),a=(e,t,o)=>r[4*(Math.min(n-1,Math.max(0,e))*i+Math.min(i-1,Math.max(0,t)))+o]/255;for(let s=0;s<n;s++)for(let e=0;e<i;e++){const n=4*(s*i+e),l=.299*(Math.abs(a(s,e-1,0)-a(s,e+1,0))+Math.abs(a(s+1,e,0)-a(s-1,e,0)))+.587*(Math.abs(a(s,e-1,1)-a(s,e+1,1))+Math.abs(a(s+1,e,1)-a(s-1,e,1)))+.114*(Math.abs(a(s,e-1,2)-a(s,e+1,2))+Math.abs(a(s+1,e,2)-a(s-1,e,2)));for(let e=0;e<3;e++){const i=r[n+e]/255;o[n+e]=Math.min(255,Math.max(0,Math.round(255*(i*(1-t)+l*t))))}o[n+3]=r[n+3]}return new ImageData(o,i,n)}},defaultVariables:{edge_intensity:1},variableSchema:[{key:"edge_intensity",type:"number",label:"Edge intensity",min:0,max:1,step:.05,default:1}]},{id:"warm-tone",name:"Warm Tone",description:"Add warm orange-yellow tones",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_warmth;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n vec3 warm = c.rgb + vec3(0.08, 0.03, -0.05) * u_warmth;\n gl_FragColor = vec4(clamp(warm, 0.0, 1.0), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_warmth??.5;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length);for(let a=0;a<r.length;a+=4)o[a]=Math.min(255,Math.max(0,Math.round(r[a]+20.4*t))),o[a+1]=Math.min(255,Math.max(0,Math.round(r[a+1]+7.65*t))),o[a+2]=Math.min(255,Math.max(0,Math.round(r[a+2]-12.75*t))),o[a+3]=r[a+3];return new ImageData(o,i,n)}},defaultVariables:{warmth:.5},variableSchema:[{key:"warmth",type:"number",label:"Warmth",min:0,max:1,step:.05,default:.5}]},{id:"cool-tone",name:"Cool Tone",description:"Add cool blue-cyan tones",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_coolness;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n vec3 cool = c.rgb + vec3(-0.05, 0.02, 0.08) * u_coolness;\n gl_FragColor = vec4(clamp(cool, 0.0, 1.0), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_coolness??.5;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length);for(let a=0;a<r.length;a+=4)o[a]=Math.min(255,Math.max(0,Math.round(r[a]-12.75*t))),o[a+1]=Math.min(255,Math.max(0,Math.round(r[a+1]+5.1*t))),o[a+2]=Math.min(255,Math.max(0,Math.round(r[a+2]+20.4*t))),o[a+3]=r[a+3];return new ImageData(o,i,n)}},defaultVariables:{coolness:.5},variableSchema:[{key:"coolness",type:"number",label:"Coolness",min:0,max:1,step:.05,default:.5}]},{id:"custom-script",name:"Custom Shader",description:"Write a custom GLSL fragment shader",category:"custom",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform vec2 u_resolution;\nvarying vec2 v_texCoord;\nvoid main() {\n // Your custom shader here.\n // Example — invert colours:\n // vec4 c = texture2D(u_image, v_texCoord);\n // gl_FragColor = vec4(1.0 - c.rgb, c.a);\n gl_FragColor = texture2D(u_image, v_texCoord);\n}".trim(),defaultVariables:{},variableSchema:[]}];function Se(e){return xe.find(t=>t.id===e)}function Te(e,t){if(e){if("number"===e.type){if("number"!=typeof t||!Number.isFinite(t))return;const r=e.min??-1/0,i=e.max??1/0;return Math.min(i,Math.max(r,t))}return"boolean"===e.type?"boolean"==typeof t?t:void 0:"string"==typeof t?t:void 0}}var Ce="\nattribute vec2 a_position;\nvarying vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n v_texCoord = a_position * 0.5 + 0.5;\n}".trim(),Fe=new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),ke=null,_e=null,Ee=null;function Me(e,t,r){const i=e.createShader(t);if(!i)return null;if(e.shaderSource(i,r),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){const r=e.getShaderInfoLog(i);return console.warn("[webgl-filter] shader error:",r),de(/* @__PURE__ */new Error(`WebGL shader compilation failed: ${r}`),{component:"webgl-filter-engine",tags:["upload","filter","webgl","shader"],extra:{shaderType:t===e.VERTEX_SHADER?"vertex":"fragment"}}),e.deleteShader(i),null}return i}function Ue(e,t){const r=Me(e,e.VERTEX_SHADER,Ce),i=Me(e,e.FRAGMENT_SHADER,t);if(!r||!i)return e.deleteShader(r),e.deleteShader(i),null;const n=e.createProgram();if(e.attachShader(n,r),e.attachShader(n,i),e.linkProgram(n),e.deleteShader(r),e.deleteShader(i),!e.getProgramParameter(n,e.LINK_STATUS)){const r=e.getProgramInfoLog(n);return console.warn("[webgl-filter] link error:",r),de(/* @__PURE__ */new Error(`WebGL program link failed: ${r}`),{component:"webgl-filter-engine",tags:["upload","filter","webgl","link"],extra:{fragmentLength:t.length}}),e.deleteProgram(n),null}return n}function Re(e){const t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),t}function Ie(e,t,r){const i=Re(e);e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,r,0,e.RGBA,e.UNSIGNED_BYTE,null);const n=e.createFramebuffer();return e.bindFramebuffer(e.FRAMEBUFFER,n),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.bindFramebuffer(e.FRAMEBUFFER,null),{fbo:n,tex:i}}function Ne(e,t,r){for(const[i,n]of Object.entries(r)){const r=e.getUniformLocation(t,i);if(r)if("number"!=typeof n)switch(n.length){case 2:e.uniform2fv(r,n);break;case 3:e.uniform3fv(r,n);break;case 4:e.uniform4fv(r,n)}else e.uniform1f(r,n)}}function Oe(e){const t=e.config,r=t?.templateId,i=t?.fragShader;if(r){const e=Se(r);return{def:e??null,fragShader:e?.fragShader??null}}return i?{def:null,fragShader:i}:{def:null,fragShader:null}}function Pe(e){const t=e.config?.variables??{},r={};for(const[i,n]of Object.entries(t))"number"==typeof n&&(r[`u_${i}`]=n);return r}async function qe(e,t,r,i="image/webp",n=.85){const o=Date.now(),a=t.filter(e=>e.enabled);if(!a.length)return{blob:e,appliedFilters:[],width:0,height:0,processingTime:0};const s=await createImageBitmap(e);let l=s.width,d=s.height;if(l>r||d>r){const e=Math.min(r/l,r/d);l=Math.round(l*e),d=Math.round(d*e)}const c=Math.min(150,l),u=Math.max(1,Math.round(c*d/l)),h=new OffscreenCanvas(c,u).getContext("2d");h.drawImage(s,0,0,c,u);const p=h.getImageData(0,0,c,u);let m;if(s.width!==l||s.height!==d){const e=new OffscreenCanvas(l,d);e.getContext("2d").drawImage(s,0,0,l,d),s.close(),m=await createImageBitmap(e,{imageOrientation:"flipY"})}else m=await createImageBitmap(s,{imageOrientation:"flipY"}),s.close();const g=ke??new OffscreenCanvas(l,d);g.width===l&&g.height===d||(g.width=l,g.height=d),ke=g;let f=_e;if(f||(f=g.getContext("webgl",{preserveDrawingBuffer:!0,alpha:!0})||g.getContext("experimental-webgl",{preserveDrawingBuffer:!0,alpha:!0}),_e=f),!f||f.isContextLost())return m.close(),_e=null,ke=null,async function(e,t,r,i,n,o,a="image/webp",s=.85){const l=new OffscreenCanvas(r,i),d=l.getContext("2d"),c=await createImageBitmap(e);d.drawImage(c,0,0,r,i),c.close();const u=[];for(const h of t){const{def:e}=Oe(h);if(!e?.buildCpuTransform)continue;const t=e.analyze?e.analyze(n,h.config?.variables??{}):{},o={},a=h.config?.variables??{};for(const[r,i]of Object.entries(a))"number"==typeof i&&(o[`u_${r}`]=i);const s=e.buildCpuTransform({...t,...o},r,i),l=d.getImageData(0,0,r,i);d.putImageData(s(l),0,0),u.push(h.id)}return u.length?{blob:await l.convertToBlob({type:a,quality:s}),appliedFilters:u,width:r,height:i,processingTime:Date.now()-o}:{blob:e,appliedFilters:[],width:r,height:i,processingTime:Date.now()-o}}(e,a,l,d,p,o,i,n);const v=Re(f);f.bindTexture(f.TEXTURE_2D,v),f.texImage2D(f.TEXTURE_2D,0,f.RGBA,f.RGBA,f.UNSIGNED_BYTE,m),m.close(),f.viewport(0,0,l,d);const b=[Ie(f,l,d),Ie(f,l,d)],y=f.createBuffer();f.bindBuffer(f.ARRAY_BUFFER,y),f.bufferData(f.ARRAY_BUFFER,Fe,f.STATIC_DRAW);const w=Ee??/* @__PURE__ */new Map;Ee=w;const x=[];let S=v,T=0;try{for(let e=0;e<a.length;e++){const t=a[e],r=e===a.length-1,{def:i,fragShader:n}=Oe(t);if(!n)continue;const o=t.config?.templateId??n;w.has(o)||w.set(o,Ue(f,n));const s=w.get(o);if(!s)continue;f.useProgram(s);const c=f.getAttribLocation(s,"a_position");f.bindBuffer(f.ARRAY_BUFFER,y),f.enableVertexAttribArray(c),f.vertexAttribPointer(c,2,f.FLOAT,!1,0,0),f.activeTexture(f.TEXTURE0),f.bindTexture(f.TEXTURE_2D,S),f.uniform1i(f.getUniformLocation(s,"u_image"),0);const u=f.getUniformLocation(s,"u_resolution");if(u&&f.uniform2f(u,l,d),Ne(f,s,Pe(t)),i?.analyze&&Ne(f,s,i.analyze(p,t.config?.variables??{})),r)f.bindFramebuffer(f.FRAMEBUFFER,null),f.drawArrays(f.TRIANGLES,0,6);else{const e=b[T];f.bindFramebuffer(f.FRAMEBUFFER,e.fbo),f.drawArrays(f.TRIANGLES,0,6),S=e.tex,T=1-T}x.push(t.id)}return x.length?{blob:await g.convertToBlob({type:i,quality:n}),appliedFilters:x,width:l,height:d,processingTime:Date.now()-o}:{blob:e,appliedFilters:[],width:l,height:d,processingTime:Date.now()-o}}finally{for(const{fbo:e,tex:t}of b)f.deleteFramebuffer(e),f.deleteTexture(t);f.deleteTexture(v),f.deleteBuffer(y)}}async function Ae(e,t,r,i){const n=Date.now(),o=e.filter(e=>e.enabled),a=e=>e;if(!o.length)return{transform:a,appliedFilters:[],processingTime:0};let s=null;try{const e=await createImageBitmap(t),r=Math.min(64,e.width),i=Math.round(r*e.height/e.width),n=new OffscreenCanvas(r,Math.max(1,i)).getContext("2d");n.drawImage(e,0,0,r,Math.max(1,i)),e.close(),s=n.getImageData(0,0,r,Math.max(1,i))}catch{}const l=[],d=[];for(const u of o){const{def:e}=Oe(u);if(!e?.buildCpuTransform)continue;const t=u.config?.variables??{},n=e.analyze&&s?e.analyze(s,t):{},o={};for(const[r,i]of Object.entries(t))"number"==typeof i&&(o[`u_${r}`]=i);try{const t=e.buildCpuTransform({...n,...o},r,i);l.push(t),d.push(u.id)}catch(c){console.warn(`[webgl-filter] buildCpuTransform failed for ${u.id}:`,c),de(c instanceof Error?c:/* @__PURE__ */new Error(`buildCpuTransform failed for ${u.id}`),{component:"webgl-filter-engine",tags:["upload","filter","cpu-transform"],extra:{filterId:u.id}})}}return l.length?{transform:1===l.length?l[0]:e=>l.reduce((e,t)=>t(e),e),appliedFilters:d,processingTime:Date.now()-n}:{transform:a,appliedFilters:[],processingTime:Date.now()-n}}var De=800;async function Le(e){return new Promise((t,r)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>r(/* @__PURE__ */new Error("FileReader failed")),i.readAsDataURL(e)})}async function je(e,t){const r=Date.now(),i=t.filter(e=>e.enabled),n=await D(e);let o,a;const s=await createImageBitmap(n,{resizeWidth:De});if(o=s.width,a=s.height,a>De){const e=De/a;o=Math.round(o*e),a=De}const l=new OffscreenCanvas(o,a);l.getContext("2d").drawImage(s,0,0,o,a),s.close();const d=await l.convertToBlob({type:"image/jpeg",quality:.92}),c=await Le(d);if(!i.length)return{original:c,processed:c,appliedFilters:[],failedFilters:[],totalExecutionTime:Date.now()-r};let u=c;const h=[],p=[];try{const e=await qe(d,i,De,"image/jpeg",.92);e.appliedFilters.length>0&&(u=await Le(e.blob),h.push(...e.appliedFilters));for(const t of i)e.appliedFilters.includes(t.id)||p.push({id:t.id,error:"Filter not applied"})}catch(m){for(const e of i)p.push({id:e.id,error:m instanceof Error?m.message:"Unknown error"});de(m instanceof Error?m:/* @__PURE__ */new Error("Filter preview failed"),{component:"client-filter-engine",tags:["upload","filter-preview","webgl"],extra:{filterCount:i.length,failedFilters:p.map(e=>e.id)}})}return{original:c,processed:u,appliedFilters:h,failedFilters:p,totalExecutionTime:Date.now()-r}}function ze({label:e,info:t,className:r,error:i,disabled:n,id:o,...a}){const l=s(),d=o??l,c=[t?`${d}-info`:null,i?`${d}-error`:null].filter(Boolean);/* @__PURE__ */
|
|
14
14
|
return h("div",{className:"space-y-1.5",children:[e&&/* @__PURE__ */h("label",{htmlFor:d,className:"block text-base font-medium",children:e}),
|
|
15
|
-
/* @__PURE__ */h("textarea",{id:d,className:g("border-border shadow-card focus:border-primary ring-offset-background focus:ring-primary min-h-12 w-full rounded border px-3 py-2.5 focus:outline-none focus-visible:ring-2","field-sizing-content",n&&"text-muted-foreground bg-transparent",i&&"border-destructive focus-visible:ring-destructive/20",r),disabled:n,"aria-invalid":!!i,"aria-describedby":c.length>0?c.join(" "):void 0,...a}),t&&/* @__PURE__ */h("p",{id:`${d}-info`,className:"text-muted-foreground text-xs",children:t}),i&&/* @__PURE__ */h("p",{id:`${d}-error`,className:"text-destructive text-xs",children:i})]})}var
|
|
16
|
-
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"m20 7l-.95-2.05L17 4l2.05-.95L20 1l.95 2.05L23 4l-2.05.95L20 7ZM8.5 7l-.95-2.05L5.5 4l2.05-.95L8.5 1l.95 2.05L11.5 4l-2.05.95L8.5 7ZM20 18.5l-.95-2.05L17 15.5l2.05-.95l.95-2.05l.95 2.05l2.05.95l-2.05.95L20 18.5ZM5.1 21.7l-2.8-2.8q-.3-.3-.3-.725t.3-.725L13.45 6.3q.3-.3.725-.3t.725.3l2.8 2.8q.3.3.3.725t-.3.725L6.55 21.7q-.3.3-.725.3t-.725-.3Zm9.075-10.475l1.4-1.4l-1.4-1.4l-1.4 1.4l1.4 1.4Z"})})}function
|
|
17
|
-
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"m19.55 6.025l-.5-1.075l-1.075-.5Q17.7 4.325 17.7 4t.275-.45l1.075-.5l.5-1.075q.125-.275.45-.275t.45.275l.5 1.075l1.075.5q.275.125.275.45t-.275.45l-1.075.5l-.5 1.075q-.125.275-.45.275t-.45-.275Zm-4 6.675L11.3 8.45l2.15-2.15q.3-.3.725-.3t.725.3l2.8 2.8q.3.3.3.725t-.3.725l-2.15 2.15Zm3.55 9.2l-6.4-6.35l-6.15 6.15q-.3.3-.725.3t-.725-.3l-2.8-2.85q-.275-.275-.275-.7t.275-.7l6.15-6.15L2.1 4.9q-.3-.3-.3-.7t.3-.7q.275-.275.7-.275t.7.275l17 17q.275.275.275.7t-.275.7q-.3.3-.7.3t-.7-.3Z"})})}function
|
|
18
|
-
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M10 21H5q-.825 0-1.412-.587T3 19V5q0-.825.588-1.412T5 3h5V2q0-.425.288-.712T11 1t.713.288T12 2v20q0 .425-.288.713T11 23t-.712-.288T10 22zm-5-3h5v-6zm9 3v-9l5 6V5h-5V3h5q.825 0 1.413.588T21 5v14q0 .825-.587 1.413T19 21z"})})}function
|
|
19
|
-
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"m12 14l-2.35 2.35q.2.375.275.8T10 18q0 1.65-1.175 2.825T6 22t-2.825-1.175T2 18t1.175-2.825T6 14q.425 0 .85.075t.8.275L10 12L7.65 9.65q-.375.2-.8.275T6 10q-1.65 0-2.825-1.175T2 6t1.175-2.825T6 2t2.825 1.175T10 6q0 .425-.075.85t-.275.8L20.6 18.6q.675.675.3 1.538T19.575 21q-.275 0-.537-.112t-.463-.313zm3-3l-2-2l5.575-5.575q.2-.2.463-.312T19.574 3q.95 0 1.313.875t-.313 1.55zM7.413 7.413Q8 6.825 8 6t-.587-1.412T6 4t-1.412.588T4 6t.588 1.413T6 8t1.413-.587m4.937 4.937q.15-.15.15-.35t-.15-.35t-.35-.15t-.35.15t-.15.35t.15.35t.35.15t.35-.15m-4.937 7.063Q8 18.825 8 18t-.587-1.412T6 16t-1.412.588T4 18t.588 1.413T6 20t1.413-.587"})})}function
|
|
20
|
-
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M17 22v-3H7q-.825 0-1.412-.587T5 17V7H2q-.425 0-.712-.288T1 6t.288-.712T2 5h3V2q0-.425.288-.712T6 1t.713.288T7 2v15h15q.425 0 .713.288T23 18t-.288.713T22 19h-3v3q0 .425-.288.713T18 23t-.712-.288T17 22m0-7V7H9V5h8q.825 0 1.413.588T19 7v8z"})})}function
|
|
21
|
-
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M6 22q-.825 0-1.412-.587T4 20V4q0-.825.588-1.412T6 2h7.175q.4 0 .763.15t.637.425l4.85 4.85q.275.275.425.638t.15.762V20q0 .825-.587 1.413T18 22zm7-14q0 .425.288.713T14 9h4l-5-5z"})})}function
|
|
22
|
-
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M16 19q-.825 0-1.412-.587T14 17V7q0-.825.588-1.412T16 5t1.413.588T18 7v10q0 .825-.587 1.413T16 19m-8 0q-.825 0-1.412-.587T6 17V7q0-.825.588-1.412T8 5t1.413.588T10 7v10q0 .825-.587 1.413T8 19"})})}function
|
|
23
|
-
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M8 17.175V6.825q0-.425.3-.713t.7-.287q.125 0 .263.037t.262.113l8.15 5.175q.225.15.338.375t.112.475t-.112.475t-.338.375l-8.15 5.175q-.125.075-.262.113T9 18.175q-.4 0-.7-.288t-.3-.712"})})}function
|
|
24
|
-
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M16.775 19.575q-.275.175-.55.325t-.575.275q-.375.175-.762 0t-.538-.575q-.15-.375.038-.737t.562-.538q.1-.05.188-.1t.187-.1L12 14.8v2.775q0 .675-.612.938T10.3 18.3L7 15H4q-.425 0-.712-.288T3 14v-4q0-.425.288-.712T4 9h2.2L2.1 4.9q-.275-.275-.275-.7t.275-.7t.7-.275t.7.275l17 17q.275.275.275.7t-.275.7t-.7.275t-.7-.275zm2.225-7.6q0-2.075-1.1-3.787t-2.95-2.563q-.375-.175-.55-.537t-.05-.738q.15-.4.538-.575t.787 0Q18.1 4.85 19.55 7.05T21 11.975q0 .825-.15 1.638t-.425 1.562q-.2.55-.612.688t-.763.012t-.562-.45t-.013-.75q.275-.65.4-1.312T19 11.975m-4.225-3.55Q15.6 8.95 16.05 10t.45 2v.25q0 .125-.025.25q-.05.325-.35.425t-.55-.15L14.3 11.5q-.15-.15-.225-.337T14 10.775V8.85q0-.3.263-.437t.512.012M9.75 6.95Q9.6 6.8 9.6 6.6t.15-.35l.55-.55q.475-.475 1.087-.213t.613.938V8q0 .35-.3.475t-.55-.125z"})})}function
|
|
25
|
-
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M19 11.975q0-2.075-1.1-3.787t-2.95-2.563q-.375-.175-.55-.537t-.05-.738q.15-.4.538-.575t.787 0Q18.1 4.85 19.55 7.063T21 11.974t-1.45 4.913t-3.875 3.287q-.4.175-.788 0t-.537-.575q-.125-.375.05-.737t.55-.538q1.85-.85 2.95-2.562t1.1-3.788M7 15H4q-.425 0-.712-.288T3 14v-4q0-.425.288-.712T4 9h3l3.3-3.3q.475-.475 1.088-.213t.612.938v11.15q0 .675-.612.938T10.3 18.3zm9.5-3q0 1.05-.475 1.988t-1.25 1.537q-.25.15-.513.013T14 15.1V8.85q0-.3.263-.437t.512.012q.775.625 1.25 1.575t.475 2"})})}function
|
|
26
|
-
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M6 18H4q-.425 0-.712-.288T3 17t.288-.712T4 16h3q.425 0 .713.288T8 17v3q0 .425-.288.713T7 21t-.712-.288T6 20zm12 0v2q0 .425-.288.713T17 21t-.712-.288T16 20v-3q0-.425.288-.712T17 16h3q.425 0 .713.288T21 17t-.288.713T20 18zM6 6V4q0-.425.288-.712T7 3t.713.288T8 4v3q0 .425-.288.713T7 8H4q-.425 0-.712-.288T3 7t.288-.712T4 6zm12 0h2q.425 0 .713.288T21 7t-.288.713T20 8h-3q-.425 0-.712-.288T16 7V4q0-.425.288-.712T17 3t.713.288T18 4z"})})}function
|
|
27
|
-
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M5 19h2q.425 0 .713.288T8 20t-.288.713T7 21H4q-.425 0-.712-.288T3 20v-3q0-.425.288-.712T4 16t.713.288T5 17zm14 0v-2q0-.425.288-.712T20 16t.713.288T21 17v3q0 .425-.288.713T20 21h-3q-.425 0-.712-.288T16 20t.288-.712T17 19zM5 5v2q0 .425-.288.713T4 8t-.712-.288T3 7V4q0-.425.288-.712T4 3h3q.425 0 .713.288T8 4t-.288.713T7 5zm14 0h-2q-.425 0-.712-.288T16 4t.288-.712T17 3h3q.425 0 .713.288T21 4v3q0 .425-.288.713T20 8t-.712-.288T19 7z"})})}
|
|
28
|
-
return h(
|
|
29
|
-
|
|
15
|
+
/* @__PURE__ */h("textarea",{id:d,className:g("border-border shadow-card focus:border-primary ring-offset-background focus:ring-primary min-h-12 w-full rounded border px-3 py-2.5 focus:outline-none focus-visible:ring-2","field-sizing-content",n&&"text-muted-foreground bg-transparent",i&&"border-destructive focus-visible:ring-destructive/20",r),disabled:n,"aria-invalid":!!i,"aria-describedby":c.length>0?c.join(" "):void 0,...a}),t&&/* @__PURE__ */h("p",{id:`${d}-info`,className:"text-muted-foreground text-xs",children:t}),i&&/* @__PURE__ */h("p",{id:`${d}-error`,className:"text-destructive text-xs",children:i})]})}var $e=/* @__PURE__ */new Map;function Be(e,t,r,i){return`${e}:${JSON.stringify(t)}:${r}x${i}`}function He(e){const t=$e.get(e);return t&&($e.delete(e),$e.set(e,t)),t}function Ve(e,t){if($e.delete(e),$e.set(e,t),$e.size>3){const e=$e.keys().next().value;void 0!==e&&$e.delete(e)}}var We=e=>{let t;const r=/* @__PURE__ */new Set,i=(e,i)=>{const n="function"==typeof e?e(t):e;if(!Object.is(n,t)){const e=t;t=(null!=i?i:"object"!=typeof n||null===n)?n:Object.assign({},t,n),r.forEach(r=>r(t,e))}},n=()=>t,o={setState:i,getState:n,getInitialState:()=>a,subscribe:e=>(r.add(e),()=>r.delete(e))},a=t=e(i,n,o);return o},Ge=e=>e;var Xe=r(null);function Ye({children:e,...t}){const r=a(null),i=a(t);return r.current&&t.eventId===i.current.eventId&&t.groupId===i.current.groupId||(r.current=function(e){return(t=t=>({eventId:e.eventId,groupId:e.groupId,selectedFiles:[],originalFiles:{},captions:{},hasStarted:!1,oversizedUids:{},showOversizedModal:!1,trimRanges:{},cropSelections:{},videoMuted:!0,uploadStates:{},uploadSpeedBps:0,showRestoreDialog:!1,restoredUids:[],activeFilters:[],showFilterChoice:!1,skipUploadFilters:!1,perFileFilterSkipped:{},filteredThumbs:{},filterOverrides:{},setSelectedFiles:e=>t(t=>({selectedFiles:"function"==typeof e?e(t.selectedFiles):e})),addOriginalFiles:e=>t(t=>({originalFiles:{...t.originalFiles,...e}})),removeFile:e=>t(t=>{if(!t.selectedFiles.some(t=>t.uid===e))return t;const r={...t.captions};delete r[e];const i={...t.oversizedUids};delete i[e];const n={...t.trimRanges};delete n[e];const o={...t.originalFiles};delete o[e];const a={...t.cropSelections};delete a[e];const s={...t.uploadStates};t.hasStarted||delete s[e];const l={...t.filteredThumbs};delete l[e];const d={...t.perFileFilterSkipped};delete d[e];const c={...t.filterOverrides};return delete c[e],{selectedFiles:t.selectedFiles.filter(t=>t.uid!==e),captions:r,oversizedUids:i,trimRanges:n,originalFiles:o,cropSelections:a,uploadStates:s,filteredThumbs:l,perFileFilterSkipped:d,filterOverrides:c}}),setCaption:(e,r)=>t(t=>({captions:{...t.captions,[e]:r}})),setHasStarted:e=>t({hasStarted:e}),addOversizedUids:e=>t(t=>({oversizedUids:{...t.oversizedUids,...e}})),removeOversizedFiles:()=>t(e=>{const t=new Set(Object.keys(e.oversizedUids)),r={...e.captions},i={...e.trimRanges},n={...e.originalFiles},o={...e.cropSelections},a={...e.uploadStates},s={...e.filteredThumbs},l={...e.perFileFilterSkipped},d={...e.filterOverrides};return t.forEach(e=>{delete r[e],delete i[e],delete n[e],delete o[e],delete a[e],delete s[e],delete l[e],delete d[e]}),{selectedFiles:e.selectedFiles.filter(e=>!t.has(e.uid)),captions:r,trimRanges:i,originalFiles:n,cropSelections:o,uploadStates:a,filteredThumbs:s,perFileFilterSkipped:l,filterOverrides:d,oversizedUids:{},showOversizedModal:!1}}),setShowOversizedModal:e=>t({showOversizedModal:e}),replaceFile:(e,r,i)=>t(t=>{const n={...t.cropSelections};i&&(n[e]=i);const o={...t.filteredThumbs};return delete o[e],{selectedFiles:t.selectedFiles.map(t=>t.uid===e?{...t,file:r}:t),cropSelections:n,filteredThumbs:o}}),setTrimRange:(e,r)=>t(t=>({trimRanges:{...t.trimRanges,[e]:r}})),setVideoMuted:e=>t({videoMuted:e}),setUploadState:(e,r)=>t(t=>({uploadStates:{...t.uploadStates,[e]:{...t.uploadStates[e],...r}}})),setUploadSpeedBps:e=>t({uploadSpeedBps:e}),setActiveFilters:(e,r)=>t({activeFilters:e,showFilterChoice:r}),setSkipUploadFilters:e=>t({skipUploadFilters:e}),setFileFilterSkipped:(e,r)=>t(t=>({perFileFilterSkipped:{...t.perFileFilterSkipped,[e]:r}})),setFilterOverride:(e,r,i,n)=>t(t=>({filterOverrides:{...t.filterOverrides,[e]:{...t.filterOverrides[e],[r]:{...t.filterOverrides[e]?.[r],[i]:n}}}})),setFilteredThumb:(e,r)=>t(t=>({filteredThumbs:{...t.filteredThumbs,[e]:r}})),resetUploader:()=>{$e.clear(),t({selectedFiles:[],originalFiles:{},captions:{},hasStarted:!1,oversizedUids:{},showOversizedModal:!1,trimRanges:{},cropSelections:{},uploadStates:{},uploadSpeedBps:0,skipUploadFilters:!1,perFileFilterSkipped:{},filteredThumbs:{},filterOverrides:{}})}}))?We(t):We;var t}(t),i.current=t),/* @__PURE__ */h(Xe.Provider,{value:r.current,children:e})}function Qe(e){const t=m(Xe);if(!t)throw new Error("useUploadStore must be used within UploadStoreProvider");return function(e,t=Ge){const r=n.useSyncExternalStore(e.subscribe,n.useCallback(()=>t(e.getState()),[e,t]),n.useCallback(()=>t(e.getInitialState()),[e,t]));return n.useDebugValue(r),r}(t,e)}function Ke(){const e=m(Xe);if(!e)throw new Error("useUploadStoreInstance must be used within UploadStoreProvider");return e}var Je=/* @__PURE__ */new Map,Ze=null;function et({className:e}){/* @__PURE__ */
|
|
16
|
+
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"m20 7l-.95-2.05L17 4l2.05-.95L20 1l.95 2.05L23 4l-2.05.95L20 7ZM8.5 7l-.95-2.05L5.5 4l2.05-.95L8.5 1l.95 2.05L11.5 4l-2.05.95L8.5 7ZM20 18.5l-.95-2.05L17 15.5l2.05-.95l.95-2.05l.95 2.05l2.05.95l-2.05.95L20 18.5ZM5.1 21.7l-2.8-2.8q-.3-.3-.3-.725t.3-.725L13.45 6.3q.3-.3.725-.3t.725.3l2.8 2.8q.3.3.3.725t-.3.725L6.55 21.7q-.3.3-.725.3t-.725-.3Zm9.075-10.475l1.4-1.4l-1.4-1.4l-1.4 1.4l1.4 1.4Z"})})}function tt({className:e}){/* @__PURE__ */
|
|
17
|
+
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"m19.55 6.025l-.5-1.075l-1.075-.5Q17.7 4.325 17.7 4t.275-.45l1.075-.5l.5-1.075q.125-.275.45-.275t.45.275l.5 1.075l1.075.5q.275.125.275.45t-.275.45l-1.075.5l-.5 1.075q-.125.275-.45.275t-.45-.275Zm-4 6.675L11.3 8.45l2.15-2.15q.3-.3.725-.3t.725.3l2.8 2.8q.3.3.3.725t-.3.725l-2.15 2.15Zm3.55 9.2l-6.4-6.35l-6.15 6.15q-.3.3-.725.3t-.725-.3l-2.8-2.85q-.275-.275-.275-.7t.275-.7l6.15-6.15L2.1 4.9q-.3-.3-.3-.7t.3-.7q.275-.275.7-.275t.7.275l17 17q.275.275.275.7t-.275.7q-.3.3-.7.3t-.7-.3Z"})})}function rt({className:e}){/* @__PURE__ */
|
|
18
|
+
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M10 21H5q-.825 0-1.412-.587T3 19V5q0-.825.588-1.412T5 3h5V2q0-.425.288-.712T11 1t.713.288T12 2v20q0 .425-.288.713T11 23t-.712-.288T10 22zm-5-3h5v-6zm9 3v-9l5 6V5h-5V3h5q.825 0 1.413.588T21 5v14q0 .825-.587 1.413T19 21z"})})}function it({className:e}){/* @__PURE__ */
|
|
19
|
+
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"m12 14l-2.35 2.35q.2.375.275.8T10 18q0 1.65-1.175 2.825T6 22t-2.825-1.175T2 18t1.175-2.825T6 14q.425 0 .85.075t.8.275L10 12L7.65 9.65q-.375.2-.8.275T6 10q-1.65 0-2.825-1.175T2 6t1.175-2.825T6 2t2.825 1.175T10 6q0 .425-.075.85t-.275.8L20.6 18.6q.675.675.3 1.538T19.575 21q-.275 0-.537-.112t-.463-.313zm3-3l-2-2l5.575-5.575q.2-.2.463-.312T19.574 3q.95 0 1.313.875t-.313 1.55zM7.413 7.413Q8 6.825 8 6t-.587-1.412T6 4t-1.412.588T4 6t.588 1.413T6 8t1.413-.587m4.937 4.937q.15-.15.15-.35t-.15-.35t-.35-.15t-.35.15t-.15.35t.15.35t.35.15t.35-.15m-4.937 7.063Q8 18.825 8 18t-.587-1.412T6 16t-1.412.588T4 18t.588 1.413T6 20t1.413-.587"})})}function nt({className:e}){/* @__PURE__ */
|
|
20
|
+
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M17 22v-3H7q-.825 0-1.412-.587T5 17V7H2q-.425 0-.712-.288T1 6t.288-.712T2 5h3V2q0-.425.288-.712T6 1t.713.288T7 2v15h15q.425 0 .713.288T23 18t-.288.713T22 19h-3v3q0 .425-.288.713T18 23t-.712-.288T17 22m0-7V7H9V5h8q.825 0 1.413.588T19 7v8z"})})}function ot({className:e}){/* @__PURE__ */
|
|
21
|
+
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M6 22q-.825 0-1.412-.587T4 20V4q0-.825.588-1.412T6 2h7.175q.4 0 .763.15t.637.425l4.85 4.85q.275.275.425.638t.15.762V20q0 .825-.587 1.413T18 22zm7-14q0 .425.288.713T14 9h4l-5-5z"})})}function at({className:e}){/* @__PURE__ */
|
|
22
|
+
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M16 19q-.825 0-1.412-.587T14 17V7q0-.825.588-1.412T16 5t1.413.588T18 7v10q0 .825-.587 1.413T16 19m-8 0q-.825 0-1.412-.587T6 17V7q0-.825.588-1.412T8 5t1.413.588T10 7v10q0 .825-.587 1.413T8 19"})})}function st({className:e}){/* @__PURE__ */
|
|
23
|
+
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M8 17.175V6.825q0-.425.3-.713t.7-.287q.125 0 .263.037t.262.113l8.15 5.175q.225.15.338.375t.112.475t-.112.475t-.338.375l-8.15 5.175q-.125.075-.262.113T9 18.175q-.4 0-.7-.288t-.3-.712"})})}function lt({className:e}){/* @__PURE__ */
|
|
24
|
+
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M16.775 19.575q-.275.175-.55.325t-.575.275q-.375.175-.762 0t-.538-.575q-.15-.375.038-.737t.562-.538q.1-.05.188-.1t.187-.1L12 14.8v2.775q0 .675-.612.938T10.3 18.3L7 15H4q-.425 0-.712-.288T3 14v-4q0-.425.288-.712T4 9h2.2L2.1 4.9q-.275-.275-.275-.7t.275-.7t.7-.275t.7.275l17 17q.275.275.275.7t-.275.7t-.7.275t-.7-.275zm2.225-7.6q0-2.075-1.1-3.787t-2.95-2.563q-.375-.175-.55-.537t-.05-.738q.15-.4.538-.575t.787 0Q18.1 4.85 19.55 7.05T21 11.975q0 .825-.15 1.638t-.425 1.562q-.2.55-.612.688t-.763.012t-.562-.45t-.013-.75q.275-.65.4-1.312T19 11.975m-4.225-3.55Q15.6 8.95 16.05 10t.45 2v.25q0 .125-.025.25q-.05.325-.35.425t-.55-.15L14.3 11.5q-.15-.15-.225-.337T14 10.775V8.85q0-.3.263-.437t.512.012M9.75 6.95Q9.6 6.8 9.6 6.6t.15-.35l.55-.55q.475-.475 1.087-.213t.613.938V8q0 .35-.3.475t-.55-.125z"})})}function dt({className:e}){/* @__PURE__ */
|
|
25
|
+
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M19 11.975q0-2.075-1.1-3.787t-2.95-2.563q-.375-.175-.55-.537t-.05-.738q.15-.4.538-.575t.787 0Q18.1 4.85 19.55 7.063T21 11.974t-1.45 4.913t-3.875 3.287q-.4.175-.788 0t-.537-.575q-.125-.375.05-.737t.55-.538q1.85-.85 2.95-2.562t1.1-3.788M7 15H4q-.425 0-.712-.288T3 14v-4q0-.425.288-.712T4 9h3l3.3-3.3q.475-.475 1.088-.213t.612.938v11.15q0 .675-.612.938T10.3 18.3zm9.5-3q0 1.05-.475 1.988t-1.25 1.537q-.25.15-.513.013T14 15.1V8.85q0-.3.263-.437t.512.012q.775.625 1.25 1.575t.475 2"})})}function ct({className:e}){/* @__PURE__ */
|
|
26
|
+
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M6 18H4q-.425 0-.712-.288T3 17t.288-.712T4 16h3q.425 0 .713.288T8 17v3q0 .425-.288.713T7 21t-.712-.288T6 20zm12 0v2q0 .425-.288.713T17 21t-.712-.288T16 20v-3q0-.425.288-.712T17 16h3q.425 0 .713.288T21 17t-.288.713T20 18zM6 6V4q0-.425.288-.712T7 3t.713.288T8 4v3q0 .425-.288.713T7 8H4q-.425 0-.712-.288T3 7t.288-.712T4 6zm12 0h2q.425 0 .713.288T21 7t-.288.713T20 8h-3q-.425 0-.712-.288T16 7V4q0-.425.288-.712T17 3t.713.288T18 4z"})})}function ut({className:e}){/* @__PURE__ */
|
|
27
|
+
return h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M5 19h2q.425 0 .713.288T8 20t-.288.713T7 21H4q-.425 0-.712-.288T3 20v-3q0-.425.288-.712T4 16t.713.288T5 17zm14 0v-2q0-.425.288-.712T20 16t.713.288T21 17v3q0 .425-.288.713T20 21h-3q-.425 0-.712-.288T16 20t.288-.712T17 19zM5 5v2q0 .425-.288.713T4 8t-.712-.288T3 7V4q0-.425.288-.712T4 3h3q.425 0 .713.288T8 4t-.288.713T7 5zm14 0h-2q-.425 0-.712-.288T16 4t.288-.712T17 3h3q.425 0 .713.288T21 4v3q0 .425-.288.713T20 8t-.712-.288T19 7z"})})}function ht({filters:e,overrides:t,onChange:r}){const i=e.flatMap(e=>{const t=e.config.adjustableKeys;if(!t?.length||!e.config.templateId)return[];const r=Se(e.config.templateId);return r?r.variableSchema.filter(e=>t.includes(e.key)).map(t=>({filterId:e.id,filterName:e.name,v:t})):[]});return 0===i.length?null:/* @__PURE__ */h("div",{className:"space-y-4",children:i.map(({filterId:e,filterName:n,v:o})=>{const a=t?.[e]?.[o.key]??o.default;/* @__PURE__ */
|
|
28
|
+
return h("div",{className:"space-y-1",children:[
|
|
29
|
+
/* @__PURE__ */h("label",{className:"flex items-center justify-between text-sm",children:[/* @__PURE__ */h("span",{children:[o.label,i.length>1&&/* @__PURE__ */h("span",{className:"text-muted-foreground ml-1 text-xs",children:["(",n,")"]})]}),/* @__PURE__ */h("span",{className:"text-muted-foreground",children:String(a)})]}),"number"===o.type&&/* @__PURE__ */h("input",{type:"range",className:"w-full",value:a,min:o.min,max:o.max,step:o.step,onInput:t=>r(e,o.key,parseFloat(t.target.value))}),"boolean"===o.type&&/* @__PURE__ */h("input",{type:"checkbox",checked:a,onChange:t=>r(e,o.key,t.target.checked)})]},`${e}:${o.key}`)})})}var pt=o(()=>import("./CFnGGYmq.js").then(e=>({default:e.ReactCompareSlider})));function mt({open:e,onClose:t,file:r,filters:n,isVideo:o,trimRange:s,overrides:d,onOverrideChange:c}){const[p,m]=l(),[f,v]=l(),[b,y]=l(!0),[w,x]=l(!1),[S,T]=l(!1),[C,F]=l(),[k,_]=l(0),[E,U]=l(!1),[R,I]=l(null),[N,O]=l(null),[P,q]=l(!1),[A,L]=l(!0),[j,z]=l(!0),$=a(null),H=a(!1),G=a([]),Y=a(null),K=a(null),J=a(null),Z=a(n);Z.current=n,i(()=>()=>{G.current.forEach(e=>URL.revokeObjectURL(e))},[]);const ee=()=>{document.fullscreenElement?document.exitFullscreen():$.current?.requestFullscreen()};i(()=>{const e=()=>U(!!document.fullscreenElement);return document.addEventListener("fullscreenchange",e),()=>document.removeEventListener("fullscreenchange",e)},[]),i(()=>{q(!!R&&!!N)},[R,N]),i(()=>{R&&(R.muted=A)},[R,A]),i(()=>{if(!e||o)return;let t=!1;return H.current?x(!0):y(!0),T(!1),(async()=>{const e=await D(r),i=await createImageBitmap(e),o=Math.min(1,1600/Math.max(i.width,i.height)),a=Math.round(i.width*o),s=Math.round(i.height*o),l=new OffscreenCanvas(a,s);if(l.getContext("2d").drawImage(i,0,0,a,s),i.close(),t)return;F(a/s);const d=await l.convertToBlob({type:"image/jpeg",quality:.92});if(t)return;const c=await qe(d,n,1600,"image/jpeg",.92);if(t)return;const u=URL.createObjectURL(d),h=URL.createObjectURL(c.blob);G.current.forEach(e=>URL.revokeObjectURL(e)),G.current=[u,h],m(u),v(h),H.current=!0})().catch(()=>{t||H.current||T(!0)}).finally(()=>{t||(y(!1),x(!1))}),()=>{t=!0}},[e,o,r,n]),i(()=>{if(!e||!o||!P)return;const t=R,i=N;if(!t||!i)return;let n=!1,a=null;const l=URL.createObjectURL(r);y(!0),T(!1),_(0);const d=s?.startTime??0,c=d+5,u=e=>new Promise(t=>{let r=!1;const i=()=>{r||(r=!0,t())};"function"==typeof e.requestVideoFrameCallback?e.requestVideoFrameCallback(i):requestAnimationFrame(i),setTimeout(i,600)}),h=e=>{const t=e.data;for(let r=3;r<t.length;r+=4)if(0!==t[r])return!1;return!0};return t.addEventListener("loadeddata",async()=>{if(n)return;_(15);let e=t.videoWidth||640,r=t.videoHeight||360;const o=Math.min(1,720/Math.max(e,r));e=Math.round(e*o),r=Math.round(r*o),i.width=e,i.height=r,F(e/r);const l=i.getContext("2d",{willReadFrequently:!0});if(!l)return y(!1),void T(!0);if(Math.abs(t.currentTime-d)>.05&&(await new Promise(e=>{const r=()=>{t.removeEventListener("seeked",r),e()};t.addEventListener("seeked",r,{once:!0}),t.currentTime=d}),n))return;_(40);const p=new OffscreenCanvas(e,r),m=p.getContext("2d",{willReadFrequently:!0});let g=null;t.muted=!0;try{await t.play()}catch{}if(n)return;for(let i=0;i<6&&!n;i++){if(await u(t),n)return;if(m.drawImage(t,0,0,e,r),!h(m.getImageData(0,0,e,r))){g=await p.convertToBlob({type:"image/jpeg",quality:.85});break}if(t.paused)break}if(n)return;if(!g)return y(!1),void T(!0);_(60),K.current=g,J.current={w:e,h:r};const f=await Ae(Z.current,g,e,r);if(n)return;if(!f.appliedFilters.length)return y(!1),void T(!0);Y.current=f.transform,_(100),y(!1),H.current=!0;const v=s?Math.min(s.endTime,c):Math.min(t.duration||c,c),b=()=>{if(!n){if(l.drawImage(t,0,0,e,r),Y.current&&l.putImageData(Y.current(l.getImageData(0,0,e,r)),0,0),t.currentTime>=v||t.currentTime<d){const e=()=>{t.removeEventListener("seeked",e),n||(a=t.requestVideoFrameCallback(b))};return t.addEventListener("seeked",e,{once:!0}),void(t.currentTime=d)}a=t.requestVideoFrameCallback(b)}};a=t.requestVideoFrameCallback(b)},{once:!0}),t.src=l,t.load(),()=>{n=!0,null!==a&&t.cancelVideoFrameCallback(a),t.pause(),t.removeAttribute("src"),t.load(),URL.revokeObjectURL(l)}},[e,o,r,s,P]),i(()=>{if(!e||!o||!P)return;if(!K.current||!J.current)return;let t=!1;return x(!0),(async()=>{const{w:e,h:r}=J.current,i=await Ae(n,K.current,e,r);t||i.appliedFilters.length>0&&(Y.current=i.transform)})().catch(()=>{}).finally(()=>{t||x(!1)}),()=>{t=!0}},[e,o,n,P]);const te=E?"100vh":"70vh";/* @__PURE__ */
|
|
30
|
+
return h(X,{open:e,onOpenChange:e=>!e&&t(),children:/* @__PURE__ */h(V,{className:g(E?"max-w-none rounded-none":"max-w-2xl sm:w-2xl"),children:/* @__PURE__ */h("div",{className:"bg-background",children:[/* @__PURE__ */h(B,{className:"flex-row items-center justify-between space-y-0",children:[/* @__PURE__ */h(W,{children:"Compare original & filtered"}),/* @__PURE__ */h(Q,{size:"sm",variant:"ghost","aria-label":E?"Exit fullscreen":"Fullscreen",tooltip:E?"Exit fullscreen":"Fullscreen",icon:/* @__PURE__ */h(E?ct:ut,{}),onClick:ee})]}),/* @__PURE__ */h("div",{ref:$,className:g("relative p-4 pt-0",E&&"bg-background flex h-screen w-screen items-center justify-center p-0"),children:[E&&/* @__PURE__ */h(Q,{size:"sm",variant:"ghost","aria-label":"Exit fullscreen",tooltip:"Exit fullscreen",className:"absolute top-2 right-2 z-30",icon:/* @__PURE__ */h(ct,{}),onClick:ee}),b&&/* @__PURE__ */h("div",{className:"flex h-64 flex-col items-center justify-center gap-2",children:[/* @__PURE__ */h(M,{}),o&&/* @__PURE__ */h("p",{className:"text-muted-foreground text-sm",children:["Generating preview… ",k,"%"]})]}),S&&!b&&/* @__PURE__ */h("div",{className:"text-muted-foreground flex h-64 items-center justify-center text-sm",children:"Couldn't generate preview."}),w&&!b&&!S&&/* @__PURE__ */h("div",{className:"bg-background/90 text-muted-foreground absolute top-16 left-1/2 z-20 flex -translate-x-1/2 items-center gap-1.5 rounded-full px-3 py-1 text-xs shadow",children:[/* @__PURE__ */h(M,{className:"size-3.5"}),"Updating…"]}),!o&&!b&&!S&&p&&f&&/* @__PURE__ */h(u,{fallback:null,children:/* @__PURE__ */h(pt,{style:{width:"100%",maxHeight:te,aspectRatio:C},defaultPosition:50,onlyHandleDraggable:!0,itemOne:/* @__PURE__ */h("div",{className:"relative size-full",children:[/* @__PURE__ */h("img",{alt:"Original",className:"size-full object-contain",src:p}),/* @__PURE__ */h(gt,{position:"left",children:"Original"})]}),itemTwo:/* @__PURE__ */h("div",{className:"relative size-full",children:[/* @__PURE__ */h("img",{alt:"Filtered",className:"size-full object-contain",src:f}),/* @__PURE__ */h(gt,{position:"right",children:"Filtered"})]})})}),o&&/* @__PURE__ */h("div",{className:"relative",style:{visibility:b||S?"hidden":"visible"},children:[/* @__PURE__ */h(u,{fallback:null,children:/* @__PURE__ */h(pt,{style:{width:"100%",maxHeight:te,aspectRatio:C},defaultPosition:50,onlyHandleDraggable:!0,itemOne:/* @__PURE__ */h("div",{className:"relative size-full",children:[/* @__PURE__ */h("video",{ref:I,playsInline:!0,className:"pointer-events-none size-full object-contain"}),/* @__PURE__ */h(gt,{position:"left",children:"Original"})]}),itemTwo:/* @__PURE__ */h("div",{className:"relative size-full",children:[/* @__PURE__ */h("canvas",{ref:O,className:"size-full object-contain"}),/* @__PURE__ */h(gt,{position:"right",children:"Filtered"})]})})}),/* @__PURE__ */h("div",{className:"bg-background/80 absolute bottom-2 left-1/2 z-20 flex -translate-x-1/2 gap-1 rounded-full p-1 shadow",children:[/* @__PURE__ */h(Q,{size:"sm",variant:"ghost","aria-label":A?"Unmute":"Mute",tooltip:A?"Unmute":"Mute",icon:/* @__PURE__ */h(A?lt:dt,{}),onClick:()=>L(e=>!e)}),/* @__PURE__ */h(Q,{size:"sm",variant:"ghost","aria-label":j?"Pause":"Play",tooltip:j?"Pause":"Play",icon:/* @__PURE__ */h(j?at:st,{}),onClick:()=>{R&&(R.paused?(R.play(),z(!0)):(R.pause(),z(!1)))}})]})]}),c&&!E&&/* @__PURE__ */h("div",{className:"mt-4",children:/* @__PURE__ */h(ht,{filters:n,overrides:d,onChange:c})})]})]})})})}function gt({position:e,children:t}){/* @__PURE__ */
|
|
31
|
+
return h("div",{className:"bg-background/80 text-foreground pointer-events-none absolute bottom-2 z-10 rounded-full px-2 py-0.5 text-[10px] font-semibold shadow "+("left"===e?"left-2":"right-2"),children:t})}var ft=(e,t,r)=>Math.min(Math.max(e,t),r),vt=e=>Math.max(0,Math.min(100,e)),bt=["nw","ne","sw","se"],yt=({open:e,onClose:t,imageSrc:r,outputSrc:i,aspectRatio:n,initialCrop:o,onCropComplete:s,title:d})=>{const c=a(null),[u,m]=l(null),[g,f]=l(!1),v=a(null),b=p((e,t)=>{const r=c.current.getBoundingClientRect();return{px:Math.min(Math.max(e-r.left,0),r.width),py:Math.min(Math.max(t-r.top,0),r.height)}},[]),y=p(e=>{const t=v.current,r=c.current;var i,o,a,s,l;if(t&&r)if("move"===t.mode)m((i=t.start,o=e.clientX-t.clientX,a=e.clientY-t.clientY,s=r.width,l=r.height,{...i,x:ft(i.x+o,0,s-i.w),y:ft(i.y+a,0,l-i.h)}));else{const{px:i,py:o}=b(e.clientX,e.clientY);m(function(e,t,r,i,n,o,a){const s=t.includes("e")?1:-1,l=t.includes("s")?1:-1,d=s>0?e.x:e.x+e.w,c=l>0?e.y:e.y+e.h,u=s>0?n-d:d,h=l>0?o-c:c;let p=ft((r-d)*s,20,u),m=ft((i-c)*l,20,h);return a&&(m=p/a,m<20&&(m=20,p=m*a),m>h&&(m=h,p=m*a),p>u&&(p=u,m=p/a)),{x:s>0?d:d-p,y:l>0?c:c-m,w:p,h:m}}(t.start,t.corner,i,o,r.width,r.height,n))}},[n,b]),w=p(()=>{v.current=null,window.removeEventListener("pointermove",y),window.removeEventListener("pointerup",w)},[y]),x=(e,t)=>r=>{u&&(r.preventDefault(),r.stopPropagation(),v.current={mode:e,corner:t,start:u,clientX:r.clientX,clientY:r.clientY},window.addEventListener("pointermove",y),window.addEventListener("pointerup",w))},S=p(()=>{m(null),t()},[t]),T=e=>({position:"absolute",width:"14px",height:"14px",background:"#fff",border:"1px solid rgba(0,0,0,.4)",borderRadius:"2px",touchAction:"none",cursor:`${e}-resize`,...e.includes("n")?{top:"-7px"}:{bottom:"-7px"},...e.includes("w")?{left:"-7px"}:{right:"-7px"}});/* @__PURE__ */
|
|
30
32
|
return h(X,{open:e,onOpenChange:S,children:/* @__PURE__ */h(V,{className:"flex h-[90vh] min-w-xl flex-col overflow-hidden p-0",children:[
|
|
31
33
|
/* @__PURE__ */h("div",{className:"bg-background shrink-0",children:/* @__PURE__ */h(B,{children:[/* @__PURE__ */h(W,{children:d||"Crop Image"}),/* @__PURE__ */h(G,{className:"sr-only",children:"Drag the box to move it, or drag a corner to resize."})]})}),
|
|
32
|
-
/* @__PURE__ */h("div",{className:"flex max-h-[50vh] min-h-0 flex-1 items-center justify-center overflow-hidden bg-black",children:/* @__PURE__ */h("div",{style:{position:"relative",display:"inline-block",lineHeight:0,touchAction:"none"},children:[/* @__PURE__ */h("img",{ref:c,src:r,alt:"Crop preview",draggable:!1,onLoad:()=>{const e=c.current;e&&m(o?{x:o.x/100*e.width,y:o.y/100*e.height,w:o.width/100*e.width,h:o.height/100*e.height}:function(e,t,r){let i=.9*e,n=.9*t;return r&&(n=i/r,n>.9*t&&(n=.9*t,i=n*r)),{x:(e-i)/2,y:(t-n)/2,w:i,h:n}}(e.width,e.height,n))},style:{display:"block",maxWidth:"100%",maxHeight:"50vh",width:"auto",height:"auto",userSelect:"none"}}),u&&/* @__PURE__ */h("div",{onPointerDown:x("move"),style:{position:"absolute",left:`${u.x}px`,top:`${u.y}px`,width:`${u.w}px`,height:`${u.h}px`,border:"1px dashed rgba(255,255,255,.9)",boxShadow:"0 0 0 9999px rgba(0,0,0,.5)",cursor:"move",touchAction:"none",boxSizing:"border-box"},children:
|
|
33
|
-
/* @__PURE__ */h("div",{className:"border-border bg-background shrink-0 border-t",children:/* @__PURE__ */h(H,{children:[/* @__PURE__ */h(
|
|
34
|
+
/* @__PURE__ */h("div",{className:"flex max-h-[50vh] min-h-0 flex-1 items-center justify-center overflow-hidden bg-black",children:/* @__PURE__ */h("div",{style:{position:"relative",display:"inline-block",lineHeight:0,touchAction:"none"},children:[/* @__PURE__ */h("img",{ref:c,src:r,alt:"Crop preview",draggable:!1,onLoad:()=>{const e=c.current;e&&m(o?{x:o.x/100*e.width,y:o.y/100*e.height,w:o.width/100*e.width,h:o.height/100*e.height}:function(e,t,r){let i=.9*e,n=.9*t;return r&&(n=i/r,n>.9*t&&(n=.9*t,i=n*r)),{x:(e-i)/2,y:(t-n)/2,w:i,h:n}}(e.width,e.height,n))},style:{display:"block",maxWidth:"100%",maxHeight:"50vh",width:"auto",height:"auto",userSelect:"none"}}),u&&/* @__PURE__ */h("div",{onPointerDown:x("move"),style:{position:"absolute",left:`${u.x}px`,top:`${u.y}px`,width:`${u.w}px`,height:`${u.h}px`,border:"1px dashed rgba(255,255,255,.9)",boxShadow:"0 0 0 9999px rgba(0,0,0,.5)",cursor:"move",touchAction:"none",boxSizing:"border-box"},children:bt.map(e=>/* @__PURE__ */h("div",{onPointerDown:x("resize",e),style:T(e)},e))})]})}),
|
|
35
|
+
/* @__PURE__ */h("div",{className:"border-border bg-background shrink-0 border-t",children:/* @__PURE__ */h(H,{children:[/* @__PURE__ */h(P,{variant:"outlined",onClick:S,disabled:g,children:"Cancel"}),/* @__PURE__ */h(P,{onClick:async()=>{const e=c.current;var t;if(u&&e)try{f(!0);const n=i&&i!==r?await(t=i,new Promise((e,r)=>{const i=new Image;i.onload=()=>e(i),i.onerror=()=>r(/* @__PURE__ */new Error("Failed to load image")),i.src=t})):e,o=u.x/e.width,a=u.y/e.height,l=u.w/e.width,d=u.h/e.height,c={x:Math.round(o*n.naturalWidth),y:Math.round(a*n.naturalHeight),w:Math.round(l*n.naturalWidth),h:Math.round(d*n.naturalHeight)},h={unit:"%",x:vt(100*o),y:vt(100*a),width:vt(100*l),height:vt(100*d)};s(await function(e,t){const r=document.createElement("canvas");r.width=t.w,r.height=t.h;const i=r.getContext("2d");return i?(i.drawImage(e,t.x,t.y,t.w,t.h,0,0,t.w,t.h),new Promise((e,t)=>{r.toBlob(r=>{r?e(r):t(/* @__PURE__ */new Error("Canvas is empty"))},"image/jpeg",.95)})):Promise.reject(/* @__PURE__ */new Error("Failed to get canvas context"))}(n,c),h),S()}catch(n){de(n instanceof Error?n:new Error(String(n)),{component:"ImageCropDialog",tags:["upload","crop"]})}finally{f(!1)}},loading:g,disabled:g||!u,children:"Crop"})]})})]})})},wt=({open:e,onClose:t,videoFile:r,activeFilters:n,onTrimComplete:o,title:s="Select 60 Second Clip"})=>{const d=a(null),c=a(null),u=a(null),m=n?.filter(e=>e.enabled)??[],g=m.length>0,[f,v]=l(0),[b,y]=l(0),[w,x]=l(60),[S,T]=l(0),[C,F]=l(!1),[k,_]=l(!1),[E,M]=l(null),[U,R]=l(null),[I,N]=l(0),[O,q]=l({start:0,end:0});i(()=>{if(r&&e){const e=URL.createObjectURL(r);return M(e),()=>URL.revokeObjectURL(e)}},[r,e]),i(()=>{if(!E||!g)return;const e=d.current,t=c.current;if(!e||!t||!e.requestVideoFrameCallback)return;let r=!1,i=null,n=!1;if(i=e.requestVideoFrameCallback(()=>{(async()=>{if(n||r||!e.videoWidth)return;n=!0;const o=Math.min(1,640/Math.max(e.videoWidth,e.videoHeight)),a=Math.max(1,Math.round(e.videoWidth*o)),s=Math.max(1,Math.round(e.videoHeight*o));t.width=a,t.height=s;const l=t.getContext("2d",{willReadFrequently:!0});if(!l)return;const d=document.createElement("canvas");d.width=a,d.height=s,d.getContext("2d")?.drawImage(e,0,0,a,s);const c=await new Promise(e=>d.toBlob(e,"image/jpeg",.85));if(r||!c)return;const u=await Ae(m,c,a,s);if(r||!u.appliedFilters.length)return;const h=u.transform,p=()=>{r||(l.drawImage(e,0,0,a,s),l.putImageData(h(l.getImageData(0,0,a,s)),0,0),i=e.requestVideoFrameCallback(p))};p()})()}),e.readyState>=2&&e.paused)try{e.currentTime=e.currentTime+.001}catch{}return()=>{r=!0,null!==i&&e.cancelVideoFrameCallback?.(i)}},[E,g,JSON.stringify(n)]);const A=p(e=>{if(!u.current||0===f)return 0;const t=u.current.getBoundingClientRect();return Math.max(0,Math.min(1,(e-t.left)/t.width))*f},[f]),D=p(e=>0===f?0:e/f*100,[f]),L=(e,t)=>{e.preventDefault(),e.stopPropagation(),R(t),N(e.clientX),q({start:b,end:w})},j=(e,t)=>{e.stopPropagation();const r=e.touches[0];R(t),N(r?.clientX??0),q({start:b,end:w})};i(()=>{if(!U||!u.current)return;const e=e=>{const t=u.current.getBoundingClientRect(),r=(e-I)/t.width*f;if("start"===U){let e=Math.max(0,O.start+r);e=Math.min(e,w-1),w-e>60&&(e=w-60),y(e),d.current&&(d.current.currentTime=e)}else if("end"===U){let e=Math.min(f,O.end+r);e=Math.max(e,b+1),e-b>60&&(e=b+60),x(e)}else if("range"===U){const e=O.end-O.start;let t=O.start+r,i=O.end+r;t<0&&(t=0,i=e),i>f&&(i=f,t=f-e),y(t),x(i),d.current&&(d.current.currentTime=t)}},t=t=>e(t.clientX),r=t=>e(t.touches[0].clientX),i=()=>R(null);return document.addEventListener("mousemove",t),document.addEventListener("mouseup",i),document.addEventListener("touchmove",r),document.addEventListener("touchend",i),()=>{document.removeEventListener("mousemove",t),document.removeEventListener("mouseup",i),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",i)}},[U,I,O,f,b,w]);const z=()=>{d.current&&(C?d.current.pause():((S<b||S>=w)&&(d.current.currentTime=b),d.current.play()),F(!C))},$=e=>`${Math.floor(e/60)}:${Math.floor(e%60).toString().padStart(2,"0")}`,Y=()=>{y(0),x(60),T(0),F(!1),R(null),d.current&&d.current.pause(),t()},Q=w-b;/* @__PURE__ */
|
|
34
36
|
return h(X,{open:e,onOpenChange:Y,children:/* @__PURE__ */h(V,{className:"max-h-[90vh] max-w-3xl overflow-y-auto p-0",children:[
|
|
35
37
|
/* @__PURE__ */h("div",{className:"bg-background sticky top-0 z-10",children:/* @__PURE__ */h(B,{children:[/* @__PURE__ */h(W,{children:s}),/* @__PURE__ */h(G,{className:"hidden",children:"Review the video preview and choose the start and end times for the clip you want to keep."})]})}),
|
|
36
38
|
/* @__PURE__ */h("div",{className:"space-y-4 p-4",children:[
|
|
@@ -50,36 +52,36 @@ return h(X,{open:e,onOpenChange:Y,children:/* @__PURE__ */h(V,{className:"max-h-
|
|
|
50
52
|
/* @__PURE__ */h("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 flex h-2 justify-between px-0",children:Array.from({length:Math.min(50,Math.ceil(f))}).map((e,t)=>/* @__PURE__ */h("div",{className:"w-px bg-gray-400/30",style:{height:t%5==0?"100%":"50%"}},t))})]}),
|
|
51
53
|
/* @__PURE__ */h("p",{className:"text-muted-foreground text-center text-xs",children:"Drag the handles to adjust selection • Drag the center to move the range • Click to seek"})]}),
|
|
52
54
|
/* @__PURE__ */h("div",{className:"flex items-center justify-center gap-2",children:[
|
|
53
|
-
/* @__PURE__ */h(
|
|
54
|
-
/* @__PURE__ */h(
|
|
55
|
-
/* @__PURE__ */h(
|
|
56
|
-
/* @__PURE__ */h("div",{className:"bg-background border-border sticky bottom-0 border-t",children:/* @__PURE__ */h(H,{children:[/* @__PURE__ */h(
|
|
57
|
-
/* @__PURE__ */h("div",{ref:
|
|
58
|
-
/* @__PURE__ */h("video",{ref:
|
|
59
|
-
/* @__PURE__ */h(Y,{className:"size-4"}),"Exceeds ",
|
|
60
|
-
/* @__PURE__ */h("div",{className:"bg-primary/10 flex size-12 items-center justify-center rounded-full",children:/* @__PURE__ */h(
|
|
61
|
-
/* @__PURE__ */h("div",{className:"relative z-10 rounded-full bg-white/80 px-3 py-1 backdrop-blur-sm dark:bg-black/40",children:/* @__PURE__ */h("span",{className:"text-muted-foreground text-sm font-medium",children:"creating"!==
|
|
55
|
+
/* @__PURE__ */h(P,{variant:"outlined",size:"sm",onClick:()=>{d.current&&(d.current.currentTime=b,T(b))},children:/* @__PURE__ */h("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 24 24",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M6 6h2v12H6zm3.5 6l8.5 6V6z"})})}),
|
|
56
|
+
/* @__PURE__ */h(P,{variant:"outlined",onClick:z,children:/* @__PURE__ */h("svg",C?{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6",viewBox:"0 0 24 24",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M6 19h4V5H6zm8-14v14h4V5z"})}:{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6",viewBox:"0 0 24 24",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M8 5v14l11-7z"})})}),
|
|
57
|
+
/* @__PURE__ */h(P,{variant:"outlined",size:"sm",onClick:()=>{d.current&&(d.current.currentTime=w,T(w))},children:/* @__PURE__ */h("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 24 24",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"m5 18l8.5-6L5 6zm11 0V6h2v12z"})})})]})]}),
|
|
58
|
+
/* @__PURE__ */h("div",{className:"bg-background border-border sticky bottom-0 border-t",children:/* @__PURE__ */h(H,{children:[/* @__PURE__ */h(P,{variant:"outlined",onClick:Y,disabled:k,children:"Cancel"}),/* @__PURE__ */h(P,{onClick:async()=>{_(!0);try{o({startTime:b,endTime:w,duration:w-b}),Y()}catch(e){de(e instanceof Error?e:new Error(String(e)),{component:"VideoTrimDialog",tags:["upload","trim"]})}finally{_(!1)}},loading:k,disabled:k||Q>60,children:"Confirm Selection"})]})})]})})};function xt(e,t){const r=Math.min(1,360/e);return{w:Math.round(e*r),h:Math.round(t*r)}}var St={image:"25 MB",video:"250 MB"},Tt=d(function({uid:e,file:t,onRemove:r,disabled:n,adaRequired:o,onRetry:s}){const d=L(t),u=!d&&q(t),m=Ke(),f=Qe(t=>t.captions[e]),v=Qe(t=>t.oversizedUids[e]),b=Qe(t=>t.uploadStates[e]),y=Qe(t=>t.trimRanges[e]),w=Qe(t=>t.originalFiles[e])??t,x=Qe(e=>e.videoMuted),S=Qe(e=>e.setVideoMuted),T=Qe(e=>e.activeFilters),C=Qe(e=>e.showFilterChoice),F=Qe(e=>e.skipUploadFilters),k=Qe(t=>t.perFileFilterSkipped[e]),_=Qe(t=>t.filteredThumbs[e]),E=Qe(t=>t.filterOverrides[e]),U=c(()=>{return e=T,(t=E)&&0!==Object.keys(t).length?e.map(e=>{const r=t[e.id],i=e.config.adjustableKeys;if(!r||!i?.length)return e;const n=e.config.templateId?Se(e.config.templateId):void 0;if(!n)return e;const o={...e.config.variables};let a=!1;for(const t of i){if(!(t in r))continue;const e=Te(n.variableSchema.find(e=>e.key===t),r[t]);void 0!==e&&(o[t]=e,a=!0)}return a?{...e,config:{...e.config,variables:o}}:e}):e;var e,t},[T,E]),I=!!b,N="success"===b?.status,O="error"===b?.status,P=C&&T.length>0&&!F&&!k,[A,D]=l(!1),[z,B]=l(),[H,V]=l(!1),[W,G]=l(!1),{ref:X,inView:K}=function({rootMargin:e,triggerOnce:t}={}){const r=a(null),[n,o]=l(!1);return i(()=>{const i=r.current;if(!i)return;const n=new IntersectionObserver(e=>{for(const r of e)r.isIntersecting?(o(!0),t&&n.disconnect()):t||o(!1)},{rootMargin:e});return n.observe(i),()=>n.disconnect()},[e,t]),{ref:r,inView:n}}({rootMargin:"200px",triggerOnce:!0}),[Z,ee]=l();i(()=>{if(!u||!K)return;let e,r=!1;return j(t).then(t=>{r?URL.revokeObjectURL(t):(e=t,ee(t))}),()=>{r=!0,e&&URL.revokeObjectURL(e)}},[t,u,K]);const[te,re]=l();i(()=>{if(!u||!A)return;let e,t=!1;return j(w).then(r=>{t?URL.revokeObjectURL(r):(e=r,re(r))}),()=>{t=!0,e&&URL.revokeObjectURL(e),re(void 0)}},[w,u,A]);const[ie,ne]=l();i(()=>{if(!u||!A||!P)return void ne(void 0);let e=!1;return je(w,U).then(t=>{e||ne(t.processed)}).catch(()=>{}),()=>{e=!0}},[u,A,P,w,U]);const oe=a(null),ae=a(null),se=a(null),le=a(0),de=a(null),[ce,ue]=l(!1),[he,pe]=l(!1),[me,ve]=l(null),[be,ye]=l(null),we=p(()=>{const e=oe.current;if(!e||se.current)return;const r=URL.createObjectURL(t);se.current=r,e.src=r,e.load()},[t]),xe=p(()=>{const e=oe.current;e&&(e.removeAttribute("src"),e.load()),se.current&&(URL.revokeObjectURL(se.current),se.current=null)},[]),Ce=p(()=>{const e=oe.current;if(!e||!e.videoWidth)return;const t=Math.min(1,640/e.videoWidth),r=document.createElement("canvas");r.width=e.videoWidth*t,r.height=e.videoHeight*t;const i=r.getContext("2d");i&&(i.drawImage(e,0,0,r.width,r.height),ve(r.toDataURL("image/jpeg",.85)))},[]),Fe=p(()=>{const t=oe.current,r=ae.current;if(!t||!r||!t.videoWidth)return!1;const{w:i,h:n}=xt(t.videoWidth,t.videoHeight),o=He(Be(e,U,i,n));if(!o)return!1;r.width=i,r.height=n;const a=r.getContext("2d");return!!a&&(a.drawImage(t,0,0,i,n),a.putImageData(o.transform(a.getImageData(0,0,i,n)),0,0),!0)},[e,U]),ke=p(()=>{de.current&&(clearTimeout(de.current),de.current=null)},[]),_e=p(()=>{const t=oe.current;if(t&&(le.current=t.currentTime),Ce(),P){const e=Fe();pe(e),e&&ae.current&&ye(ae.current.toDataURL("image/jpeg",.85))}ue(!1),function(e){Ze===e&&(Ze=null)}(e),ke(),de.current=setTimeout(()=>{xe(),de.current=null},200)},[e,Ce,Fe,P,xe,ke]),Ee=p(()=>{const t=oe.current;if(!t)return;if(ce)return void t.pause();!function(e){Ze&&Ze!==e&&Je.get(Ze)?.(),Ze=e}(e),ke(),we();const r=le.current||y?.startTime||0,i=()=>{t.currentTime=r,t.play().catch(()=>{})};t.readyState>=1?i():t.addEventListener("loadedmetadata",i,{once:!0})},[ce,we,y,e,ke]);return i(()=>{if(!d)return;const t=function(e){return Je.set(e,()=>oe.current?.pause()),()=>{Je.delete(e),Ze===e&&(Ze=null)}}(e);return()=>{t(),ke(),xe()}},[d,e,xe,ke]),i(()=>{H&&oe.current?.pause()},[H]),i(()=>{I&&oe.current?.pause()},[I]),i(()=>{le.current=0},[y]),i(()=>{pe(!1)},[P,U,e]),i(()=>{oe.current&&(oe.current.muted=x)},[x]),i(()=>{if(!d||!K)return;let e=!1,r=null,i=null;const n=()=>{i&&(i.pause(),i.removeAttribute("src"),i.load(),i=null),r&&(URL.revokeObjectURL(r),r=null)};return ge(async()=>{if(!e)try{if(r=URL.createObjectURL(t),i=document.createElement("video"),i.preload="metadata",i.muted=!0,i.playsInline=!0,await new Promise((e,t)=>{if(!i)return t(/* @__PURE__ */new Error("no probe"));const n=()=>{i?.removeEventListener("loadedmetadata",n),i?.removeEventListener("error",o),e()},o=()=>{i?.removeEventListener("loadedmetadata",n),i?.removeEventListener("error",o),t(/* @__PURE__ */new Error("video load error"))};i.addEventListener("loadedmetadata",n),i.addEventListener("error",o),i.src=r,i.load()}),e||!i)return;const n=Math.min(.5,.05*(i.duration||0)||.1);if(await new Promise((e,t)=>{if(!i)return t(/* @__PURE__ */new Error("no probe"));const r=()=>{i?.removeEventListener("seeked",r),i?.removeEventListener("error",o),e()},o=()=>{i?.removeEventListener("seeked",r),i?.removeEventListener("error",o),t(/* @__PURE__ */new Error("video seek error"))};i.addEventListener("seeked",r),i.addEventListener("error",o),i.currentTime=n}),e||!i)return;const o=document.createElement("canvas"),a=i.videoWidth||640,s=i.videoHeight||360,l=Math.min(1,640/a);o.width=a*l,o.height=s*l;const d=o.getContext("2d");if(!d)return;d.drawImage(i,0,0,o.width,o.height),ve(o.toDataURL("image/jpeg",.85))}catch{}finally{n()}}).catch(()=>{}),()=>{e=!0,n()}},[d,K,t]),i(()=>{if(!u||!K||!P||_)return;let r=!1;return fe(()=>je(t,U)).then(t=>{!r&&t.appliedFilters.length&&m.getState().setFilteredThumb(e,t.processed)}).catch(()=>{}),()=>{r=!0}},[u,K,P,_,t,U,m,e]),i(()=>{if(!d||!me||!P||_)return;let t=!1;return fe(async()=>{const t=await fetch(me).then(e=>e.blob()),r=await createImageBitmap(t),{w:i,h:n}=xt(r.width,r.height),o=Be(e,U,i,n);let a=He(o);if(a||(a=await Ae(U,t,i,n),a.appliedFilters.length&&Ve(o,a)),!a.appliedFilters.length)return r.close(),null;const s=new OffscreenCanvas(i,n),l=s.getContext("2d");return l.drawImage(r,0,0,i,n),r.close(),l.putImageData(a.transform(l.getImageData(0,0,i,n)),0,0),s.convertToBlob({type:"image/jpeg",quality:.85})}).then(r=>{if(t||!r)return;const i=new FileReader;i.onload=()=>{t||m.getState().setFilteredThumb(e,i.result)},i.readAsDataURL(r)}).catch(()=>{}),()=>{t=!0}},[d,me,P,_,U,m,e]),i(()=>{if(!(d&&ce&&P&&me))return;const t=oe.current,r=ae.current;if(!t||!r)return;let i=!1,n=null;return(async()=>{if(!t.videoWidth)return;const{w:o,h:a}=xt(t.videoWidth,t.videoHeight);r.width=o,r.height=a;const s=r.getContext("2d");if(!s)return;const l=Be(e,U,o,a);let d=He(l);if(!d){const e=await fetch(me).then(e=>e.blob());if(i)return;if(d=await Ae(U,e,o,a),i||!d.appliedFilters.length)return;Ve(l,d)}const c=d.transform,u=y?.startTime??0,h=Number.isFinite(t.duration)?t.duration:1/0,p=Math.min(y?.endTime??1/0,h);let m=!1;const g=()=>{if(!i){if(s.drawImage(t,0,0,o,a),s.putImageData(c(s.getImageData(0,0,o,a)),0,0),m||(m=!0,pe(!0)),t.currentTime>=p||t.currentTime<u){const e=()=>{t.removeEventListener("seeked",e),i||(n=t.requestVideoFrameCallback(g))};return t.addEventListener("seeked",e,{once:!0}),void(t.currentTime=u)}n=t.requestVideoFrameCallback(g)}};n=t.requestVideoFrameCallback(g)})().catch(()=>{}),()=>{i=!0,null!==n&&t.cancelVideoFrameCallback(n)}},[d,ce,P,me,U,y,e]),i(()=>{if(!d||ce||!P||!me)return;let e=!1;return(async()=>{const t=await fetch(me).then(e=>e.blob()),r=await je(new File([t],"poster.jpg",{type:"image/jpeg"}),U);e||ye(r.processed)})().catch(()=>{}),()=>{e=!0}},[d,ce,P,me,U]),/* @__PURE__ */h("div",{className:"group relative",children:[
|
|
59
|
+
/* @__PURE__ */h("div",{ref:X,className:g("bg-muted relative h-48 overflow-hidden rounded sm:h-72",v&&"border-destructive border-2"),children:[u&&Z&&/* @__PURE__ */h("img",{src:P&&_?_:Z,alt:t.name,loading:"lazy",decoding:"async",className:"size-full object-contain"}),u&&C&&T.length>0&&!F&&/* @__PURE__ */h(Ct,{applied:P&&!!_}),d&&/* @__PURE__ */h("div",{className:"relative size-full",children:[me&&/* @__PURE__ */h("img",{src:P?be??_??me:me,alt:"",className:g("absolute inset-0 size-full object-contain",ce?"opacity-0":"opacity-100")}),(!ce||P)&&C&&T.length>0&&!F&&/* @__PURE__ */h(Ct,{applied:P&&!!_}),
|
|
60
|
+
/* @__PURE__ */h("video",{ref:oe,muted:x,playsInline:!0,loop:!y,preload:"none",onLoadedMetadata:e=>{y&&(e.currentTarget.currentTime=y.startTime)},onTimeUpdate:e=>{if(!y)return;const t=e.currentTarget;t.currentTime>=y.endTime&&(t.currentTime=y.startTime)},onPlaying:()=>ue(!0),onPause:_e,className:g("size-full object-contain",ce&&!P?"opacity-100":"opacity-0")}),P&&/* @__PURE__ */h("canvas",{ref:ae,className:g("pointer-events-none absolute inset-0 size-full object-contain",ce&&he?"opacity-100":"opacity-0")}),!I&&/* @__PURE__ */h("button",{type:"button","aria-label":ce?"Pause":"Play",onClick:Ee,className:"bg-background/60 absolute top-1/2 left-1/2 z-10 -translate-x-1/2 -translate-y-1/2 rounded-full p-3 backdrop-blur-sm",children:/* @__PURE__ */h(ce?at:st,{className:"text-foreground size-8"})}),!I&&/* @__PURE__ */h("button",{type:"button","aria-label":x?"Unmute videos":"Mute videos",onClick:()=>S(!x),className:"bg-background/60 absolute bottom-2 left-2 z-10 rounded-full p-2 backdrop-blur-sm",children:/* @__PURE__ */h(x?lt:dt,{className:"text-foreground size-5"})}),y&&!I&&/* @__PURE__ */h("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 rounded bg-black/70 px-2 py-1 text-xs text-white",children:["Trimmed: ",(Me=y.endTime-y.startTime,`${Math.floor(Me/60)}:${Math.floor(Me%60).toString().padStart(2,"0")}`)]})]}),!u&&!d&&/* @__PURE__ */h("div",{className:"flex h-full w-full items-center justify-center",children:/* @__PURE__ */h(ot,{className:"text-muted-foreground size-12"})}),v&&/* @__PURE__ */h("div",{className:"bg-destructive/75 absolute inset-x-0 top-0 flex items-center justify-center gap-1 p-2 text-center text-xs font-semibold text-white backdrop-blur-sm",children:[
|
|
61
|
+
/* @__PURE__ */h(Y,{className:"size-4"}),"Exceeds ",St[v]," limit"]}),I&&!N&&!O&&/* @__PURE__ */h("div",{className:"bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-3 backdrop-blur-sm",children:[b.bytesTotal>0&&/* @__PURE__ */h("div",{className:"bg-primary/20 absolute bottom-0 left-0 h-full transition-all duration-300",style:{width:`${Math.round(b.bytesUploaded/b.bytesTotal*100)}%`}}),
|
|
62
|
+
/* @__PURE__ */h("div",{className:"bg-primary/10 flex size-12 items-center justify-center rounded-full",children:/* @__PURE__ */h(M,{className:"size-6"})}),
|
|
63
|
+
/* @__PURE__ */h("div",{className:"relative z-10 rounded-full bg-white/80 px-3 py-1 backdrop-blur-sm dark:bg-black/40",children:/* @__PURE__ */h("span",{className:"text-muted-foreground text-sm font-medium",children:"creating"!==b.status&&"queued"!==b.status&&b.bytesTotal>0?`Uploading ${Math.round(b.bytesUploaded/b.bytesTotal*100)}%`:"Uploading"})})]}),N&&/* @__PURE__ */h("div",{className:"bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-2 p-4 backdrop-blur-sm",children:[/* @__PURE__ */h("div",{className:"bg-success/20 flex size-14 items-center justify-center rounded-full",children:/* @__PURE__ */h(J,{className:"text-success size-8"})}),/* @__PURE__ */h("span",{className:"text-success text-sm font-medium",children:"Uploaded!"})]}),O&&/* @__PURE__ */h("div",{className:"bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-3 p-4 backdrop-blur-sm",children:[
|
|
62
64
|
/* @__PURE__ */h("div",{className:"bg-destructive/20 flex size-14 items-center justify-center rounded-full",children:/* @__PURE__ */h(Y,{className:"text-destructive size-8"})}),
|
|
63
|
-
/* @__PURE__ */h("p",{className:"text-destructive text-center text-xs font-medium",children:
|
|
64
|
-
/* @__PURE__ */h(Q,{size:"sm",variant:"default","aria-label":
|
|
65
|
-
/* @__PURE__ */h("div",{className:"mt-2",children:/* @__PURE__ */h(
|
|
66
|
-
return h("div",{className:g("absolute right-2 bottom-2 z-10 flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-semibold shadow",e?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),children:e?"Filtered":"Original"})}function
|
|
67
|
-
/* @__PURE__ */h("div",{className:"relative min-w-0 flex-1 overflow-hidden",children:[o&&l&&/* @__PURE__ */h("div",{className:"bg-primary/40 absolute inset-y-0 t-0 text-right transition-all duration-300",style:{width:`${l.percent}%`}}),/* @__PURE__ */h("div",{className:"relative flex h-full flex-col justify-center gap-0.5 py-3 pl-3",children:/* @__PURE__ */h("span",o&&l?{className:"text-muted-foreground text-sm font-medium",children:["Uploading",l.failed>0?` · ${l.failed} failed`:""," (",l.percent,"%)"," ",s?/* @__PURE__ */h("span",{className:"text-muted-foreground/70 text-xs",children:["• ",(u=s,u<=0?"":u<1048576?`${(u/1024).toFixed(0)} KB/s`:`${(u/1048576).toFixed(1)} MB/s`)]}):null]}:{className:"text-muted-foreground text-sm font-medium",children:[n," media selected"]})})]}),o&&d&&/* @__PURE__ */h("button",{type:"button",onClick:r,className:"border-primary text-primary hover:bg-primary/10 flex shrink-0 items-center gap-1.5 border px-4 py-2.5 text-sm font-semibold",children:[/* @__PURE__ */h($,{className:"size-4"}),"Retry All"]}),o&&!d&&/* @__PURE__ */h("button",{type:"button",onClick:t,className:"shrink-0 px-2 py-2.5 text-sm font-semibold text-destructive hover:bg-red-50 dark:hover:bg-red-950/20",children:"Cancel"}),!o&&/* @__PURE__ */h("button",{type:"button",onClick:e,disabled:i,className:g("bg-primary text-primary-foreground shrink-0 bg-linear-to-r px-6 py-2.5 text-sm font-semibold transition-all","disabled:cursor-not-allowed disabled:opacity-50"),children:/* @__PURE__ */h("span",{className:"flex items-center gap-2",children:[/* @__PURE__ */h(A,{className:"size-4"}),"Upload"]})})]})});var u}function
|
|
68
|
-
return h("div",{role:"button",tabIndex:0,onClick:()=>!t&&s.current?.click(),onKeyDown:e=>{t||"Enter"!==e.key&&" "!==e.key||s.current?.click()},onDragOver:e=>{e.preventDefault(),t||o(!0)},onDragLeave:()=>o(!1),onDrop:p(e=>{e.preventDefault(),o(!1),t||c(e.dataTransfer?.files??null)},[t,c]),children:[/* @__PURE__ */h("input",{ref:s,type:"file",accept:d,multiple:!0,disabled:t,className:"hidden",onChange:e=>{c(e.target.files),e.target.value=""}}),i({isDragActive:n})]})}function
|
|
69
|
-
return h("div",{className:"mb-6 flex-auto",children:/* @__PURE__ */h("div",{className:"flex w-full justify-center",children:/* @__PURE__ */h(
|
|
65
|
+
/* @__PURE__ */h("p",{className:"text-destructive text-center text-xs font-medium",children:b?.error??"Upload failed"}),s&&/* @__PURE__ */h("button",{type:"button",onClick:()=>s(e),className:"border-destructive text-destructive hover:bg-destructive/10 flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-semibold",children:[/* @__PURE__ */h($,{className:"size-3.5"}),"Retry"]})]})]}),!n&&/* @__PURE__ */h(Q,{size:"sm",color:"error",variant:"default",className:"absolute top-3 right-3","aria-label":"Remove file",icon:/* @__PURE__ */h(R,{}),onClick:()=>r(e)}),!n&&(u||d)&&/* @__PURE__ */h("div",{className:"absolute top-3 left-3 flex gap-2",children:[
|
|
66
|
+
/* @__PURE__ */h(Q,{size:"sm",variant:"default","aria-label":u?"Crop image":"Trim video",icon:/* @__PURE__ */h(u?nt:it,{}),onClick:()=>u?D(!0):V(!0)}),C&&T.length>0&&!F&&/* @__PURE__ */h(Q,{size:"sm",variant:"default","aria-label":k?"Apply filter":"Skip filter",tooltip:k?"Apply filter":"Skip filter",icon:/* @__PURE__ */h(k?et:tt,{}),onClick:()=>m.getState().setFileFilterSkipped(e,!k)}),C&&T.length>0&&!F&&!k&&/* @__PURE__ */h(Q,{size:"sm",variant:"default","aria-label":"Compare original and filtered",tooltip:"Compare original and filtered",icon:/* @__PURE__ */h(rt,{}),onClick:()=>{Ze&&(Je.get(Ze)?.(),Ze=null),G(!0)}})]}),u&&te&&/* @__PURE__ */h(yt,{open:A,onClose:()=>D(!1),imageSrc:P&&ie?ie:te,outputSrc:te,title:"Crop Image",initialCrop:z,onCropComplete:(r,i)=>{const n=new File([r],t.name,{type:r.type});B(i),m.getState().replaceFile(e,n,i)}}),d&&H&&/* @__PURE__ */h(wt,{open:H,onClose:()=>V(!1),videoFile:t,activeFilters:P?U:void 0,title:"Select Clip",onTrimComplete:({startTime:t,endTime:r})=>m.getState().setTrimRange(e,{startTime:t,endTime:r})}),W&&/* @__PURE__ */h(mt,{open:W,onClose:()=>G(!1),file:t,filters:U,isVideo:d,trimRange:y,overrides:E,onOverrideChange:(t,r,i)=>m.getState().setFilterOverride(e,t,r,i)}),
|
|
67
|
+
/* @__PURE__ */h("div",{className:"mt-2",children:/* @__PURE__ */h(ze,{placeholder:o?"Caption (required)":"Caption",value:f??"",onInput:t=>m.getState().setCaption(e,t.target.value),disabled:n,error:o&&!f?.trim()?" ":void 0,className:"text-xs"})})]});var Me});function Ct({applied:e}){/* @__PURE__ */
|
|
68
|
+
return h("div",{className:g("absolute right-2 bottom-2 z-10 flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-semibold shadow",e?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),children:e?"Filtered":"Original"})}function Ft({onUpload:e,onCancel:t,onRetryAll:r,uploadDisabled:i,selectedCount:n}){const o=Qe(e=>e.hasStarted),a=Qe(e=>e.uploadStates),s=Qe(e=>e.uploadSpeedBps),l=c(()=>{const e=Object.values(a);if(0===e.length)return null;const t=e.filter(e=>"success"===e.status).length,r=e.filter(e=>"error"===e.status).length,i=e.reduce((e,t)=>e+(t.bytesTotal||0),0),n=e.reduce((e,t)=>e+("success"===t.status?t.bytesTotal||0:t.bytesUploaded||0),0),o=i>0?Math.round(n/i*100):0,s=e.length;return{succeeded:t,failed:r,percent:o,total:s,allDone:t+r>=s}},[a]),d=!!(o&&l&&l.allDone&&l.failed>0);return 0===n?null:/* @__PURE__ */h("div",{className:"bg-background/85 fixed right-0 bottom-0 left-0 z-2002 overflow-hidden backdrop-blur-sm",children:/* @__PURE__ */h("div",{className:"relative flex items-stretch gap-3",children:[
|
|
69
|
+
/* @__PURE__ */h("div",{className:"relative min-w-0 flex-1 overflow-hidden",children:[o&&l&&/* @__PURE__ */h("div",{className:"bg-primary/40 absolute inset-y-0 t-0 text-right transition-all duration-300",style:{width:`${l.percent}%`}}),/* @__PURE__ */h("div",{className:"relative flex h-full flex-col justify-center gap-0.5 py-3 pl-3",children:/* @__PURE__ */h("span",o&&l?{className:"text-muted-foreground text-sm font-medium",children:["Uploading",l.failed>0?` · ${l.failed} failed`:""," (",l.percent,"%)"," ",s?/* @__PURE__ */h("span",{className:"text-muted-foreground/70 text-xs",children:["• ",(u=s,u<=0?"":u<1048576?`${(u/1024).toFixed(0)} KB/s`:`${(u/1048576).toFixed(1)} MB/s`)]}):null]}:{className:"text-muted-foreground text-sm font-medium",children:[n," media selected"]})})]}),o&&d&&/* @__PURE__ */h("button",{type:"button",onClick:r,className:"border-primary text-primary hover:bg-primary/10 flex shrink-0 items-center gap-1.5 border px-4 py-2.5 text-sm font-semibold",children:[/* @__PURE__ */h($,{className:"size-4"}),"Retry All"]}),o&&!d&&/* @__PURE__ */h("button",{type:"button",onClick:t,className:"shrink-0 px-2 py-2.5 text-sm font-semibold text-destructive hover:bg-red-50 dark:hover:bg-red-950/20",children:"Cancel"}),!o&&/* @__PURE__ */h("button",{type:"button",onClick:e,disabled:i,className:g("bg-primary text-primary-foreground shrink-0 bg-linear-to-r px-6 py-2.5 text-sm font-semibold transition-all","disabled:cursor-not-allowed disabled:opacity-50"),children:/* @__PURE__ */h("span",{className:"flex items-center gap-2",children:[/* @__PURE__ */h(A,{className:"size-4"}),"Upload"]})})]})});var u}function kt({enabledFileTypes:e,disabled:t,onFileSelect:r,children:i}){const[n,o]=l(!1),s=a(null),d=function(e){const t=e.filter(e=>ie.includes(e)),r=e.filter(e=>ne.includes(e)),i=[];return t.length>0&&i.push("image/*",...t.map(e=>`.${e}`)),r.length>0&&i.push("video/*",...r.map(e=>`.${e}`)),i.join(",")}(e),c=p(t=>{if(!t)return;const i=Array.from(t).filter(t=>function(e,t){const r=e.name.lastIndexOf("."),i=r>0&&r<e.name.length-1?e.name.slice(r+1).toLowerCase():void 0;return i?t.includes(i):e.type.startsWith("image/")?t.some(e=>ie.includes(e)):!!e.type.startsWith("video/")&&t.some(e=>ne.includes(e))}(t,e));i.length>0&&r(i)},[e,r]);/* @__PURE__ */
|
|
70
|
+
return h("div",{role:"button",tabIndex:0,onClick:()=>!t&&s.current?.click(),onKeyDown:e=>{t||"Enter"!==e.key&&" "!==e.key||s.current?.click()},onDragOver:e=>{e.preventDefault(),t||o(!0)},onDragLeave:()=>o(!1),onDrop:p(e=>{e.preventDefault(),o(!1),t||c(e.dataTransfer?.files??null)},[t,c]),children:[/* @__PURE__ */h("input",{ref:s,type:"file",accept:d,multiple:!0,disabled:t,className:"hidden",onChange:e=>{c(e.target.files),e.target.value=""}}),i({isDragActive:n})]})}function _t({enabledFileTypes:e,disabled:t,onFileSelect:r,selectedCount:i,maxCount:n,enableVideo:o}){/* @__PURE__ */
|
|
71
|
+
return h("div",{className:"mb-6 flex-auto",children:/* @__PURE__ */h("div",{className:"flex w-full justify-center",children:/* @__PURE__ */h(kt,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:()=>/* @__PURE__ */h("div",{className:g("w-full rounded border-2 border-dashed px-[6vw] py-36 text-center transition-colors lg:py-52",t?"border-border hover:cursor-not-allowed":"border-primary hover:bg-primary/10 hover:cursor-pointer"),children:[
|
|
70
72
|
/* @__PURE__ */h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:"text-primary mx-auto size-16",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M4.25 14q.15.575.363 1.1t.487 1q.225.375.175.8t-.325.7t-.688.263t-.637-.363q-.525-.8-.888-1.65t-.562-1.8q-.1-.4.163-.725T3.025 13t.763.275t.462.725m.85-6.1q-.275.475-.487 1T4.25 10q-.125.45-.462.725T3.025 11t-.687-.3t-.163-.7q.2-.975.575-1.875t.9-1.65q.225-.325.625-.337t.675.262t.325.7t-.175.8m2.775 10.95q.5.3 1.025.525t1.075.375q.425.125.7.45t.275.75t-.3.675t-.7.175q-.925-.2-1.787-.55T6.5 20.375q-.35-.225-.387-.638t.237-.712q.3-.3.725-.35t.8.175m2.15-14.6q-.55.15-1.062.363t-1.013.512q-.4.225-.837.188t-.738-.338t-.275-.7t.375-.625q.825-.525 1.713-.887t1.837-.563q.375-.075.675.175t.3.675t-.275.75t-.7.45m6.05 14.625q.375-.225.813-.187t.737.337t.275.713t-.375.612q-.8.525-1.7.888t-1.85.562q-.4.075-.712-.175t-.313-.675t.288-.75t.712-.45q.575-.15 1.1-.362t1.025-.513m-2.1-14.625q-.425-.125-.7-.45T13 3.05t.3-.675t.675-.175q.95.2 1.85.563t1.7.887q.35.225.375.625t-.25.7q-.3.3-.725.35T16.1 5.15q-.525-.3-1.05-.525t-1.075-.375m5.775 9.725q.125-.425.463-.7t.762-.275t.687.325t.163.725q-.2.95-.587 1.825T20.35 17.5q-.225.325-.625.35t-.675-.25t-.325-.712t.175-.813q.275-.5.488-1.012t.362-1.088M18.9 7.9q-.225-.375-.175-.8t.325-.7t.675-.25t.625.35q.55.8.925 1.675T21.85 10q.075.4-.188.7t-.687.3t-.763-.275T19.75 10q-.15-.575-.362-1.1t-.488-1m-7.637 8.813q-.288-.288-.288-.713v-5.125l-1.875 1.9q-.3.3-.712.3t-.713-.3t-.312-.712t.287-.713l3.625-3.65q.275-.275.7-.275t.7.275l3.575 3.575q.3.3.313.725t-.288.725t-.725.3t-.725-.3l-1.85-1.85V16q0 .425-.287.713t-.713.287t-.712-.288"})}),
|
|
71
73
|
/* @__PURE__ */h("span",{className:g(t?"text-muted-foreground":"","mt-2 block font-medium"),children:`Select Images ${o?"or Videos (60s)":""} to upload (${i}/${n})`}),
|
|
72
|
-
/* @__PURE__ */h("div",{className:"text-muted-foreground mt-3 w-full text-center text-xs italic",children:"* Only your new, original photos will be eligible for upload."})]})})})})}function
|
|
73
|
-
return h(
|
|
74
|
-
return h(
|
|
75
|
-
return h("div",{className:"relative overflow-hidden rounded-2xl px-3 pt-6 sm:pt-0",children:[/* @__PURE__ */h("div",{className:"absolute inset-0 opacity-50"}),/* @__PURE__ */h("div",{className:"relative z-10",children:/* @__PURE__ */h("div",{className:"flex flex-col items-center justify-center gap-3",children:/* @__PURE__ */h("div",{className:"flex items-center gap-3",children:/* @__PURE__ */h("div",{className:"space-y-1 text-center",children:[t&&/* @__PURE__ */h(E,{variant:"h4",align:"center",className:"line-clamp-2",children:t}),/* @__PURE__ */h("p",{className:g("text-sm font-medium",e?"text-muted-foreground":"text-foreground"),children:["Remaining Uploads: ",/* @__PURE__ */h("span",{className:"text-primary font-bold",children:n})]})]})})})})]})}var Et=Object.defineProperty,Mt=Object.getOwnPropertyNames,Ut=(e,t)=>function(){return e&&(t=(0,e[Mt(e)[0]])(e=0)),t},Rt=(e,t)=>{for(var r in t)Et(e,r,{get:t[r],enumerable:!0})};function It(e){const t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Pt(e){const t=e<=.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055;return Math.round(Math.max(0,Math.min(255,255*t)))}function Nt(e,t,r){const i=It(e),n=It(t),o=It(r),a=.4122214708*i+.5363325363*n+.0514459929*o,s=.2119034982*i+.6806995451*n+.1073969566*o,l=.0883024619*i+.2817188376*n+.6299787005*o,d=Math.cbrt(a),c=Math.cbrt(s),u=Math.cbrt(l),h=.2104542553*d+.793617785*c-.0040720468*u,p=1.9779984951*d-2.428592205*c+.4505937099*u,m=.0259040371*d+.7827717662*c-.808675766*u,g=Math.sqrt(p*p+m*m);let f=Math.atan2(m,p)*(180/Math.PI);return f<0&&(f+=360),{l:h,c:g,h:f}}function qt(e,t,r){const i=r*(Math.PI/180),n=t*Math.cos(i),o=t*Math.sin(i),a=e+.3963377774*n+.2158037573*o,s=e-.1055613458*n-.0638541728*o,l=e-.0894841775*n-1.291485548*o,d=a*a*a,c=s*s*s,u=l*l*l,h=-1.2684380046*d+2.6097574011*c-.3413193965*u,p=-.0041960863*d-.7034186147*c+1.707614701*u;return[Pt(4.0767416621*d-3.3077115913*c+.2309699292*u),Pt(h),Pt(p)]}var Ot,At=Ut({"src/color-space.ts"(){}});function Dt(e,t){return(Math.max(e,t)+.05)/(Math.min(e,t)+.05)}function Lt(e,t,r,i,n=0){return new Ot(e,t,r,i,n)}var jt=Ut({"src/color.ts"(){At(),Ot=class{constructor(e,t,r,i,n){this._r=e,this._g=t,this._b=r,this.population=i,this.proportion=n}rgb(){return{r:this._r,g:this._g,b:this._b}}hex(){const e=e=>e.toString(16).padStart(2,"0");return`#${e(this._r)}${e(this._g)}${e(this._b)}`}hsl(){return this._hsl||(this._hsl=function(e,t,r){const i=e/255,n=t/255,o=r/255,a=Math.max(i,n,o),s=Math.min(i,n,o),l=(a+s)/2;let d=0,c=0;if(a!==s){const e=a-s;c=l>.5?e/(2-a-s):e/(a+s),d=a===i?((n-o)/e+(n<o?6:0))/6:a===n?((o-i)/e+2)/6:((i-n)/e+4)/6}return{h:Math.round(360*d),s:Math.round(100*c),l:Math.round(100*l)}}(this._r,this._g,this._b)),this._hsl}oklch(){return this._oklch||(this._oklch=Nt(this._r,this._g,this._b)),this._oklch}css(e="rgb"){switch(e){case"hsl":{const{h:e,s:t,l:r}=this.hsl();return`hsl(${e}, ${t}%, ${r}%)`}case"oklch":{const{l:e,c:t,h:r}=this.oklch();return`oklch(${e.toFixed(3)} ${t.toFixed(3)} ${r.toFixed(1)})`}default:return`rgb(${this._r}, ${this._g}, ${this._b})`}}array(){return[this._r,this._g,this._b]}toString(){return this.hex()}get textColor(){return this.isDark?"#ffffff":"#000000"}get luminance(){return void 0===this._luminance&&(this._luminance=function(e,t,r){const i=e=>{const t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)};return.2126*i(e)+.7152*i(t)+.0722*i(r)}(this._r,this._g,this._b)),this._luminance}get isDark(){return this.luminance<=.179}get isLight(){return!this.isDark}get contrast(){if(!this._contrast){const e=this.luminance,t=Dt(e,1),r=Dt(e,0),i=this.isDark?Lt(255,255,255,0,0):Lt(0,0,0,0,0);this._contrast={white:Math.round(100*t)/100,black:Math.round(100*r)/100,foreground:i}}return this._contrast}}}});function zt(e){let{colorCount:t,quality:r}=e;if(void 0!==t&&Number.isInteger(t)){if(1===t)throw new Error("colorCount should be between 2 and 20. To get one color, call getColor() instead of getPalette()");t=Math.max(t,2),t=Math.min(t,20)}else t=10;return(void 0===r||!Number.isInteger(r)||r<1)&&(r=10),{colorCount:t,quality:r,ignoreWhite:void 0===e.ignoreWhite||!!e.ignoreWhite,whiteThreshold:"number"==typeof e.whiteThreshold?e.whiteThreshold:250,alphaThreshold:"number"==typeof e.alphaThreshold?e.alphaThreshold:125,minSaturation:"number"==typeof e.minSaturation?Math.max(0,Math.min(1,e.minSaturation)):0,colorSpace:e.colorSpace??"oklch"}}function $t(e,t,r,i){const{ignoreWhite:n=!0,whiteThreshold:o=250,alphaThreshold:a=125,minSaturation:s=0}=i,l=[];for(let d=0;d<t;d+=r){const t=4*d,r=e[t],i=e[t+1],c=e[t+2],u=e[t+3];if(!(void 0!==u&&u<a||n&&r>o&&i>o&&c>o)){if(s>0){const e=Math.max(r,i,c);if(0===e||(e-Math.min(r,i,c))/e<s)continue}l.push([r,i,c])}}return l}function Bt(e,t,r){let i=0,n=0,o=0,a=0;for(let s=0;s<t;s+=r){const t=4*s;i+=e[t],n+=e[t+1],o+=e[t+2],a++}return 0===a?null:[Math.round(i/a),Math.round(n/a),Math.round(o/a)]}function Ht(e,t,r,i,n){const o=t*r,a={ignoreWhite:i.ignoreWhite,whiteThreshold:i.whiteThreshold,alphaThreshold:i.alphaThreshold,minSaturation:i.minSaturation};let s,l=$t(e,o,i.quality,a);if(0===l.length&&(l=$t(e,o,i.quality,{...a,ignoreWhite:!1})),0===l.length&&(l=$t(e,o,i.quality,{...a,ignoreWhite:!1,alphaThreshold:0})),"oklch"===i.colorSpace){const e=function(e){const t=new Array(e.length);for(let r=0;r<e.length;r++){const[i,n,o]=e[r],{l:a,c:s,h:l}=Nt(i,n,o);t[r]=[Math.round(255*a),Math.round(s/.4*255),Math.round(l/360*255)]}return t}(l);s=n.quantize(e,i.colorCount).map(({color:[e,t,r],population:i})=>({color:qt(e/255,t/255*.4,r/255*360),population:i}))}else s=n.quantize(l,i.colorCount);if(s.length>0){const e=s.reduce((e,t)=>e+t.population,0);return s.map(({color:[t,r,i],population:n})=>Lt(t,r,i,n,e>0?n/e:0))}const d=Bt(e,o,i.quality);return d?[Lt(d[0],d[1],d[2],1,1)]:null}Rt({},{computeFallbackColor:()=>Bt,createPixelArray:()=>$t,extractPalette:()=>Ht,validateOptions:()=>zt});var Vt,Wt=Ut({"src/pipeline.ts"(){jt(),At()}});Rt({},{BrowserPixelLoader:()=>Vt});var Gt,Xt,Yt,Qt,Kt,Jt=Ut({"src/loaders/browser.ts"(){Vt=class{async load(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)return this.loadFromImage(e);if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement)return this.loadFromCanvas(e);if("undefined"!=typeof ImageData&&e instanceof ImageData)return{data:e.data,width:e.width,height:e.height};if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)return this.loadFromVideo(e);if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return this.loadFromImageBitmap(e);if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return this.loadFromOffscreenCanvas(e);throw new Error("Unsupported source type. Expected HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap, or OffscreenCanvas.")}loadFromImage(e){if(!e.complete)throw new Error('Image has not finished loading. Wait for the "load" event before calling getColor/getPalette.');if(!e.naturalWidth)throw new Error("Image has no dimensions. It may not have loaded successfully.");const t=document.createElement("canvas"),r=t.getContext("2d"),i=t.width=e.naturalWidth,n=t.height=e.naturalHeight;r.drawImage(e,0,0,i,n);try{return{data:r.getImageData(0,0,i,n).data,width:i,height:n}}catch(o){if(o instanceof DOMException&&"SecurityError"===o.name){const e=/* @__PURE__ */new Error('Image is tainted by cross-origin data. Add crossorigin="anonymous" to the <img> tag and ensure the server sends appropriate CORS headers.');throw e.cause=o,e}throw o}}loadFromCanvas(e){const t=e.getContext("2d"),{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}loadFromVideo(e){if(e.readyState<2)throw new Error('Video is not ready. Wait for the "loadeddata" or "canplay" event before calling getColor/getPalette.');const t=e.videoWidth,r=e.videoHeight;if(!t||!r)throw new Error("Video has no dimensions. It may not have loaded successfully.");const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=t,i.height=r,n.drawImage(e,0,0,t,r),{data:n.getImageData(0,0,t,r).data,width:t,height:r}}loadFromOffscreenCanvas(e){const t=e.getContext("2d");if(!t)throw new Error("Could not get 2D context from OffscreenCanvas.");const{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}loadFromImageBitmap(e){const t=document.createElement("canvas"),r=t.getContext("2d");return t.width=e.width,t.height=e.height,r.drawImage(e,0,0),{data:r.getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}}}}}),Zt=Ut({"src/worker/worker-script.ts"(){Gt="\n'use strict';\n\n// -------------------------------------------------------------------------\n// Inlined MMCQ (Modified Median Cut Quantization)\n// -------------------------------------------------------------------------\n\nvar SIGBITS = 5;\nvar RSHIFT = 3;\nvar MAX_ITER = 1000;\nvar FRACT_POP = 0.75;\nvar HISTO_SIZE = 32768;\n\nfunction colorIndex(r, g, b) {\n return (r << 10) + (g << 5) + b;\n}\n\nfunction getHisto(pixels) {\n var h = new Uint32Array(HISTO_SIZE);\n for (var i = 0; i < pixels.length; i++) {\n var p = pixels[i];\n h[colorIndex(p[0] >> RSHIFT, p[1] >> RSHIFT, p[2] >> RSHIFT)]++;\n }\n return h;\n}\n\nfunction VBox(r1, r2, g1, g2, b1, b2, histo) {\n this.r1 = r1; this.r2 = r2;\n this.g1 = g1; this.g2 = g2;\n this.b1 = b1; this.b2 = b2;\n this.histo = histo;\n this._count = -1;\n this._volume = -1;\n this._avg = null;\n}\n\nVBox.prototype.volume = function(force) {\n if (this._volume < 0 || force) {\n this._volume = (this.r2 - this.r1 + 1) * (this.g2 - this.g1 + 1) * (this.b2 - this.b1 + 1);\n }\n return this._volume;\n};\n\nVBox.prototype.count = function(force) {\n if (this._count < 0 || force) {\n var n = 0;\n for (var i = this.r1; i <= this.r2; i++)\n for (var j = this.g1; j <= this.g2; j++)\n for (var k = this.b1; k <= this.b2; k++)\n n += this.histo[colorIndex(i, j, k)] || 0;\n this._count = n;\n }\n return this._count;\n};\n\nVBox.prototype.copy = function() {\n return new VBox(this.r1, this.r2, this.g1, this.g2, this.b1, this.b2, this.histo);\n};\n\nVBox.prototype.avg = function(force) {\n if (!this._avg || force) {\n var mult = 1 << RSHIFT;\n if (this.r1 === this.r2 && this.g1 === this.g2 && this.b1 === this.b2) {\n this._avg = [this.r1 << RSHIFT, this.g1 << RSHIFT, this.b1 << RSHIFT];\n } else {\n var ntot = 0, rsum = 0, gsum = 0, bsum = 0;\n for (var i = this.r1; i <= this.r2; i++)\n for (var j = this.g1; j <= this.g2; j++)\n for (var k = this.b1; k <= this.b2; k++) {\n var hval = this.histo[colorIndex(i, j, k)] || 0;\n ntot += hval;\n rsum += hval * (i + 0.5) * mult;\n gsum += hval * (j + 0.5) * mult;\n bsum += hval * (k + 0.5) * mult;\n }\n this._avg = ntot\n ? [~~(rsum / ntot), ~~(gsum / ntot), ~~(bsum / ntot)]\n : [~~(mult * (this.r1 + this.r2 + 1) / 2), ~~(mult * (this.g1 + this.g2 + 1) / 2), ~~(mult * (this.b1 + this.b2 + 1) / 2)];\n }\n }\n return this._avg;\n};\n\nfunction PQueue(comparator) {\n this.contents = [];\n this.sorted = false;\n this.comparator = comparator;\n}\n\nPQueue.prototype.push = function(item) { this.contents.push(item); this.sorted = false; };\nPQueue.prototype.pop = function() {\n if (!this.sorted) { this.contents.sort(this.comparator); this.sorted = true; }\n return this.contents.pop();\n};\nPQueue.prototype.size = function() { return this.contents.length; };\n\nfunction vboxFromPixels(pixels, histo) {\n var rmin = 1e6, rmax = 0, gmin = 1e6, gmax = 0, bmin = 1e6, bmax = 0;\n for (var i = 0; i < pixels.length; i++) {\n var p = pixels[i];\n var rv = p[0] >> RSHIFT, gv = p[1] >> RSHIFT, bv = p[2] >> RSHIFT;\n if (rv < rmin) rmin = rv; if (rv > rmax) rmax = rv;\n if (gv < gmin) gmin = gv; if (gv > gmax) gmax = gv;\n if (bv < bmin) bmin = bv; if (bv > bmax) bmax = bv;\n }\n return new VBox(rmin, rmax, gmin, gmax, bmin, bmax, histo);\n}\n\nfunction medianCutApply(histo, vbox) {\n if (!vbox.count()) return undefined;\n if (vbox.count() === 1) return [vbox.copy(), null];\n\n var rw = vbox.r2 - vbox.r1 + 1;\n var gw = vbox.g2 - vbox.g1 + 1;\n var bw = vbox.b2 - vbox.b1 + 1;\n var maxw = Math.max(rw, gw, bw);\n var total = 0;\n var partialsum = [];\n var lookaheadsum = [];\n var i, j, k, sum;\n\n if (maxw === rw) {\n for (i = vbox.r1; i <= vbox.r2; i++) {\n sum = 0;\n for (j = vbox.g1; j <= vbox.g2; j++)\n for (k = vbox.b1; k <= vbox.b2; k++)\n sum += histo[colorIndex(i, j, k)] || 0;\n total += sum; partialsum[i] = total;\n }\n } else if (maxw === gw) {\n for (i = vbox.g1; i <= vbox.g2; i++) {\n sum = 0;\n for (j = vbox.r1; j <= vbox.r2; j++)\n for (k = vbox.b1; k <= vbox.b2; k++)\n sum += histo[colorIndex(j, i, k)] || 0;\n total += sum; partialsum[i] = total;\n }\n } else {\n for (i = vbox.b1; i <= vbox.b2; i++) {\n sum = 0;\n for (j = vbox.r1; j <= vbox.r2; j++)\n for (k = vbox.g1; k <= vbox.g2; k++)\n sum += histo[colorIndex(j, k, i)] || 0;\n total += sum; partialsum[i] = total;\n }\n }\n\n partialsum.forEach(function(d, idx) { lookaheadsum[idx] = total - d; });\n\n function doCut(color) {\n var dim1 = color + '1', dim2 = color + '2';\n for (var i = vbox[dim1]; i <= vbox[dim2]; i++) {\n if (partialsum[i] > total / 2) {\n var vbox1 = vbox.copy(), vbox2 = vbox.copy();\n var left = i - vbox[dim1], right = vbox[dim2] - i;\n var d2 = left <= right\n ? Math.min(vbox[dim2] - 1, ~~(i + right / 2))\n : Math.max(vbox[dim1], ~~(i - 1 - left / 2));\n while (!partialsum[d2]) d2++;\n var count2 = lookaheadsum[d2];\n while (!count2 && partialsum[d2 - 1]) count2 = lookaheadsum[--d2];\n vbox1[dim2] = d2;\n vbox2[dim1] = d2 + 1;\n return [vbox1, vbox2];\n }\n }\n }\n\n if (maxw === rw) return doCut('r');\n if (maxw === gw) return doCut('g');\n return doCut('b');\n}\n\nfunction iterate(pq, target, histo) {\n var ncolors = pq.size(), niters = 0;\n while (niters < MAX_ITER) {\n if (ncolors >= target) return;\n niters++;\n var vbox = pq.pop();\n if (!vbox.count()) { pq.push(vbox); continue; }\n var result = medianCutApply(histo, vbox);\n if (!result || !result[0]) return;\n pq.push(result[0]);\n if (result[1]) { pq.push(result[1]); ncolors++; }\n }\n}\n\nfunction quantize(pixels, maxColors) {\n if (!pixels.length || maxColors < 2 || maxColors > 256) return [];\n\n var histo = getHisto(pixels);\n var vbox = vboxFromPixels(pixels, histo);\n var pq = new PQueue(function(a, b) { return a.count() - b.count(); });\n pq.push(vbox);\n iterate(pq, FRACT_POP * maxColors, histo);\n\n var pq2 = new PQueue(function(a, b) { return a.count() * a.volume() - b.count() * b.volume(); });\n while (pq.size()) pq2.push(pq.pop());\n iterate(pq2, maxColors, histo);\n\n var results = [];\n while (pq2.size()) {\n var box = pq2.pop();\n results.push({ color: box.avg(), population: box.count() });\n }\n return results;\n}\n\n// -------------------------------------------------------------------------\n// Worker message handler\n// -------------------------------------------------------------------------\n\nself.onmessage = function (e) {\n var data = e.data;\n var id = data.id;\n try {\n var palette = quantize(data.pixels, data.maxColors);\n self.postMessage({ id: id, palette: palette });\n } catch (err) {\n self.postMessage({ id: id, error: err.message || 'Unknown worker error' });\n }\n};\n"}});function er(){return"undefined"!=typeof Worker}function tr(e,t,r){return new Promise((i,n)=>{if(r?.aborted)return void n(r.reason??new DOMException("Aborted","AbortError"));const o=Qt++;Kt.set(o,{resolve:i,reject:n});const a=()=>{Kt.delete(o),n(r.reason??new DOMException("Aborted","AbortError"))};r?.addEventListener("abort",a,{once:!0});try{(function(){if(Xt)return Xt;if(!er())throw new Error("Web Workers are not supported in this environment.");return Yt=URL.createObjectURL(new Blob([Gt],{type:"application/javascript"})),(Xt=new Worker(Yt)).onmessage=e=>{const{id:t,palette:r,error:i}=e.data,n=Kt.get(t);if(n)if(Kt.delete(t),i)n.reject(new Error(i));else{const e=r,t=e.reduce((e,t)=>e+t.population,0),i=e.map(({color:[e,r,i],population:n})=>Lt(e,r,i,n,t>0?n/t:0));n.resolve(i)}},Xt.onerror=e=>{for(const[,t]of Kt)t.reject(new Error(e.message));Kt.clear()},Xt})().postMessage({id:o,pixels:e,maxColors:t})}catch(s){Kt.delete(o),r?.removeEventListener("abort",a),n(s)}})}function rr(){Xt&&(Xt.terminate(),Xt=null),Yt&&(URL.revokeObjectURL(Yt),Yt=null);for(const[,e]of Kt)e.reject(/* @__PURE__ */new Error("Worker terminated"));Kt.clear()}function ir(e,t,r){return(e<<10)+(t<<5)+r}Rt({},{extractInWorker:()=>tr,isWorkerSupported:()=>er,terminateWorker:()=>rr}),Ut({"src/worker/manager.ts"(){jt(),Zt(),Xt=null,Yt=null,Qt=0,Kt=/* @__PURE__ */new Map}}),Wt(),Wt(),jt(),Lt(255,255,255,0),Lt(0,0,0,0);var nr=class e{constructor(e,t,r,i,n,o,a){this.r1=e,this.r2=t,this.g1=r,this.g2=i,this.b1=n,this.b2=o,this.histo=a}volume(e=!1){return(void 0===this._volume||e)&&(this._volume=(this.r2-this.r1+1)*(this.g2-this.g1+1)*(this.b2-this.b1+1)),this._volume}count(e=!1){if(void 0===this._count||e){let e=0;for(let t=this.r1;t<=this.r2;t++)for(let r=this.g1;r<=this.g2;r++)for(let i=this.b1;i<=this.b2;i++)e+=this.histo[ir(t,r,i)]||0;this._count=e}return this._count}copy(){return new e(this.r1,this.r2,this.g1,this.g2,this.b1,this.b2,this.histo)}avg(e=!1){if(void 0===this._avg||e){const e=8;if(this.r1===this.r2&&this.g1===this.g2&&this.b1===this.b2)this._avg=[this.r1<<3,this.g1<<3,this.b1<<3];else{let t=0,r=0,i=0,n=0;for(let o=this.r1;o<=this.r2;o++)for(let a=this.g1;a<=this.g2;a++)for(let s=this.b1;s<=this.b2;s++){const l=this.histo[ir(o,a,s)]||0;t+=l,r+=l*(o+.5)*e,i+=l*(a+.5)*e,n+=l*(s+.5)*e}this._avg=t?[~~(r/t),~~(i/t),~~(n/t)]:[~~(e*(this.r1+this.r2+1)/2),~~(e*(this.g1+this.g2+1)/2),~~(e*(this.b1+this.b2+1)/2)]}}return this._avg}},or=class{constructor(e){this.comparator=e,this.contents=[],this.sorted=!1}sort(){this.contents.sort(this.comparator),this.sorted=!0}push(e){this.contents.push(e),this.sorted=!1}peek(e){return this.sorted||this.sort(),this.contents[e??this.contents.length-1]}pop(){return this.sorted||this.sort(),this.contents.pop()}size(){return this.contents.length}map(e){return this.contents.map(e)}};function ar(e,t){if(!t.count())return;if(1===t.count())return[t.copy(),null];const r=t.r2-t.r1+1,i=t.g2-t.g1+1,n=t.b2-t.b1+1,o=Math.max(r,i,n);let a=0;const s=[],l=[];if(o===r)for(let d=t.r1;d<=t.r2;d++){let r=0;for(let i=t.g1;i<=t.g2;i++)for(let n=t.b1;n<=t.b2;n++)r+=e[ir(d,i,n)]||0;a+=r,s[d]=a}else if(o===i)for(let d=t.g1;d<=t.g2;d++){let r=0;for(let i=t.r1;i<=t.r2;i++)for(let n=t.b1;n<=t.b2;n++)r+=e[ir(i,d,n)]||0;a+=r,s[d]=a}else for(let d=t.b1;d<=t.b2;d++){let r=0;for(let i=t.r1;i<=t.r2;i++)for(let n=t.g1;n<=t.g2;n++)r+=e[ir(i,n,d)]||0;a+=r,s[d]=a}return s.forEach((e,t)=>{l[t]=a-e}),function(e){const r=e+"1",i=e+"2";for(let n=t[r];n<=t[i];n++)if(s[n]>a/2){const e=t.copy(),o=t.copy(),a=n-t[r],d=t[i]-n;let c;for(c=a<=d?Math.min(t[i]-1,~~(n+d/2)):Math.max(t[r],~~(n-1-a/2));!s[c];)c++;let u=l[c];for(;!u&&s[c-1];)u=l[--c];return e[i]=c,o[r]=e[i]+1,[e,o]}}(o===r?"r":o===i?"g":"b")}function sr(e,t,r){let i=e.size(),n=0;for(;n<1e3;){if(i>=t)return;n++;const o=e.pop();if(!o.count()){e.push(o);continue}const a=ar(r,o);if(!a||!a[0])return;e.push(a[0]),a[1]&&(e.push(a[1]),i++)}}Jt(),Wt(),new Vt;var lr=new class{async init(){}quantize(e,t){return function(e,t){if(!e.length||t<2||t>256)return[];const r=/* @__PURE__ */new Set,i=[];for(const d of e){const e=d.join(",");r.has(e)||(r.add(e),i.push(d))}if(i.length<=t){const t=/* @__PURE__ */new Map;for(const r of e){const e=r.join(",");t.set(e,(t.get(e)||0)+1)}return i.map(e=>({color:e,population:t.get(e.join(","))}))}const n=function(e){const t=new Uint32Array(32768);for(const r of e)t[ir(r[0]>>3,r[1]>>3,r[2]>>3)]++;return t}(e),o=function(e,t){let r=1e6,i=0,n=1e6,o=0,a=1e6,s=0;for(const l of e){const e=l[0]>>3,t=l[1]>>3,d=l[2]>>3;e<r?r=e:e>i&&(i=e),t<n?n=t:t>o&&(o=t),d<a?a=d:d>s&&(s=d)}return new nr(r,i,n,o,a,s,t)}(e,n),a=new or((e,t)=>e.count()-t.count());a.push(o),sr(a,.75*t,n);const s=new or((e,t)=>e.count()*e.volume()-t.count()*t.volume());for(;a.size();)s.push(a.pop());sr(s,t,n);const l=[];for(;s.size();){const e=s.pop();l.push({color:e.avg(),population:e.count()})}return l}(e,t)}};function dr(e,t,r){if(t<=0||r<=0)return{};const i=Math.min(1,128/Math.max(t,r)),n=Math.max(1,Math.round(t*i)),o=Math.max(1,Math.round(r*i)),a=new OffscreenCanvas(n,o),s=a.getContext("2d",{willReadFrequently:!0});if(!s)return{};s.drawImage(e,0,0,n,o);const l=s.getImageData(0,0,n,o),d={};try{d.blurhash=M(l.data,n,o,4,4)}catch(c){console.warn("[media-intrinsics] blurhash encode failed:",c)}try{const e=function(e,t){const r=zt(t??{}),i=t?.quantizer??lr,n=function(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)return function(e){if(!e.complete)throw new Error('Image has not finished loading. Wait for the "load" event before calling getColorSync/getPaletteSync.');if(!e.naturalWidth)throw new Error("Image has no dimensions. It may not have loaded successfully.");const t=document.createElement("canvas"),r=t.getContext("2d"),i=t.width=e.naturalWidth,n=t.height=e.naturalHeight;r.drawImage(e,0,0,i,n);try{return{data:r.getImageData(0,0,i,n).data,width:i,height:n}}catch(o){if(o instanceof DOMException&&"SecurityError"===o.name){const e=/* @__PURE__ */new Error('Image is tainted by cross-origin data. Add crossorigin="anonymous" to the <img> tag and ensure the server sends appropriate CORS headers.');throw e.cause=o,e}throw o}}(e);if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement)return function(e){const t=e.getContext("2d"),{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}(e);if("undefined"!=typeof ImageData&&e instanceof ImageData)return{data:e.data,width:e.width,height:e.height};if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)return function(e){if(e.readyState<2)throw new Error('Video is not ready. Wait for the "loadeddata" or "canplay" event before calling getColorSync/getPaletteSync.');const t=e.videoWidth,r=e.videoHeight;if(!t||!r)throw new Error("Video has no dimensions. It may not have loaded successfully.");const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=t,i.height=r,n.drawImage(e,0,0,t,r),{data:n.getImageData(0,0,t,r).data,width:t,height:r}}(e);if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return function(e){const t=document.createElement("canvas"),r=t.getContext("2d");return t.width=e.width,t.height=e.height,r.drawImage(e,0,0),{data:r.getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}}(e);if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return function(e){const t=e.getContext("2d");if(!t)throw new Error("Could not get 2D context from OffscreenCanvas.");const{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}(e);throw new Error("Unsupported source type. Expected HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap, or OffscreenCanvas.")}(e);return Ht(n.data,n.width,n.height,r,i)}(a,{colorCount:5});e&&(d.colors={palette:e.map(e=>e.hex())})}catch(c){console.warn("[media-intrinsics] palette extraction failed:",c)}return d}function cr(e,t){return Object.hasOwn(e,t)}jt();var{AbortController:ur}=globalThis,{AbortSignal:hr}=globalThis,pr=(e="Aborted",t)=>{const r=new DOMException(e,"AbortError");return null!=t&&cr(t,"cause")&&Object.defineProperty(r,"cause",{__proto__:null,configurable:!0,writable:!0,value:t.cause}),r},mr=class extends Error{isNetworkError;cause;constructor(e,t){super(e),this.cause=t?.cause,this.cause&&cr(this.cause,"isNetworkError")?this.isNetworkError=this.cause.isNetworkError:this.isNetworkError=!1}},gr=class extends Error{cause;isNetworkError;request;constructor(e,t=null){super("This looks like a network error, the endpoint might be blocked by an internet provider or a firewall."),this.cause=e,this.isNetworkError=!0,this.request=t}};function fr(e){const t=e.lastIndexOf(".");return-1===t||t===e.length-1?{name:e,extension:void 0}:{name:e.slice(0,t),extension:e.slice(t+1)}}var vr={__proto__:null,md:"text/markdown",markdown:"text/markdown",mp4:"video/mp4",mp3:"audio/mp3",svg:"image/svg+xml",jpg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",heic:"image/heic",heif:"image/heif",yaml:"text/yaml",yml:"text/yaml",csv:"text/csv",tsv:"text/tab-separated-values",tab:"text/tab-separated-values",avi:"video/x-msvideo",mks:"video/x-matroska",mkv:"video/x-matroska",mov:"video/quicktime",dicom:"application/dicom",doc:"application/msword",msg:"application/vnd.ms-outlook",docm:"application/vnd.ms-word.document.macroenabled.12",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",dot:"application/msword",dotm:"application/vnd.ms-word.template.macroenabled.12",dotx:"application/vnd.openxmlformats-officedocument.wordprocessingml.template",xla:"application/vnd.ms-excel",xlam:"application/vnd.ms-excel.addin.macroenabled.12",xlc:"application/vnd.ms-excel",xlf:"application/x-xliff+xml",xlm:"application/vnd.ms-excel",xls:"application/vnd.ms-excel",xlsb:"application/vnd.ms-excel.sheet.binary.macroenabled.12",xlsm:"application/vnd.ms-excel.sheet.macroenabled.12",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xlt:"application/vnd.ms-excel",xltm:"application/vnd.ms-excel.template.macroenabled.12",xltx:"application/vnd.openxmlformats-officedocument.spreadsheetml.template",xlw:"application/vnd.ms-excel",txt:"text/plain",text:"text/plain",conf:"text/plain",log:"text/plain",pdf:"application/pdf",zip:"application/zip","7z":"application/x-7z-compressed",rar:"application/x-rar-compressed",tar:"application/x-tar",gz:"application/gzip",dmg:"application/x-apple-diskimage"};function br(e){if(e.type)return e.type;const t=e.name?fr(e.name).extension?.toLowerCase():null;return t&&t in vr?vr[t]:"application/octet-stream"}function yr(e){let t="";return e.replace(/[^A-Z0-9]/gi,e=>(t+=`-${function(e){return e.charCodeAt(0).toString(32)}(e)}`,"/"))+t}function wr(e,t){return!0===e?Object.keys(t):Array.isArray(e)?e:[]}function xr(e){return e<10?`0${e}`:e.toString()}function Sr(){const e=/* @__PURE__ */new Date;return`${xr(e.getHours())}:${xr(e.getMinutes())}:${xr(e.getSeconds())}`}function Tr(e){if(null!=e){const t=()=>this.abort(e.reason);e.addEventListener("abort",t,{once:!0});const r=()=>{e.removeEventListener("abort",t)};this.then?.(r,r)}return this}var Cr=class{#e=0;#t=[];#r=!1;#i;#n=1;#o;#a;limit;constructor(e){this.limit="number"!=typeof e||0===e?1/0:e}#s(e){this.#e+=1;let t,r=!1;try{t=e()}catch(i){throw this.#e-=1,i}return{abort:e=>{r||(r=!0,this.#e-=1,t?.(e),this.#l())},done:()=>{r||(r=!0,this.#e-=1,this.#l())}}}#l(){queueMicrotask(()=>this.#d())}#d(){if(this.#r||this.#e>=this.limit)return;if(0===this.#t.length)return;const e=this.#t.shift();if(null==e)throw new Error("Invariant violation: next is null");const t=this.#s(e.fn);e.abort=t.abort,e.done=t.done}#c(e,t){const r={fn:e,priority:t?.priority||0,abort:()=>{this.#u(r)},done:()=>{throw new Error("Cannot mark a queued request as done: this indicates a bug")}},i=this.#t.findIndex(e=>r.priority>e.priority);return-1===i?this.#t.push(r):this.#t.splice(i,0,r),r}#u(e){const t=this.#t.indexOf(e);-1!==t&&this.#t.splice(t,1)}run(e,t){return!this.#r&&this.#e<this.limit?this.#s(e):this.#c(e,t)}wrapSyncFunction(e,t){return(...r)=>{const i=this.run(()=>(e(...r),queueMicrotask(()=>i.done()),()=>{}),t);return{abortOn:Tr,abort(){i.abort()}}}}wrapPromiseFunction(e,t){return(...r)=>{let i;const n=new Promise((n,o)=>{i=this.run(()=>{let t,a;try{a=Promise.resolve(e(...r))}catch(s){a=Promise.reject(s)}return a.then(e=>{t?o(t):(i.done(),n(e))},e=>{t?o(t):(i.done(),o(e))}),e=>{t=function(e){return new Error("Cancelled",{cause:e})}(e)}},t)});return n.abort=e=>{i.abort(e)},n.abortOn=Tr,n}}resume(){this.#r=!1,clearTimeout(this.#i);for(let e=0;e<this.limit;e++)this.#l()}#h=()=>this.resume();pause(e=null){this.#r=!0,clearTimeout(this.#i),null!=e&&(this.#i=setTimeout(this.#h,e))}rateLimit(e){clearTimeout(this.#a),this.pause(e),this.limit>1&&Number.isFinite(this.limit)&&(this.#o=this.limit-1,this.limit=this.#n,this.#a=setTimeout(this.#p,e))}#p=()=>{if(this.#r)this.#a=setTimeout(this.#p,0);else{this.#n=this.limit,this.limit=Math.ceil((this.#o+this.#n)/2);for(let e=this.#n;e<=this.limit;e++)this.#l();this.#o-this.#n>3?this.#a=setTimeout(this.#p,2e3):this.#n=Math.floor(this.#n/2)}};get isPaused(){return this.#r}};function Fr(e,t,r){const i=[];return e.forEach(e=>"string"!=typeof e?i.push(e):t[Symbol.split](e).forEach((e,t,n)=>{""!==e&&i.push(e),t<n.length-1&&i.push(r)})),i}function kr(e,t){const r=/\$/g;let i=[e];if(null==t)return i;for(const n of Object.keys(t))if("_"!==n){let e=t[n];"string"==typeof e&&(e=r[Symbol.replace](e,"$$$$")),i=Fr(i,new RegExp(`%\\{${n}\\}`,"g"),e)}return i}var _r=e=>{throw new Error(`missing string: ${e}`)},Er=class{locale;constructor(e,{onMissingKey:t=_r}={}){this.locale={strings:{},pluralize:e=>1===e?0:1},Array.isArray(e)?e.forEach(this.#m,this):this.#m(e),this.#g=t}#g;#m(e){if(!e?.strings)return;const t=this.locale;Object.assign(this.locale,{strings:{...t.strings,...e.strings},pluralize:e.pluralize||t.pluralize})}translate(e,t){return this.translateArray(e,t).join("")}translateArray(e,t){let r=this.locale.strings[e];if(null==r&&(this.#g(e),r=e),"object"==typeof r){if(t&&void 0!==t.smart_count)return kr(r[this.locale.pluralize(t.smart_count)],t);throw new Error("Attempted to use a string with plural forms, but no value was given for %{smart_count}")}if("string"!=typeof r)throw new Error("string was not a string");return kr(r,t)}},Mr=class extends Error{name="UserFacingApiError"},Ur=/* @__PURE__ */t((e,t)=>{function r(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=r,r.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},r.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},r.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=/* @__PURE__ */(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(/* @__PURE__ */new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},r),this._options.unref&&this._timer.unref(),!0},r.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=/* @__PURE__ */(new Date).getTime(),this._fn(this._attempts)},r.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},r.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},r.prototype.start=r.prototype.try,r.prototype.errors=function(){return this._errors},r.prototype.attempts=function(){return this._attempts},r.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,i=0;i<this._errors.length;i++){var n=this._errors[i],o=n.message,a=(e[o]||0)+1;e[o]=a,a>=r&&(t=n,r=a)}return t}}),Rr=/* @__PURE__ */t(e=>{var t=Ur();e.operation=function(r){return new t(e.timeouts(r),{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],n=0;n<t.retries;n++)i.push(this.createTimeout(n,t));return e&&e.forever&&!i.length&&i.push(this.createTimeout(n,t)),i.sort(function(e,t){return e-t}),i},e.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,i=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(i,t.maxTimeout)},e.wrap=function(t,r,i){if(r instanceof Array&&(i=r,r=null),!i)for(var n in i=[],t)"function"==typeof t[n]&&i.push(n);for(var o=0;o<i.length;o++){var a=i[o],s=t[a];t[a]=function(i){var n=e.operation(r),o=Array.prototype.slice.call(arguments,1),a=o.pop();o.push(function(e){n.retry(e)||(e&&(arguments[0]=n.mainError()),a.apply(this,arguments))}),n.attempt(function(){i.apply(t,o)})}.bind(t,s),t[a].options=r}}}),Ir=/* @__PURE__ */t((e,t)=>{t.exports=Rr()}),Pr=Object.prototype.toString,Nr=/* @__PURE__ */new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);var qr=/* @__PURE__ */e(Ir(),1),Or=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},Ar=(e,t,r)=>{const i=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=i,e};async function Dr(e,t){return new Promise((r,i)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const n=qr.operation(t),o=()=>{n.stop(),i(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",o,{once:!0});const a=()=>{t.signal?.removeEventListener("abort",o),n.stop()};n.attempt(async o=>{try{const t=await e(o);a(),r(t)}catch(s){try{if(!(s instanceof Error))throw new TypeError(`Non-error was thrown: "${s}". You should only throw errors.`);if(s instanceof Or)throw s.originalError;if(s instanceof TypeError&&!function(e){if(!e||(t=e,"[object Error]"!==Pr.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)return!1;var t;const{message:r,stack:i}=e;return"Load failed"===r||r.startsWith("Load failed (")&&r.endsWith(")")?void 0===i||"__sentry_captured__"in e:!!r.startsWith("error sending request for url")||!!("Failed to fetch"===r||r.startsWith("Failed to fetch (")&&r.endsWith(")"))||Nr.has(r)}(s))throw s;if(Ar(s,o,t),await t.shouldRetry(s)||(n.stop(),i(s)),await t.onFailedAttempt(s),!n.retry(s))throw n.mainError()}catch(l){Ar(l,o,t),a(),i(l)}}})})}var Lr=class extends Error{isAuthError;constructor(){super("Authorization required"),this.name="AuthError",this.isAuthError=!0}},jr=class extends Error{statusCode;constructor({statusCode:e,message:t}){super(t),this.name="HttpError",this.statusCode=e}},zr=class{static VERSION="5.1.1";#f;uppy;opts;constructor(e,t){this.uppy=e,this.opts=t,this.onReceiveResponse=this.onReceiveResponse.bind(this),this.#f=t.companionHeaders}setCompanionHeaders(e){this.#f=e}[Symbol.for("uppy test: getCompanionHeaders")](){return this.#f}get hostname(){const{companion:e}=this.uppy.getState(),t=this.opts.companionUrl;return(e?.[t]?e[t]:t).replace(/\/$/,"")}async headers(e=!1){return{Accept:"application/json",...e?void 0:{"Content-Type":"application/json"},...this.#f}}onReceiveResponse(e){const{headers:t}=e,r=this.uppy.getState().companion||{},i=this.opts.companionUrl;t.has("i-am")&&t.get("i-am")!==r[i]&&this.uppy.setState({companion:{...r,[i]:t.get("i-am")}})}#v(e){return/^(https?:|)\/\//.test(e)?e:`${this.hostname}/${e}`}async request({path:e,method:t="GET",data:r,skipPostResponse:i,signal:n}){try{const o=await this.headers(!r),a=await function(...e){return fetch(...e).catch(e=>{throw"AbortError"===e.name?e:new gr(e)})}(this.#v(e),{method:t,signal:n,headers:o,credentials:this.opts.companionCookiesRule||"same-origin",body:r?JSON.stringify(r):null});return i||this.onReceiveResponse(a),await async function(e){if(401===e.status)throw new Lr;if(e.ok)return e.json();let t,r=`Failed request with status: ${e.status}. ${e.statusText}`;try{t=await e.json(),t.message&&(r=`${r} message: ${t.message}`),t.requestId&&(r=`${r} request-Id: ${t.requestId}`)}catch(i){throw new Error(r,{cause:i})}if(e.status>=400&&e.status<=499&&t.message)throw new Mr(t.message);throw new jr({statusCode:e.status,message:r})}(a)}catch(o){if(o.isAuthError||"UserFacingApiError"===o.name||"AbortError"===o.name)throw o;throw new mr(`Could not ${t} ${this.#v(e)}`,{cause:o})}}async get(e,t){return this.request({...t,path:e})}async post(e,t,r){return this.request({...r,path:e,method:"POST",data:t})}async delete(e,t,r){return this.request({...r,path:e,method:"DELETE",data:t})}async uploadRemoteFile(e,t,r){try{const{signal:i,getQueue:n}=r||{};return await Dr(async()=>{const r=this.uppy.getFile(e.id)?.serverToken;if(null!=r)return this.uppy.log(`Connecting to exiting websocket ${r}`),this.#b({file:e,queue:n(),signal:i});const o=await n().wrapPromiseFunction(async(...e)=>{try{return await this.#y(...e)}catch(t){if(t.isAuthError)throw new Or(t);if(null==t.cause)throw t;const e=t.cause,r=()=>[408,409,429,418,423].includes(e.statusCode)||e.statusCode>=500&&e.statusCode<=599&&![501,505].includes(e.statusCode);if("HttpError"===e.name&&!r())throw new Or(e);throw e}},{priority:-1})({file:e,postBody:t,signal:i}).abortOn(i);return this.uppy.getFile(e.id)?(this.uppy.setFileState(e.id,{serverToken:o}),this.#b({file:this.uppy.getFile(e.id),queue:n(),signal:i})):void 0},{retries:10,signal:i,onFailedAttempt:e=>this.uppy.log(`Retrying upload due to: ${e.message}`,"warning")})}catch(i){if("AbortError"===i.name)return;throw this.uppy.emit("upload-error",e,i),i}}#y=async({file:e,postBody:t,signal:r})=>{if(null==e.remote?.url)throw new Error("Cannot connect to an undefined URL");return(await this.post(e.remote.url,{...e.remote.body,...t},{signal:r})).token};async#b({file:e,queue:t,signal:r}){let i;const{capabilities:n}=this.uppy.getState();try{return await new Promise((o,a)=>{const s=e.serverToken,l=function(e){const t=/^(?:https?:\/\/|\/\/)?(?:[^@\n]+@)?([^\n]+)/i.exec(e)?.[1];return`${/^http:\/\//i.test(e)?"ws":"wss"}://${t}`}(e.remote.companionUrl);let d,c,u,{isPaused:h}=e;const p=(t,r)=>{null!=d&&d.readyState===d.OPEN?d.send(JSON.stringify({action:t,payload:r??{}})):this.uppy.log(`Cannot send "${t}" to socket ${e.id} because the socket state was ${String(d?.readyState)}`,"warning")};function m(){n.resumableUploads&&p(h?"pause":"resume")}const g=e=>{n.resumableUploads&&(h=e,d&&m())},f=t=>{n.individualCancellation&&t.id===e.id&&(p("cancel"),c?.abort?.(),this.uppy.log(`upload ${e.id} was removed`),o())},v=()=>{p("cancel"),c?.abort?.(),this.uppy.log(`upload ${e.id} was canceled`),o()},b=(t,r)=>{t?.id===e.id&&g(r)},y=()=>g(!0),w=()=>g(!1);this.uppy.on("file-removed",f),this.uppy.on("cancel-all",v),this.uppy.on("upload-pause",b),this.uppy.on("pause-all",y),this.uppy.on("resume-all",w),i=()=>{this.uppy.off("file-removed",f),this.uppy.off("cancel-all",v),this.uppy.off("upload-pause",b),this.uppy.off("pause-all",y),this.uppy.off("resume-all",w)},r.addEventListener("abort",()=>{c?.abort()}),(async()=>{c&&c.abort(),c=new AbortController;const r=t=>{this.uppy.setFileState(e.id,{serverToken:null}),c?.abort?.(),a(t)};function i(){clearTimeout(u),h||(u=setTimeout(()=>r(/* @__PURE__ */new Error("Timeout waiting for message from Companion socket")),3e5))}try{await t.wrapPromiseFunction(async()=>{await Dr(async()=>new Promise((t,n)=>{d=new WebSocket(`${l}/api/${s}`),i(),d.addEventListener("close",()=>{d=void 0,n(/* @__PURE__ */new Error("Socket closed unexpectedly"))}),d.addEventListener("error",e=>{this.uppy.log(`Companion socket error ${JSON.stringify(e)}, closing socket`,"warning"),d?.close()}),d.addEventListener("open",()=>{m()}),d.addEventListener("message",t=>{i();try{const{action:r,payload:i}=JSON.parse(t.data);switch(r){case"progress":!function(e,t,r){const{progress:i,bytesUploaded:n,bytesTotal:o}=t;i&&(e.uppy.log(`Upload progress: ${i}`),e.uppy.emit("upload-progress",r,{uploadStarted:r.progress.uploadStarted??0,bytesUploaded:n,bytesTotal:o}))}(this,i,this.uppy.getFile(e.id));break;case"success":{const t=i.response?.responseText;this.uppy.emit("upload-success",this.uppy.getFile(e.id),{uploadURL:i.url,status:i.response?.status??200,body:t?JSON.parse(t):void 0}),c?.abort?.(),o();break}case"error":{const{message:e}=i.error;throw Object.assign(new Error(e),{cause:i.error})}default:this.uppy.log(`Companion socket unknown action ${r}`,"warning")}}catch(n){r(n)}});const a=()=>{this.uppy.log(`Closing socket ${e.id}`),clearTimeout(u),d&&d.close(),d=void 0};c.signal.addEventListener("abort",()=>{a()})}),{retries:10,signal:c.signal,onFailedAttempt:()=>{c.signal.aborted||this.uppy.log(`Retrying websocket ${e.id}`)}})})().abortOn(c.signal)}catch(n){if(c.signal.aborted)return;r(n)}})()})}finally{i?.()}}},$r=class{uppy;opts;id;defaultLocale;i18n;i18nArray;type;VERSION;constructor(e,t){this.uppy=e,this.opts=t??{}}getPluginState(){const{plugins:e}=this.uppy.getState();return e?.[this.id]||{}}setPluginState(e){const{plugins:t}=this.uppy.getState();this.uppy.setState({plugins:{...t,[this.id]:{...t[this.id],...e}}})}setOptions(e){this.opts={...this.opts,...e},this.setPluginState(void 0),this.i18nInit()}i18nInit(){const e=new Er([this.defaultLocale,this.uppy.locale,this.opts.locale]);this.i18n=e.translate.bind(e),this.i18nArray=e.translateArray.bind(e),this.setPluginState(void 0)}addTarget(e){throw new Error("Extend the addTarget method to add your plugin to another plugin's target")}install(){}uninstall(){}update(e){}afterUpdate(){}},Br=class{#w;#x=[];constructor(e){this.#w=e}on(e,t){return this.#x.push([e,t]),this.#w.on(e,t)}remove(){for(const[e,t]of this.#x.splice(0))this.#w.off(e,t)}onFilePause(e,t){this.on("upload-pause",(r,i)=>{e===r?.id&&t(i)})}onFileRemove(e,t){this.on("file-removed",r=>{e===r.id&&t(r.id)})}onPause(e,t){this.on("upload-pause",(r,i)=>{e===r?.id&&t(i)})}onRetry(e,t){this.on("upload-retry",r=>{e===r?.id&&t()})}onRetryAll(e,t){this.on("retry-all",()=>{this.#w.getFile(e)&&t()})}onPauseAll(e,t){this.on("pause-all",()=>{this.#w.getFile(e)&&t()})}onCancelAll(e,t){this.on("cancel-all",(...r)=>{this.#w.getFile(e)&&t(...r)})}onResumeAll(e,t){this.on("resume-all",()=>{this.#w.getFile(e)&&t()})}},Hr=class{static VERSION="5.0.0";state={};#S=/* @__PURE__ */new Set;getState(){return this.state}setState(e){const t={...this.state},r={...this.state,...e};this.state=r,this.#T(t,r,e)}subscribe(e){return this.#S.add(e),()=>{this.#S.delete(e)}}#T(...e){this.#S.forEach(t=>{t(...e)})}},Vr=/* @__PURE__ */t((e,t)=>{t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}}),Wr=/* @__PURE__ */t((e,t)=>{var r="object"==typeof global&&global&&global.Object===Object&&global;t.exports=r}),Gr=/* @__PURE__ */t((e,t)=>{var r=Wr(),i="object"==typeof self&&self&&self.Object===Object&&self,n=r||i||Function("return this")();t.exports=n}),Xr=/* @__PURE__ */t((e,t)=>{var r=Gr();t.exports=function(){return r.Date.now()}}),Yr=/* @__PURE__ */t((e,t)=>{var r=/\s/;t.exports=function(e){for(var t=e.length;t--&&r.test(e.charAt(t)););return t}}),Qr=/* @__PURE__ */t((e,t)=>{var r=Yr(),i=/^\s+/;t.exports=function(e){return e?e.slice(0,r(e)+1).replace(i,""):e}}),Kr=/* @__PURE__ */t((e,t)=>{var r=Gr().Symbol;t.exports=r}),Jr=/* @__PURE__ */t((e,t)=>{var r=Kr(),i=Object.prototype,n=i.hasOwnProperty,o=i.toString,a=r?r.toStringTag:void 0;t.exports=function(e){var t=n.call(e,a),r=e[a];try{e[a]=void 0;var i=!0}catch(l){}var s=o.call(e);return i&&(t?e[a]=r:delete e[a]),s}}),Zr=/* @__PURE__ */t((e,t)=>{var r=Object.prototype.toString;t.exports=function(e){return r.call(e)}}),ei=/* @__PURE__ */t((e,t)=>{var r=Kr(),i=Jr(),n=Zr(),o=r?r.toStringTag:void 0;t.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":o&&o in Object(e)?i(e):n(e)}}),ti=/* @__PURE__ */t((e,t)=>{t.exports=function(e){return null!=e&&"object"==typeof e}}),ri=/* @__PURE__ */t((e,t)=>{var r=ei(),i=ti();t.exports=function(e){return"symbol"==typeof e||i(e)&&"[object Symbol]"==r(e)}}),ii=/* @__PURE__ */t((e,t)=>{var r=Qr(),i=Vr(),n=ri(),o=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,s=/^0o[0-7]+$/i,l=parseInt;t.exports=function(e){if("number"==typeof e)return e;if(n(e))return NaN;if(i(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=i(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=r(e);var d=a.test(e);return d||s.test(e)?l(e.slice(2),d?2:8):o.test(e)?NaN:+e}}),ni=/* @__PURE__ */t((e,t)=>{var r=Vr(),i=Xr(),n=ii(),o=Math.max,a=Math.min;t.exports=function(e,t,s){var l,d,c,u,h,p,m=0,g=!1,f=!1,v=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function b(t){var r=l,i=d;return l=d=void 0,m=t,u=e.apply(i,r)}function y(e){var r=e-p;return void 0===p||r>=t||r<0||f&&e-m>=c}function w(){var e=i();if(y(e))return x(e);h=setTimeout(w,function(e){var r=t-(e-p);return f?a(r,c-(e-m)):r}(e))}function x(e){return h=void 0,v&&l?b(e):(l=d=void 0,u)}function S(){var e=i(),r=y(e);if(l=arguments,d=this,p=e,r){if(void 0===h)return function(e){return m=e,h=setTimeout(w,t),g?b(e):u}(p);if(f)return clearTimeout(h),h=setTimeout(w,t),b(p)}return void 0===h&&(h=setTimeout(w,t)),u}return t=n(t)||0,r(s)&&(g=!!s.leading,c=(f="maxWait"in s)?o(n(s.maxWait)||0,t):c,v="trailing"in s?!!s.trailing:v),S.cancel=function(){void 0!==h&&clearTimeout(h),m=0,l=p=d=h=void 0},S.flush=function(){return void 0===h?u:x(i())},S}}),oi=/* @__PURE__ */t((e,t)=>{var r=ni(),i=Vr();t.exports=function(e,t,n){var o=!0,a=!0;if("function"!=typeof e)throw new TypeError("Expected a function");return i(n)&&(o="leading"in n?!!n.leading:o,a="trailing"in n?!!n.trailing:a),r(e,t,{leading:o,maxWait:t,trailing:a})}}),ai=/* @__PURE__ */t((e,t)=>{t.exports=function(){var e={},t=e._fns={};return e.emit=function(e,r,i,n,o,a,s){var l=function(e){for(var r=t[e]?t[e]:[],i=e.indexOf(":"),n=-1===i?[e]:[e.substring(0,i),e.substring(i+1)],o=Object.keys(t),a=0,s=o.length;a<s;a++){var l=o[a];if("*"===l&&(r=r.concat(t[l])),2===n.length&&n[0]===l){r=r.concat(t[l]);break}}return r}(e);l.length&&function(e,t,r){for(var i=0,n=t.length;i<n&&t[i];i++)t[i].event=e,t[i].apply(t[i],r)}(e,l,[r,i,n,o,a,s])},e.on=function(e,r){t[e]||(t[e]=[]),t[e].push(r)},e.once=function(t,r){this.on(t,function i(){r.apply(this,arguments),e.off(t,i)})},e.off=function(e,t){var r=[];if(e&&t)for(var i=this._fns[e],n=0,o=i?i.length:0;n<o;n++)i[n]!==t&&r.push(i[n]);r.length?this._fns[e]=r:delete this._fns[e]},e}}),si={strings:{addBulkFilesFailed:{0:"Failed to add %{smart_count} file due to an internal error",1:"Failed to add %{smart_count} files due to internal errors"},youCanOnlyUploadX:{0:"You can only upload %{smart_count} file",1:"You can only upload %{smart_count} files"},youHaveToAtLeastSelectX:{0:"You have to select at least %{smart_count} file",1:"You have to select at least %{smart_count} files"},aggregateExceedsSize:"You selected %{size} of files, but maximum allowed size is %{sizeAllowed}",exceedsSize:"%{file} exceeds maximum allowed size of %{size}",missingRequiredMetaField:"Missing required meta fields",missingRequiredMetaFieldOnFile:"Missing required meta fields in %{fileName}",inferiorSize:"This file is smaller than the allowed size of %{size}",youCanOnlyUploadFileTypes:"You can only upload: %{types}",noMoreFilesAllowed:"Cannot add more files",noDuplicates:"Cannot add the duplicate file '%{fileName}', it already exists",companionError:"Connection with Companion failed",authAborted:"Authentication aborted",companionUnauthorizeHint:"To unauthorize to your %{provider} account, please go to %{url}",failedToUpload:"Failed to upload %{file}",noInternetConnection:"No Internet connection",connectedToInternet:"Connected to the Internet",noFilesFound:"You have no files or folders here",noSearchResults:"Unfortunately, there are no results for this search",selectX:{0:"Select %{smart_count}",1:"Select %{smart_count}"},allFilesFromFolderNamed:"All files from folder %{name}",openFolderNamed:"Open folder %{name}",cancel:"Cancel",logOut:"Log out",logIn:"Log in",pickFiles:"Pick files",pickPhotos:"Pick photos",filter:"Filter",resetFilter:"Reset filter",loading:"Loading...",loadedXFiles:"Loaded %{numFiles} files",authenticateWithTitle:"Please authenticate with %{pluginName} to select files",authenticateWith:"Connect to %{pluginName}",signInWithGoogle:"Sign in with Google",searchImages:"Search for images",enterTextToSearch:"Enter text to search for images",search:"Search",resetSearch:"Reset search",emptyFolderAdded:"No files were added from empty folder",addedNumFiles:"Added %{numFiles} file(s)",folderAlreadyAdded:'The folder "%{folder}" was already added',folderAdded:{0:"Added %{smart_count} file from %{folder}",1:"Added %{smart_count} files from %{folder}"},additionalRestrictionsFailed:"%{count} additional restrictions were not fulfilled",unnamed:"Unnamed",pleaseWait:"Please wait"}},li={debug:()=>{},warn:()=>{},error:(...e)=>console.error(`[Uppy] [${Sr()}]`,...e)},di={debug:(...e)=>console.debug(`[Uppy] [${Sr()}]`,...e),warn:(...e)=>console.warn(`[Uppy] [${Sr()}]`,...e),error:(...e)=>console.error(`[Uppy] [${Sr()}]`,...e)},ci=/* @__PURE__ */t((e,t)=>{t.exports=function(e){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("Expected a number, got "+typeof e);const t=e<0;let r=Math.abs(e);if(t&&(r=-r),0===r)return"0 B";const i=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],n=Math.min(Math.floor(Math.log(r)/Math.log(1024)),i.length-1),o=Number(r/1024**n),a=i[n];return`${o>=10||o%1==0?Math.round(o):o.toFixed(1)} ${a}`}}),ui=/* @__PURE__ */t((e,t)=>{function r(e,t){this.text=e=e||"",this.hasWild=~e.indexOf("*"),this.separator=t,this.parts=e.split(t)}r.prototype.match=function(e){var t,r,i=!0,n=this.parts,o=n.length;if("string"==typeof e||e instanceof String)if(this.hasWild||this.text==e){for(r=(e||"").split(this.separator),t=0;i&&t<o;t++)"*"!==n[t]&&(i=t<r.length&&n[t]===r[t]);i=i&&r}else i=!1;else if("function"==typeof e.splice)for(i=[],t=e.length;t--;)this.match(e[t])&&(i[i.length]=e[t]);else if("object"==typeof e)for(var a in i={},e)this.match(a)&&(i[a]=e[a]);return i},t.exports=function(e,t,i){var n=new r(e,i||/[\/\.]/);return void 0!==t?n.match(t):n}}),hi=/* @__PURE__ */t((e,t)=>{var r=ui(),i=/[\/\+\.]/;t.exports=function(e,t){function n(t){var n=r(t,e,i);return n&&n.length>=2}return t?n(t.split(";")[0]):n}}),pi=/* @__PURE__ */e(ci(),1),mi=/* @__PURE__ */e(hi(),1),gi={maxFileSize:null,minFileSize:null,maxTotalFileSize:null,maxNumberOfFiles:null,minNumberOfFiles:null,allowedFileTypes:null,requiredMetaFields:[]},fi=class extends Error{isUserFacing;file;constructor(e,t){super(e),this.isUserFacing=t?.isUserFacing??!0,t?.file&&(this.file=t.file)}isRestriction=!0},vi=class{getI18n;getOpts;constructor(e,t){this.getI18n=t,this.getOpts=()=>{const t=e();if(null!=t.restrictions?.allowedFileTypes&&!Array.isArray(t.restrictions.allowedFileTypes))throw new TypeError("`restrictions.allowedFileTypes` must be an array");return t}}validateAggregateRestrictions(e,t){const{maxTotalFileSize:r,maxNumberOfFiles:i}=this.getOpts().restrictions;if(i&&e.filter(e=>!e.isGhost).length+t.length>i)throw new fi(`${this.getI18n()("youCanOnlyUploadX",{smart_count:i})}`);if(r){const i=[...e,...t].reduce((e,t)=>e+(t.size??0),0);if(i>r)throw new fi(this.getI18n()("aggregateExceedsSize",{sizeAllowed:(0,pi.default)(r),size:(0,pi.default)(i)}))}}validateSingleFile(e){const{maxFileSize:t,minFileSize:r,allowedFileTypes:i}=this.getOpts().restrictions;if(i&&!i.some(t=>t.includes("/")?!!e.type&&(0,mi.default)(e.type.replace(/;.*?$/,""),t):!("."!==t[0]||!e.extension)&&e.extension.toLowerCase()===t.slice(1).toLowerCase())){const t=i.join(", ");throw new fi(this.getI18n()("youCanOnlyUploadFileTypes",{types:t}),{file:e})}if(t&&null!=e.size&&e.size>t)throw new fi(this.getI18n()("exceedsSize",{size:(0,pi.default)(t),file:e.name??this.getI18n()("unnamed")}),{file:e});if(r&&null!=e.size&&e.size<r)throw new fi(this.getI18n()("inferiorSize",{size:(0,pi.default)(r)}),{file:e})}validate(e,t){t.forEach(e=>{this.validateSingleFile(e)}),this.validateAggregateRestrictions(e,t)}validateMinNumberOfFiles(e){const{minNumberOfFiles:t}=this.getOpts().restrictions;if(t&&Object.keys(e).length<t)throw new fi(this.getI18n()("youHaveToAtLeastSelectX",{smart_count:t}))}getMissingRequiredMetaFields(e){const t=new fi(this.getI18n()("missingRequiredMetaFieldOnFile",{fileName:e.name??this.getI18n()("unnamed")})),{requiredMetaFields:r}=this.getOpts().restrictions,i=[];for(const n of r)Object.hasOwn(e.meta,n)&&""!==e.meta[n]||i.push(n);return{missingFields:i,error:t}}};function bi(e){if(null==e&&"undefined"!=typeof navigator&&(e=navigator.userAgent),!e)return!0;const t=/Edge\/(\d+\.\d+)/.exec(e);if(!t)return!0;const r=t[1].split(".",2),i=parseInt(r[0],10),n=parseInt(r[1],10);return i<15||15===i&&n<15063||i>18||18===i&&n>=18218}var yi=/* @__PURE__ */e(oi(),1),wi=/* @__PURE__ */e(ai(),1),xi={totalProgress:0,allowNewUpload:!0,error:null,recoveredState:null},Si=class e{static VERSION="5.2.0";#C=Object.create(null);#F;#k;#_=(0,wi.default)();#E=/* @__PURE__ */new Set;#M=/* @__PURE__ */new Set;#U=/* @__PURE__ */new Set;defaultLocale;locale;opts;store;i18n;i18nArray;scheduledAutoProceed=null;wasOffline=!1;constructor(t){this.defaultLocale=si;const r={id:"uppy",autoProceed:!1,allowMultipleUploadBatches:!0,debug:!1,restrictions:gi,meta:{},onBeforeFileAdded:(e,t)=>!Object.hasOwn(t,e.id),onBeforeUpload:e=>e,store:new Hr,logger:li,infoTimeout:5e3},i={...r,...t};this.opts={...i,restrictions:{...r.restrictions,...t?.restrictions}},t?.logger&&t.debug?this.log("You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.","warning"):t?.debug&&(this.opts.logger=di),this.log(`Using Core v${e.VERSION}`),this.i18nInit(),this.store=this.opts.store,this.setState({...xi,plugins:{},files:{},currentUploads:{},capabilities:{uploadProgress:bi(),individualCancellation:!0,resumableUploads:!1},meta:{...this.opts.meta},info:[]}),this.#F=new vi(()=>this.opts,()=>this.i18n),this.#k=this.store.subscribe((e,t,r)=>{this.emit("state-update",e,t,r),this.updateAll(t)}),this.opts.debug&&"undefined"!=typeof window&&(window[this.opts.id]=this),this.#R()}emit(e,...t){this.#_.emit(e,...t)}on(e,t){return this.#_.on(e,t),this}once(e,t){return this.#_.once(e,t),this}off(e,t){return this.#_.off(e,t),this}updateAll(e){this.iteratePlugins(t=>{t.update(e)})}setState(e){this.store.setState(e)}getState(){return this.store.getState()}patchFilesState(e){const t=this.getState().files;this.setState({files:{...t,...Object.fromEntries(Object.entries(e).map(([e,r])=>[e,{...t[e],...r}]))}})}setFileState(e,t){if(!this.getState().files[e])throw new Error(`Can’t set state for ${e} (the file could have been removed)`);this.patchFilesState({[e]:t})}i18nInit(){const e=new Er([this.defaultLocale,this.opts.locale],{onMissingKey:e=>this.log(`Missing i18n string: ${e}`,"error")});this.i18n=e.translate.bind(e),this.i18nArray=e.translateArray.bind(e),this.locale=e.locale}setOptions(e){this.opts={...this.opts,...e,restrictions:{...this.opts.restrictions,...e?.restrictions}},e.meta&&this.setMeta(e.meta),this.i18nInit(),e.locale&&this.iteratePlugins(t=>{t.setOptions(e)}),this.setState(void 0)}resetProgress(){const e={percentage:0,bytesUploaded:!1,uploadComplete:!1,uploadStarted:null},t={...this.getState().files},r=Object.create(null);Object.keys(t).forEach(i=>{r[i]={...t[i],progress:{...t[i].progress,...e},tus:void 0,transloadit:void 0}}),this.setState({files:r,...xi})}clear(){const{capabilities:e,currentUploads:t}=this.getState();if(Object.keys(t).length>0&&!e.individualCancellation)throw new Error("The installed uploader plugin does not allow removing files during an upload.");this.setState({...xi,files:{}})}addPreProcessor(e){this.#E.add(e)}removePreProcessor(e){return this.#E.delete(e)}addPostProcessor(e){this.#U.add(e)}removePostProcessor(e){return this.#U.delete(e)}addUploader(e){this.#M.add(e)}removeUploader(e){return this.#M.delete(e)}setMeta(e){const t={...this.getState().meta,...e},r={...this.getState().files};Object.keys(r).forEach(t=>{r[t]={...r[t],meta:{...r[t].meta,...e}}}),this.log("Adding metadata:"),this.log(e),this.setState({meta:t,files:r})}setFileMeta(e,t){const r={...this.getState().files};if(!r[e])return void this.log(`Was trying to set metadata for a file that has been removed: ${e}`);const i={...r[e].meta,...t};r[e]={...r[e],meta:i},this.setState({files:r})}getFile(e){return this.getState().files[e]}getFiles(){const{files:e}=this.getState();return Object.values(e)}getFilesByIds(e){return e.map(e=>this.getFile(e))}getObjectOfFilesPerState(){const{files:e,totalProgress:t,error:r}=this.getState(),i=Object.values(e),n=[],o=[],a=[],s=[],l=[],d=[],c=[],u=[],h=[];for(const p of i){const{progress:e}=p;!e.uploadComplete&&e.uploadStarted&&(n.push(p),p.isPaused||u.push(p)),e.uploadStarted||o.push(p),(e.uploadStarted||e.preprocess||e.postprocess)&&a.push(p),e.uploadStarted&&s.push(p),p.isPaused&&l.push(p),e.uploadComplete&&d.push(p),p.error&&c.push(p),(e.preprocess||e.postprocess)&&h.push(p)}return{newFiles:o,startedFiles:a,uploadStartedFiles:s,pausedFiles:l,completeFiles:d,erroredFiles:c,inProgressFiles:n,inProgressNotPausedFiles:u,processingFiles:h,isUploadStarted:s.length>0,isAllComplete:100===t&&d.length===i.length&&0===h.length,isAllErrored:!!r&&c.length===i.length,isAllPaused:0!==n.length&&l.length===n.length,isUploadInProgress:n.length>0,isSomeGhost:i.some(e=>e.isGhost)}}#I(e){for(const n of e)n.isRestriction?this.emit("restriction-failed",n.file,n):this.emit("error",n,n.file),this.log(n,"warning");const t=e.filter(e=>e.isUserFacing),r=t.slice(0,4),i=t.slice(4);r.forEach(({message:e,details:t=""})=>{this.info({message:e,details:t},"error",this.opts.infoTimeout)}),i.length>0&&this.info({message:this.i18n("additionalRestrictionsFailed",{count:i.length})})}validateRestrictions(e,t=this.getFiles()){try{this.#F.validate(t,[e])}catch(r){return r}return null}validateSingleFile(e){try{this.#F.validateSingleFile(e)}catch(t){return t.message}return null}validateAggregateRestrictions(e){const t=this.getFiles();try{this.#F.validateAggregateRestrictions(t,e)}catch(r){return r.message}return null}#P(e){const{missingFields:t,error:r}=this.#F.getMissingRequiredMetaFields(e);return t.length>0?(this.setFileState(e.id,{missingRequiredMetaFields:t,error:r.message}),this.log(r.message),this.emit("restriction-failed",e,r),!1):(0===t.length&&e.missingRequiredMetaFields&&this.setFileState(e.id,{missingRequiredMetaFields:[]}),!0)}#N(e){let t=!0;for(const r of Object.values(e))this.#P(r)||(t=!1);return t}#q(e){const{allowNewUpload:t}=this.getState();if(!1===t){const t=new fi(this.i18n("noMoreFilesAllowed"),{file:e});throw this.#I([t]),t}}checkIfFileAlreadyExists(e){const{files:t}=this.getState();return!(!t[e]||t[e].isGhost)}#O(e){const t=e instanceof File?{name:e.name,type:e.type,size:e.size,data:e,meta:{},isRemote:!1,source:void 0,preview:void 0}:e,r=br(t),i=function(e,t){return t.name?t.name:"image"===e.split("/")[0]?`${e.split("/")[0]}.${e.split("/")[1]}`:"noname"}(r,t),n=fr(i).extension,o=function(e,t){if(function(e){return!(!e.isRemote||!e.remote)&&/* @__PURE__ */new Set(["box","dropbox","drive","facebook","unsplash"]).has(e.remote.provider)}(e))return e.id;const r=br(e);return function(e,t){let r=t||"uppy";return"string"==typeof e.name&&(r+=`-${yr(e.name.toLowerCase())}`),void 0!==e.type&&(r+=`-${e.type}`),e.meta&&"string"==typeof e.meta.relativePath&&(r+=`-${yr(e.meta.relativePath.toLowerCase())}`),void 0!==e.data?.size&&(r+=`-${e.data.size}`),void 0!==e.data.lastModified&&(r+=`-${e.data.lastModified}`),r}({...e,type:r},t)}(t,this.getID()),a={...t.meta,name:i,type:r},s=Number.isFinite(t.data.size)?t.data.size:null;return{source:t.source||"",id:o,name:i,extension:n||"",meta:{...this.getState().meta,...a},type:r,progress:{percentage:0,bytesUploaded:!1,bytesTotal:s,uploadComplete:!1,uploadStarted:null},size:s,isGhost:!1,...t.isRemote?{isRemote:!0,remote:t.remote,data:t.data}:{isRemote:!1,data:t.data},preview:t.preview}}#A(){this.opts.autoProceed&&!this.scheduledAutoProceed&&(this.scheduledAutoProceed=setTimeout(()=>{this.scheduledAutoProceed=null,this.upload().catch(e=>{e.isRestriction||this.log(e.stack||e.message||e)})},4))}#D(e){let{files:t}=this.getState(),r={...t};const i=[],n=[];for(const a of e)try{let e=this.#O(a);this.#q(e);const n=t[e.id],o=n?.isGhost;if(o&&!e.isRemote){if(null==e.data)throw new Error("File data is missing");e={...n,isGhost:!1,data:e.data},this.log(`Replaced the blob in the restored ghost file: ${e.name}, ${e.id}`)}const s=this.opts.onBeforeFileAdded(e,r);if(t=this.getState().files,r={...t,...r},!s&&this.checkIfFileAlreadyExists(e.id))throw new fi(this.i18n("noDuplicates",{fileName:e.name??this.i18n("unnamed")}),{file:e});if(!1===s&&!o)throw new fi("Cannot add the file because onBeforeFileAdded returned false.",{isUserFacing:!1,file:e});"object"==typeof s&&null!==s&&(e=s),this.#F.validateSingleFile(e),r[e.id]=e,i.push(e)}catch(o){n.push(o)}try{this.#F.validateAggregateRestrictions(Object.values(t),i)}catch(o){return n.push(o),{nextFilesState:t,validFilesToAdd:[],errors:n}}return{nextFilesState:r,validFilesToAdd:i,errors:n}}addFile(e){const{nextFilesState:t,validFilesToAdd:r,errors:i}=this.#D([e]),n=i.filter(e=>e.isRestriction);if(this.#I(n),i.length>0)throw i[0];this.setState({files:t});const[o]=r;return this.emit("file-added",o),this.emit("files-added",r),this.log(`Added file: ${o.name}, ${o.id}, mime type: ${o.type}`),this.#A(),o.id}addFiles(e){const{nextFilesState:t,validFilesToAdd:r,errors:i}=this.#D(e),n=i.filter(e=>e.isRestriction);this.#I(n);const o=i.filter(e=>!e.isRestriction);if(o.length>0){let e="Multiple errors occurred while adding files:\n";if(o.forEach(t=>{e+=`\n * ${t.message}`}),this.info({message:this.i18n("addBulkFilesFailed",{smart_count:o.length}),details:e},"error",this.opts.infoTimeout),"function"==typeof AggregateError)throw new AggregateError(o,e);{const t=new Error(e);throw t.errors=o,t}}this.setState({files:t}),r.forEach(e=>{this.emit("file-added",e)}),this.emit("files-added",r),r.length>5?this.log(`Added batch of ${r.length} files`):Object.values(r).forEach(e=>{this.log(`Added file: ${e.name}\n id: ${e.id}\n type: ${e.type}`)}),r.length>0&&this.#A()}removeFiles(e){const{files:t,currentUploads:r}=this.getState(),i={...t},n={...r},o=Object.create(null);function a(e){return void 0===o[e]}e.forEach(e=>{t[e]&&(o[e]=t[e],delete i[e])}),Object.keys(n).forEach(e=>{const t=r[e].fileIDs.filter(a);if(0===t.length)return void delete n[e];const{capabilities:i}=this.getState();if(t.length!==r[e].fileIDs.length&&!i.individualCancellation)throw new Error("The installed uploader plugin does not allow removing files during an upload.");n[e]={...r[e],fileIDs:t}});const s={currentUploads:n,files:i};0===Object.keys(i).length&&(s.allowNewUpload=!0,s.error=null,s.recoveredState=null),this.setState(s),this.#L();const l=Object.keys(o);l.forEach(e=>{this.emit("file-removed",o[e])}),l.length>5?this.log(`Removed ${l.length} files`):this.log(`Removed files: ${l.join(", ")}`)}removeFile(e){this.removeFiles([e])}pauseResume(e){if(!this.getState().capabilities.resumableUploads||this.getFile(e).progress.uploadComplete)return;const t=this.getFile(e),r=!t.isPaused;return this.setFileState(e,{isPaused:r}),this.emit("upload-pause",t,r),r}pauseAll(){const e={...this.getState().files};Object.keys(e).filter(t=>!e[t].progress.uploadComplete&&e[t].progress.uploadStarted).forEach(t=>{e[t]={...e[t],isPaused:!0}}),this.setState({files:e}),this.emit("pause-all")}resumeAll(){const e={...this.getState().files};Object.keys(e).filter(t=>!e[t].progress.uploadComplete&&e[t].progress.uploadStarted).forEach(t=>{e[t]={...e[t],isPaused:!1,error:null}}),this.setState({files:e}),this.emit("resume-all")}#j(){const{files:e}=this.getState();return Object.keys(e).filter(t=>{const r=e[t];return r.error&&(!r.missingRequiredMetaFields||0===r.missingRequiredMetaFields.length)})}async#z(){const e=this.#j(),t={...this.getState().files};if(e.forEach(e=>{t[e]={...t[e],isPaused:!1,error:null}}),this.setState({files:t,error:null}),this.emit("retry-all",this.getFilesByIds(e)),0===e.length)return{successful:[],failed:[]};const r=this.#$(e,{forceAllowNewUpload:!0});return this.#B(r)}async retryAll(){const e=await this.#z();return this.emit("complete",e),e}cancelAll(){this.emit("cancel-all");const{files:e}=this.getState(),t=Object.keys(e);t.length&&this.removeFiles(t),this.setState(xi)}retryUpload(e){this.setFileState(e,{error:null,isPaused:!1}),this.emit("upload-retry",this.getFile(e));const t=this.#$([e],{forceAllowNewUpload:!0});return this.#B(t)}logout(){this.iteratePlugins(e=>{e.provider?.logout?.()})}#H=(e,t)=>{const r=e?this.getFile(e.id):void 0;if(null==e||!r)return void this.log(`Not setting progress for a file that has been removed: ${e?.id}`);if(100===r.progress.percentage)return void this.log(`Not setting progress for a file that has been already uploaded: ${e.id}`);const i={bytesTotal:t.bytesTotal,percentage:null!=t.bytesTotal&&Number.isFinite(t.bytesTotal)&&t.bytesTotal>0?Math.round(t.bytesUploaded/t.bytesTotal*100):void 0};null!=r.progress.uploadStarted?this.setFileState(e.id,{progress:{...r.progress,...i,bytesUploaded:t.bytesUploaded}}):this.setFileState(e.id,{progress:{...r.progress,...i}}),this.#L()};#V(){const e=this.#W();let t=null;null!=e&&(t=Math.round(100*e),t>100?t=100:t<0&&(t=0)),this.emit("progress",t??0),this.setState({totalProgress:t??0})}#L=(0,yi.default)(()=>this.#V(),500,{leading:!0,trailing:!0});[Symbol.for("uppy test: updateTotalProgress")](){return this.#V()}#W(){const e=this.getFiles().filter(e=>e.progress.uploadStarted||e.progress.preprocess||e.progress.postprocess);if(0===e.length)return 0;if(e.every(e=>e.progress.uploadComplete))return 1;const t=e=>null!=e.progress.bytesTotal&&0!==e.progress.bytesTotal,r=e.filter(t),i=e.filter(e=>!t(e));if(r.every(e=>e.progress.uploadComplete)&&i.length>0&&!i.every(e=>e.progress.uploadComplete))return null;const n=r.reduce((e,t)=>e+(t.progress.bytesTotal??0),0),o=r.reduce((e,t)=>e+(t.progress.bytesUploaded||0),0);return 0===n?0:o/n}#R(){const e=(e,t,r)=>{let i=e.message||"Unknown error";e.details&&(i+=` ${e.details}`),this.setState({error:i}),null!=t&&t.id in this.getState().files&&this.setFileState(t.id,{error:i,response:r})};this.on("error",e),this.on("upload-error",(t,r,i)=>{if(e(r,t,i),"object"==typeof r&&r.message){this.log(r.message,"error");const e=new Error(this.i18n("failedToUpload",{file:t?.name??""}));e.isUserFacing=!0,e.details=r.message,r.details&&(e.details+=` ${r.details}`),this.#I([e])}else this.#I([r])});let t=null;this.on("upload-stalled",(e,r)=>{const{message:i}=e,n=r.map(e=>e.meta.name).join(", ");t||(this.info({message:i,details:n},"warning",this.opts.infoTimeout),t=setTimeout(()=>{t=null},this.opts.infoTimeout)),this.log(`${i} ${n}`.trim(),"warning")}),this.on("upload",()=>{this.setState({error:null})}),this.on("upload-start",e=>{const t=e.filter(e=>{const t=null!=e&&this.getFile(e.id);return t||this.log(`Not setting progress for a file that has been removed: ${e?.id}`),t}),r=Object.fromEntries(t.map(e=>[e.id,{progress:{uploadStarted:Date.now(),uploadComplete:!1,bytesUploaded:0,bytesTotal:e.size}}]));this.patchFilesState(r)}),this.on("upload-progress",this.#H),this.on("upload-success",(e,t)=>{if(null==e||!this.getFile(e.id))return void this.log(`Not setting progress for a file that has been removed: ${e?.id}`);const r=this.getFile(e.id).progress,i=this.#U.size>0;this.setFileState(e.id,{progress:{...r,postprocess:i?{mode:"indeterminate"}:void 0,uploadComplete:!0,...!i&&{complete:!0},percentage:100,bytesUploaded:r.bytesTotal},response:t,uploadURL:t.uploadURL,isPaused:!1}),null==e.size&&this.setFileState(e.id,{size:t.bytesUploaded||r.bytesTotal}),this.#L()}),this.on("preprocess-progress",(e,t)=>{null!=e&&this.getFile(e.id)?this.setFileState(e.id,{progress:{...this.getFile(e.id).progress,preprocess:t}}):this.log(`Not setting progress for a file that has been removed: ${e?.id}`)}),this.on("preprocess-complete",e=>{if(null==e||!this.getFile(e.id))return void this.log(`Not setting progress for a file that has been removed: ${e?.id}`);const t={...this.getState().files};t[e.id]={...t[e.id],progress:{...t[e.id].progress}},delete t[e.id].progress.preprocess,this.setState({files:t})}),this.on("postprocess-progress",(e,t)=>{null!=e&&this.getFile(e.id)?this.setFileState(e.id,{progress:{...this.getState().files[e.id].progress,postprocess:t}}):this.log(`Not setting progress for a file that has been removed: ${e?.id}`)}),this.on("postprocess-complete",e=>{const t=e&&this.getFile(e.id);if(null==t)return void this.log(`Not setting progress for a file that has been removed: ${e?.id}`);const{postprocess:r,...i}=t.progress;this.patchFilesState({[t.id]:{progress:{...i,complete:!0}}})}),this.on("restored",()=>{this.#L()}),this.on("dashboard:file-edit-complete",e=>{e&&this.#P(e)}),"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("online",this.#G),window.addEventListener("offline",this.#G),setTimeout(this.#G,3e3))}updateOnlineStatus(){window.navigator.onLine??1?(this.emit("is-online"),this.wasOffline&&(this.emit("back-online"),this.info(this.i18n("connectedToInternet"),"success",3e3),this.wasOffline=!1)):(this.emit("is-offline"),this.info(this.i18n("noInternetConnection"),"error",0),this.wasOffline=!0)}#G=this.updateOnlineStatus.bind(this);getID(){return this.opts.id}use(e,...t){if("function"!=typeof e)throw new TypeError(`Expected a plugin class, but got ${null===e?"null":typeof e}. Please verify that the plugin was imported and spelled correctly.`);const r=new e(this,...t),i=r.id;if(!i)throw new Error("Your plugin must have an id");if(!r.type)throw new Error("Your plugin must have a type");const n=this.getPlugin(i);if(n){const e=`Already found a plugin named '${n.id}'. Tried to use: '${i}'.\nUppy plugins must have unique \`id\` options.`;throw new Error(e)}return e.VERSION&&this.log(`Using ${i} v${e.VERSION}`),r.type in this.#C?this.#C[r.type].push(r):this.#C[r.type]=[r],r.install(),this.emit("plugin-added",r),this}getPlugin(e){for(const t of Object.values(this.#C)){const r=t.find(t=>t.id===e);if(null!=r)return r}}[Symbol.for("uppy test: getPlugins")](e){return this.#C[e]}iteratePlugins(e){Object.values(this.#C).flat(1).forEach(e)}removePlugin(e){this.log(`Removing plugin ${e.id}`),this.emit("plugin-remove",e),e.uninstall&&e.uninstall();const t=this.#C[e.type],r=t.findIndex(t=>t.id===e.id);-1!==r&&t.splice(r,1);const i={plugins:{...this.getState().plugins,[e.id]:void 0}};this.setState(i)}destroy(){this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`),this.cancelAll(),this.#k(),this.iteratePlugins(e=>{this.removePlugin(e)}),"undefined"!=typeof window&&window.removeEventListener&&(window.removeEventListener("online",this.#G),window.removeEventListener("offline",this.#G))}hideInfo(){const{info:e}=this.getState();this.setState({info:e.slice(1)}),this.emit("info-hidden")}info(e,t="info",r=3e3){const i="object"==typeof e;this.setState({info:[...this.getState().info,{type:t,message:i?e.message:e,details:i?e.details:null}]}),setTimeout(()=>this.hideInfo(),r),this.emit("info-visible")}log(e,t){const{logger:r}=this.opts;switch(t){case"error":r.error(e);break;case"warning":r.warn(e);break;default:r.debug(e)}}#X=/* @__PURE__ */new Map;registerRequestClient(e,t){this.#X.set(e,t)}getRequestClientForFile(e){if(!("remote"in e)||!e.remote)throw new Error(`Tried to get RequestClient for a non-remote file ${e.id}`);const t=this.#X.get(e.remote.requestClientId);if(null==t)throw new Error(`requestClientId "${e.remote.requestClientId}" not registered for file "${e.id}"`);return t}async restore(e){this.log(`Core: Running restored upload "${e}"`);const t=await this.#B(e);return this.emit("complete",t),t}#$(e,t={}){const{forceAllowNewUpload:r=!1}=t,{allowNewUpload:i,currentUploads:n}=this.getState();if(!i&&!r)throw new Error("Cannot create a new upload: already uploading.");const o=((e=21)=>{let t="",r=0|e;for(;r-- >0;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t})();return this.emit("upload",o,this.getFilesByIds(e)),this.setState({allowNewUpload:!1!==this.opts.allowMultipleUploadBatches&&!1!==this.opts.allowMultipleUploads,currentUploads:{...n,[o]:{fileIDs:e,step:0,result:{}}}}),o}[Symbol.for("uppy test: createUpload")](...e){return this.#$(...e)}#Y(e){const{currentUploads:t}=this.getState();return t[e]}addResultData(e,t){if(!this.#Y(e))return void this.log(`Not setting result for an upload that has been removed: ${e}`);const{currentUploads:r}=this.getState(),i={...r[e],result:{...r[e].result,...t}};this.setState({currentUploads:{...r,[e]:i}})}#Q(e){const{[e]:t,...r}=this.getState().currentUploads;this.setState({currentUploads:r})}async#B(e){const t=()=>{const{currentUploads:t}=this.getState();return t[e]};let r=t();if(!r)throw new Error("Nonexistent upload");const i=[...this.#E,...this.#M,...this.#U];try{for(let n=r.step||0;n<i.length;n++){const o=i[n];this.setState({currentUploads:{...this.getState().currentUploads,[e]:{...r,step:n}}});const{fileIDs:a}=r;if(await o(a,e),r=t(),!r)break}}catch(o){throw this.#Q(e),o}if(r){r.fileIDs.forEach(e=>{const t=this.getFile(e);t?.progress.postprocess&&this.emit("postprocess-complete",t)});const i=r.fileIDs.map(e=>this.getFile(e)),n=i.filter(e=>!e.error),o=i.filter(e=>e.error);this.addResultData(e,{successful:n,failed:o,uploadID:e}),r=t()}let n;return r&&(n=r.result,this.#Q(e)),null==n&&(this.log(`Not setting result for an upload that has been removed: ${e}`),n={successful:[],failed:[],uploadID:e}),n}async upload(){this.#C.uploader?.length||this.log("No uploader type plugins are used","warning");let{files:e}=this.getState();if(this.#j().length>0){const t=await this.#z();if(!(this.getFiles().filter(e=>null==e.progress.uploadStarted).length>0))return this.emit("complete",t),t;({files:e}=this.getState())}const t=this.opts.onBeforeUpload(e);if(!1===t)throw new Error("Not starting the upload because onBeforeUpload returned false");t&&"object"==typeof t&&(e=t,this.setState({files:e}));try{if(this.#F.validateMinNumberOfFiles(e),!this.#N(e))throw new fi(this.i18n("missingRequiredMetaField"));const{currentUploads:t}=this.getState(),r=Object.values(t).flatMap(e=>e.fileIDs),i=Object.keys(e).filter(e=>{const t=this.getFile(e);return t&&!t.progress.uploadStarted&&!r.includes(e)}),n=this.#$(i),o=await this.#B(n);return this.emit("complete",o),o}catch(r){throw this.#I([r]),r}}};function Ti({method:e="PUT",CanonicalUri:t="/",CanonicalQueryString:r="",SignedHeaders:i,HashedPayload:n}){const o=Object.keys(i).map(e=>e.toLowerCase()).sort();return[e,t,r,...o.map(e=>`${e}:${i[e]}`),"",o.join(";"),n].join("\n")}var Ci=new TextEncoder,Fi={name:"HMAC",hash:"SHA-256"};async function ki(e){const{subtle:t}=globalThis.crypto;return t.digest(Fi.hash,Ci.encode(e))}function _i(e){const t=new Uint8Array(e);let r="";for(let i=0;i<t.length;i++)r+=t[i].toString(16).padStart(2,"0");return r}async function Ei(e,t){const{subtle:r}=globalThis.crypto;return r.sign(Fi,await async function(e){const{subtle:t}=globalThis.crypto;return t.importKey("raw","string"==typeof e?Ci.encode(e):e,Fi,!1,["sign"])}(e),Ci.encode(t))}async function Mi({accountKey:e,accountSecret:t,sessionToken:r,bucketName:i,Key:n,Region:o,expires:a,uploadId:s,partNumber:l}){const d="s3",c=`${d}.${o}.amazonaws.com`,u=`/${i}/${encodeURI(n).replace(/[;?:@&=+$,#!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}`,h="UNSIGNED-PAYLOAD",p=/* @__PURE__ */(new Date).toISOString().replace(/[-:]|\.\d+/g,""),m=p.slice(0,8),g=`${m}/${o}/${d}/aws4_request`,f=new URL(`https://${c}${u}`);f.searchParams.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),f.searchParams.set("X-Amz-Content-Sha256",h),f.searchParams.set("X-Amz-Credential",`${e}/${g}`),f.searchParams.set("X-Amz-Date",p),f.searchParams.set("X-Amz-Expires",a),f.searchParams.set("X-Amz-Security-Token",r),f.searchParams.set("X-Amz-SignedHeaders","host"),l&&f.searchParams.set("partNumber",l),s&&f.searchParams.set("uploadId",s),f.searchParams.set("x-id",l&&s?"UploadPart":"PutObject");const v=["AWS4-HMAC-SHA256",p,g,_i(await ki(Ti({CanonicalUri:u,CanonicalQueryString:f.search.slice(1),SignedHeaders:{host:c},HashedPayload:h})))].join("\n"),b=_i(await Ei(await Ei(await Ei(await Ei(await Ei(`AWS4${t}`,m),o),d),"aws4_request"),v));return f.searchParams.set("X-Amz-Signature",b),f}var Ui={getChunkSize:e=>Math.ceil(e.size/1e4),onProgress(){},onPartComplete(){},onSuccess(){},onError(e){throw e}},Ri=Symbol("pausing upload, not an actual error"),Ii=class{options;#K=new ur;#J=[];#Z=[];#ee;#te;#re=!1;#ie;#ne;#oe;#ae;#se=e=>e?.cause===Ri?null:this.#ie(e);#le=1e4;#de=5242880;constructor(e,t){this.options={...Ui,...t},this.options.getChunkSize??=Ui.getChunkSize,this.#ee=e,this.#te=t.file,this.#ne=this.options.onSuccess,this.#ie=this.options.onError,this.#oe=this.options.shouldUseMultipart,this.#ae=t.uploadId&&t.key,this.#ce()}#ce(){const e=this.#ee.size,t="function"==typeof this.#oe?this.#oe(this.#te):Boolean(this.#oe);if(t&&e>this.#de){let r=Math.max(this.options.getChunkSize(this.#ee),this.#de),i=Math.floor(e/r);i>this.#le&&(i=this.#le,r=e/this.#le),this.#J=Array(i);for(let n=0,o=0;n<e;n+=r,o++){const i=Math.min(e,n+r),a=()=>{const e=n;return this.#ee.slice(e,i)};if(this.#J[o]={getData:a,onProgress:this.#ue(o),onComplete:this.#he(o),shouldUseMultipart:t},this.#ae){const t=n+r>e?e-n:r;this.#J[o].setAsUploaded=()=>{this.#J[o]=null,this.#Z[o].uploaded=t}}}}else this.#J=[{getData:()=>this.#ee,onProgress:this.#ue(0),onComplete:this.#he(0),shouldUseMultipart:t}];this.#Z=this.#J.map(()=>({uploaded:0}))}#$(){this.options.companionComm.uploadFile(this.#te,this.#J,this.#K.signal).then(this.#ne,this.#se),this.#re=!0}#pe(){this.options.companionComm.resumeUploadFile(this.#te,this.#J,this.#K.signal).then(this.#ne,this.#se)}#ue=e=>t=>{if(!t.lengthComputable)return;this.#Z[e].uploaded=function(e){if("string"==typeof e)return parseInt(e,10);if("number"==typeof e)return e;throw new TypeError("Expected a number")}(t.loaded);const r=this.#Z.reduce((e,t)=>e+t.uploaded,0);this.options.onProgress(r,this.#ee.size)};#he=e=>t=>{this.#J[e]=null,this.#Z[e].etag=t,this.#Z[e].done=!0;const r={PartNumber:e+1,ETag:t};this.options.onPartComplete(r)};#me(){this.#K.abort(),this.options.companionComm.abortFileUpload(this.#te).catch(e=>this.options.log(e))}start(){this.#re?(this.#K.signal.aborted||this.#K.abort(Ri),this.#K=new ur,this.#pe()):this.#ae?(this.options.companionComm.restoreUploadFile(this.#te,{uploadId:this.options.uploadId,key:this.options.key}),this.#pe()):this.#$()}pause(){this.#K.abort(Ri),this.#K=new ur}abort(e){e?.really?this.#me():this.pause()}[Symbol.for("uppy test: getChunkState")](){return this.#Z}};function Pi(e){if(e?.aborted)throw pr("The operation was aborted",{cause:e.reason})}function Ni(e){const t=new URL(e);return t.search="",t.hash="",t.href}var qi=class{#ge;#fe=/* @__PURE__ */new WeakMap;#ve;#be;#ye;#we;#xe;#Se;#Te;#Ce;#Fe;#ke;#_e;constructor(e,t,r,i){this.#Se=e,this.#Fe=r,this.#_e=i,this.setOptions(t)}setOptions(e){const t=this.#Se;"abortMultipartUpload"in e&&(this.#ge=t.wrapPromiseFunction(e.abortMultipartUpload,{priority:1})),"createMultipartUpload"in e&&(this.#ve=t.wrapPromiseFunction(e.createMultipartUpload,{priority:-1})),"signPart"in e&&(this.#be=t.wrapPromiseFunction(e.signPart)),"listParts"in e&&(this.#we=t.wrapPromiseFunction(e.listParts)),"completeMultipartUpload"in e&&(this.#Ce=t.wrapPromiseFunction(e.completeMultipartUpload,{priority:1})),"retryDelays"in e&&(this.#Te=e.retryDelays??[]),"uploadPartBytes"in e&&(this.#ke=t.wrapPromiseFunction(e.uploadPartBytes,{priority:1/0})),"getUploadParameters"in e&&(this.#ye=t.wrapPromiseFunction(e.getUploadParameters))}async#Ee(e,t){const r=this.#Se,i=e?.source?.status;if(null==i)return!1;if(403===i&&"Request has expired"===e.message){if(!r.isPaused){if(1===r.limit||null==this.#xe){const e=t.next();if(null==e||e.done)return!1;this.#xe=e.value}r.rateLimit(0),await new Promise(e=>setTimeout(e,this.#xe))}}else if(429===i){if(!r.isPaused){const e=t.next();if(null==e||e.done)return!1;r.rateLimit(e.value)}}else{if(i>400&&i<500&&409!==i)return!1;if("undefined"!=typeof navigator&&!1===navigator.onLine)r.isPaused||(r.pause(),window.addEventListener("online",()=>{r.resume()},{once:!0}));else{const e=t.next();if(null==e||e.done)return!1;await new Promise(t=>setTimeout(t,e.value))}}return!0}async getUploadId(e,t){let r;for(;;){if(null==e.data)throw new Error("File data is empty");if(r=this.#fe.get(e.data),null==r)break;try{return await r}catch{}}const i=this.#ve(this.#_e(e),t),n=()=>{if(null==e.data)throw new Error("File data is empty");i.abort(t.reason),this.#fe.delete(e.data)};return t.addEventListener("abort",n,{once:!0}),this.#fe.set(e.data,i),i.then(async r=>{if(t.removeEventListener("abort",n),this.#Fe(e,r),null==e.data)throw new Error("File data is empty");this.#fe.set(e.data,r)},()=>{if(t.removeEventListener("abort",n),null==e.data)throw new Error("File data is empty");this.#fe.delete(e.data)}),i}async abortFileUpload(e){if(null==e.data)throw new Error("File data is empty");const t=this.#fe.get(e.data);if(null==t)return;let r;this.#fe.delete(e.data),this.#Fe(e,Object.create(null));try{r=await t}catch{return}await this.#ge(this.#_e(e),r)}async#Me(e,t,r){const{method:i="POST",url:n,fields:o,headers:a}=await this.#ye(this.#_e(e),{signal:r}).abortOn(r);let s;const l=t.getData();if("POST"===i.toUpperCase()){const e=new FormData;Object.entries(o).forEach(([t,r])=>e.set(t,r)),e.set("file",l),s=e}else s=l;const{onProgress:d,onComplete:c}=t,u=await this.#ke({signature:{url:n,headers:a,method:i},body:s,size:l.size,onProgress:d,onComplete:c,signal:r}).abortOn(r),h=o?.key;return this.#Fe(e,{key:h}),{...u,location:u.location??Ni(n),bucket:o?.bucket,key:h}}async uploadFile(e,t,r){if(Pi(r),1===t.length&&!t[0].shouldUseMultipart)return this.#Me(e,t[0],r);const{uploadId:i,key:n}=await this.getUploadId(e,r);Pi(r);try{const o=await Promise.all(t.map((t,i)=>this.uploadChunk(e,i+1,t,r)));return Pi(r),await this.#Ce(this.#_e(e),{key:n,uploadId:i,parts:o,signal:r},r).abortOn(r)}catch(o){throw o?.cause!==Ri&&"AbortError"!==o?.name&&this.abortFileUpload(e),o}}restoreUploadFile(e,t){if(null==e.data)throw new Error("File data is empty");this.#fe.set(e.data,t)}async resumeUploadFile(e,t,r){if(Pi(r),1===t.length&&null!=t[0]&&!t[0].shouldUseMultipart)return this.#Me(e,t[0],r);const{uploadId:i,key:n}=await this.getUploadId(e,r);Pi(r);const o=await this.#we(this.#_e(e),{uploadId:i,key:n,signal:r},r).abortOn(r);Pi(r);const a=await Promise.all(t.map((t,i)=>{const n=i+1,a=o.find(({PartNumber:e})=>e===n);return null==a?this.uploadChunk(e,n,t,r):(t?.setAsUploaded?.(),{PartNumber:n,ETag:a.ETag})}));return Pi(r),this.#Ce(this.#_e(e),{key:n,uploadId:i,parts:a,signal:r},r).abortOn(r)}async uploadChunk(e,t,r,i){Pi(i);const{uploadId:n,key:o}=await this.getUploadId(e,i),a=this.#Te.values(),s=this.#Te.values(),l=()=>{const e=a.next();return null==e||e.done?null:e.value};for(;;){Pi(i);const a=r.getData(),{onProgress:c,onComplete:u}=r;let h;try{h=await this.#be(this.#_e(e),{uploadId:n,key:o,partNumber:t,body:a,signal:i}).abortOn(i)}catch(d){const e=l();if(null==e||i.aborted)throw d;await new Promise(t=>setTimeout(t,e));continue}Pi(i);try{return{PartNumber:t,...await this.#ke({signature:h,body:a,size:a.size,onProgress:c,onComplete:u,signal:i}).abortOn(i)}}catch(d){if(!(await this.#Ee(d,s)))throw d}}}};function Oi(e){if(e?.error){const t=new Error(e.message);throw Object.assign(t,e.error),t}return e}function Ai(e){const t=e.Expiration;if(t){const e=Math.floor((new Date(t)-Date.now())/1e3);if(e>9)return e}}function Di({meta:e,allowedMetaFields:t,querify:r=!1}){const i=t??Object.keys(e);return e?Object.fromEntries(i.filter(t=>null!=e[t]).map(t=>[r?`metadata[${t}]`:t,String(e[t])])):{}}var Li={allowedMetaFields:!0,limit:6,getTemporarySecurityCredentials:!1,shouldUseMultipart:e=>(e.size||0)>104857600,retryDelays:[0,1e3,3e3,5e3]},ji=class e extends $r{static VERSION="5.1.0";#Ue;#Re;requests;uploaderEvents;uploaders;constructor(t,r){super(t,{...Li,uploadPartBytes:e.uploadPartBytes,createMultipartUpload:null,listParts:null,abortMultipartUpload:null,completeMultipartUpload:null,signPart:null,getUploadParameters:null,...r}),this.type="uploader",this.id=this.opts.id||"AwsS3Multipart",this.#Ie(r);const i={createMultipartUpload:this.createMultipartUpload,listParts:this.listParts,abortMultipartUpload:this.abortMultipartUpload,completeMultipartUpload:this.completeMultipartUpload,signPart:r?.getTemporarySecurityCredentials?this.createSignedURL:this.signPart,getUploadParameters:r?.getTemporarySecurityCredentials?this.createSignedURL:this.getUploadParameters};for(const e of Object.keys(i))null==this.opts[e]&&(this.opts[e]=i[e].bind(this));this.requests=this.opts.rateLimitedQueue??new Cr(this.opts.limit),this.#Ue=new qi(this.requests,this.opts,this.#Fe,this.#_e),this.uploaders=Object.create(null),this.uploaderEvents=Object.create(null)}[Symbol.for("uppy test: getClient")](){return this.#Re}#Ie(e){null!=e&&("endpoint"in e||"companionUrl"in e||"headers"in e||"companionHeaders"in e||"cookiesRule"in e||"companionCookiesRule"in e)&&("companionUrl"in e&&!("endpoint"in e)&&this.uppy.log("`companionUrl` option has been removed in @uppy/aws-s3, use `endpoint` instead.","warning"),"companionHeaders"in e&&!("headers"in e)&&this.uppy.log("`companionHeaders` option has been removed in @uppy/aws-s3, use `headers` instead.","warning"),"companionCookiesRule"in e&&!("cookiesRule"in e)&&this.uppy.log("`companionCookiesRule` option has been removed in @uppy/aws-s3, use `cookiesRule` instead.","warning"),"endpoint"in e?this.#Re=new zr(this.uppy,{pluginId:this.id,provider:"AWS",companionUrl:this.opts.endpoint,companionHeaders:this.opts.headers,companionCookiesRule:this.opts.cookiesRule}):("headers"in e&&this.#Pe(),"cookiesRule"in e&&(this.#Re.opts.companionCookiesRule=e.cookiesRule)))}setOptions(e){this.#Ue.setOptions(e),super.setOptions(e),this.#Ie(e)}resetUploaderReferences(e,t){this.uploaders[e]&&(this.uploaders[e].abort({really:t?.abort||!1}),this.uploaders[e]=null),this.uploaderEvents[e]&&(this.uploaderEvents[e].remove(),this.uploaderEvents[e]=null)}#Ne(e){if(!this.#Re)throw new Error(`Expected a \`endpoint\` option containing a URL, or if you are not using Companion, a custom \`${e}\` implementation.`)}createMultipartUpload(e,t){this.#Ne("createMultipartUpload"),Pi(t);const r=wr(this.opts.allowedMetaFields,e.meta),i=Di({meta:e.meta,allowedMetaFields:r});return this.#Re.post("s3/multipart",{filename:e.name,type:e.type,metadata:i},{signal:t}).then(Oi)}listParts(e,{key:t,uploadId:r,signal:i},n){i??=n,this.#Ne("listParts"),Pi(i);const o=encodeURIComponent(t);return this.#Re.get(`s3/multipart/${encodeURIComponent(r)}?key=${o}`,{signal:i}).then(Oi)}completeMultipartUpload(e,{key:t,uploadId:r,parts:i,signal:n},o){n??=o,this.#Ne("completeMultipartUpload"),Pi(n);const a=encodeURIComponent(t),s=encodeURIComponent(r);return this.#Re.post(`s3/multipart/${s}/complete?key=${a}`,{parts:i.map(({ETag:e,PartNumber:t})=>({ETag:e,PartNumber:t}))},{signal:n}).then(Oi)}#qe;async#Oe(e){if(Pi(e?.signal),null==this.#qe){const{getTemporarySecurityCredentials:t}=this.opts;!0===t?(this.#Ne("getTemporarySecurityCredentials"),this.#qe=this.#Re.get("s3/sts",e).then(Oi)):this.#qe=t(e),this.#qe=await this.#qe,setTimeout(()=>{this.#qe=null},500*(Ai(this.#qe.credentials)||0))}return this.#qe}async createSignedURL(e,t){const r=await this.#Oe(t),i=Ai(r.credentials)||604800,{uploadId:n,key:o,partNumber:a}=t;return{method:"PUT",expires:i,fields:{},url:`${await Mi({accountKey:r.credentials.AccessKeyId,accountSecret:r.credentials.SecretAccessKey,sessionToken:r.credentials.SessionToken,expires:i,bucketName:r.bucket,Region:r.region,Key:o??`${crypto.randomUUID()}-${e.name}`,uploadId:n,partNumber:a})}`,headers:{"Content-Type":e.type}}}signPart(e,{uploadId:t,key:r,partNumber:i,signal:n}){if(this.#Ne("signPart"),Pi(n),null==t||null==r||null==i)throw new Error("Cannot sign without a key, an uploadId, and a partNumber");const o=encodeURIComponent(r);return this.#Re.get(`s3/multipart/${encodeURIComponent(t)}/${i}?key=${o}`,{signal:n}).then(Oi)}abortMultipartUpload(e,{key:t,uploadId:r,signal:i}){this.#Ne("abortMultipartUpload");const n=encodeURIComponent(t),o=encodeURIComponent(r);return this.#Re.delete(`s3/multipart/${o}?key=${n}`,void 0,{signal:i}).then(Oi)}getUploadParameters(e,t){this.#Ne("getUploadParameters");const{meta:r}=e,{type:i,name:n}=r,o=Di({meta:r,allowedMetaFields:wr(this.opts.allowedMetaFields,e.meta),querify:!0}),a=new URLSearchParams({filename:n,type:i,...o});return this.#Re.get(`s3/params?${a}`,t)}static async uploadPartBytes({signature:{url:e,expires:t,headers:r,method:i="PUT"},body:n,size:o=n.size,onProgress:a,onComplete:s,signal:l}){if(Pi(l),null==e)throw new Error("Cannot upload to an undefined URL");return new Promise((d,c)=>{const u=new XMLHttpRequest;function h(){u.abort()}function p(){l?.removeEventListener("abort",h)}u.open(i,e,!0),r&&Object.keys(r).forEach(e=>{u.setRequestHeader(e,r[e])}),u.responseType="text","number"==typeof t&&(u.timeout=1e3*t),l?.addEventListener("abort",h),u.upload.addEventListener("progress",e=>{a(e)}),u.addEventListener("abort",()=>{p(),c(pr())}),u.addEventListener("timeout",()=>{p();const e=/* @__PURE__ */new Error("Request has expired");e.source={status:403},c(e)}),u.addEventListener("load",()=>{if(p(),403===u.status&&u.responseText.includes("<Message>Request has expired</Message>")){const e=/* @__PURE__ */new Error("Request has expired");return e.source=u,void c(e)}if(u.status<200||u.status>=300){const e=/* @__PURE__ */new Error("Non 2xx");return e.source=u,void c(e)}a?.({loaded:o,lengthComputable:!0});const e=u.getAllResponseHeaders().trim().split(/[\r\n]+/),t={__proto__:null};for(const i of e){const e=i.split(": ");t[e.shift()]=e.join(": ")}const{etag:r,location:n}=t;"POST"===i.toUpperCase()&&null==n&&console.error("@uppy/aws-s3: Could not read the Location header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3/#setting-up-your-s3-bucket"),null!=r?(s?.(r),d({...t,ETag:r})):console.error("@uppy/aws-s3: Could not read the ETag header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3/#setting-up-your-s3-bucket")}),u.addEventListener("error",e=>{p();const t=/* @__PURE__ */new Error("Unknown error");t.source=e.target,c(t)}),u.send(n)})}#Fe=(e,{key:t,uploadId:r})=>{const i=this.uppy.getFile(e.id);null!=i&&this.uppy.setFileState(e.id,{s3Multipart:{...i.s3Multipart,key:t,uploadId:r}})};#_e=e=>this.uppy.getFile(e.id)||e;#Ae(e){return new Promise((t,r)=>{if(null==e.data)throw new Error("File data is empty");const i=new Ii(e.data,{companionComm:this.#Ue,log:(...e)=>this.uppy.log(...e),getChunkSize:this.opts.getChunkSize?this.opts.getChunkSize.bind(this):void 0,onProgress:(t,r)=>{const i=this.uppy.getFile(e.id);this.uppy.emit("upload-progress",i,{uploadStarted:i.progress.uploadStarted??0,bytesUploaded:t,bytesTotal:r})},onError:t=>{this.uppy.log(t),this.uppy.emit("upload-error",e,t),this.resetUploaderReferences(e.id),r(t)},onSuccess:r=>{const i={body:{...r},status:200,uploadURL:r.location};this.resetUploaderReferences(e.id),this.uppy.emit("upload-success",this.#_e(e),i),r.location&&this.uppy.log(`Download ${e.name} from ${r.location}`),t(void 0)},onPartComplete:t=>{this.uppy.emit("s3-multipart:part-uploaded",this.#_e(e),t)},file:e,shouldUseMultipart:this.opts.shouldUseMultipart,...e.s3Multipart});this.uploaders[e.id]=i;const n=new Br(this.uppy);this.uploaderEvents[e.id]=n,n.onFileRemove(e.id,r=>{i.abort(),this.resetUploaderReferences(e.id,{abort:!0}),t(`upload ${r} was removed`)}),n.onCancelAll(e.id,()=>{i.abort(),this.resetUploaderReferences(e.id,{abort:!0}),t(`upload ${e.id} was canceled`)}),n.onFilePause(e.id,e=>{e?i.pause():i.start()}),n.onPauseAll(e.id,()=>{i.pause()}),n.onResumeAll(e.id,()=>{i.start()}),i.start()})}#De(e){return{..."remote"in e&&e.remote?.body,protocol:"s3-multipart",size:e.data.size,metadata:e.meta}}#Le=async e=>{if(0===e.length)return;const t=this.uppy.getFilesByIds(e).filter(e=>!(e=>"error"in e&&!!e.error)(e)&&!(e=>e.progress.uploadComplete)(e)),r=function(e){return e.filter(e=>!e.progress?.uploadStarted||!e.isRestored)}(t);this.uppy.emit("upload-start",r);const i=t.map(e=>{if(e.isRemote){const t=()=>this.requests;this.#je(!1);const r=new AbortController,i=t=>{t.id===e.id&&r.abort()};this.uppy.on("file-removed",i);const n=this.uppy.getRequestClientForFile(e).uploadRemoteFile(e,this.#De(e),{signal:r.signal,getQueue:t});return this.requests.wrapSyncFunction(()=>{this.uppy.off("file-removed",i)},{priority:-1})(),n}return this.#Ae(e)}),n=await Promise.allSettled(i);return this.#je(!0),n};#Pe=()=>{this.#Re?.setCompanionHeaders(this.opts.headers)};#je=e=>{const{capabilities:t}=this.uppy.getState();this.uppy.setState({capabilities:{...t,resumableUploads:e}})};#ze=()=>{this.#je(!0)};install(){this.#je(!0),this.uppy.addPreProcessor(this.#Pe),this.uppy.addUploader(this.#Le),this.uppy.on("cancel-all",this.#ze)}uninstall(){this.uppy.removePreProcessor(this.#Pe),this.uppy.removeUploader(this.#Le),this.uppy.off("cancel-all",this.#ze)}},zi="undefined"!=typeof window&&(window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB),$i=!!zi,Bi="uppy-blobs",Hi="files",Vi=864e5,Wi=1048576;function Gi(e){const t=zi.open(e,3);return new Promise((e,r)=>{t.onupgradeneeded=t=>{const r=t.target.result,i=t.currentTarget.transaction;if(t.oldVersion<2&&r.createObjectStore(Hi,{keyPath:"id"}).createIndex("store","store",{unique:!1}),t.oldVersion<3){const e=i.objectStore(Hi);e.createIndex("expires","expires",{unique:!1}),function(e){e.openCursor().onsuccess=e=>{const t=e.target.result;if(!t)return;const r=t.value;r.expires=Date.now()+Vi,t.update(r)}}(e)}i.oncomplete=()=>{e(r)}},t.onsuccess=t=>{e(t.target.result)},t.onerror=r})}function Xi(e){return new Promise((t,r)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=r})}var Yi=!1,Qi=class e{#$e;opts;name;static isSupported;constructor(t){this.opts={dbName:Bi,storeName:"default",expires:Vi,maxFileSize:10*Wi,maxTotalSize:300*Wi,...t},this.name=this.opts.storeName;const r=async()=>{const e=await Gi(this.opts.dbName);return this.#$e=e,e};Yi?this.#$e=r():(Yi=!0,this.#$e=e.cleanup().then(r,r))}get ready(){return Promise.resolve(this.#$e)}key(e){return`${this.name}!${e}`}async list(){const e=await Xi((await this.#$e).transaction([Hi],"readonly").objectStore(Hi).index("store").getAll(IDBKeyRange.only(this.name)));return Object.fromEntries(e.map(e=>[e.fileID,e.data]))}async get(e){const{data:t}=await Xi((await this.#$e).transaction([Hi],"readonly").objectStore(Hi).get(this.key(e)));return{id:t.fileID,data:t.data}}async getSize(){const e=(await this.#$e).transaction([Hi],"readonly").objectStore(Hi).index("store").openCursor(IDBKeyRange.only(this.name));return new Promise((t,r)=>{let i=0;e.onsuccess=e=>{const r=e.target.result;r?(i+=r.value.data.size,r.continue()):t(i)},e.onerror=()=>{r(/* @__PURE__ */new Error("Could not retrieve stored blobs size"))}})}async put(e){if(null!=e.data.size&&e.data.size>this.opts.maxFileSize)throw new Error("File is too big to store.");if(await this.getSize()>this.opts.maxTotalSize)throw new Error("No space left");return Xi((await this.#$e).transaction([Hi],"readwrite").objectStore(Hi).add({id:this.key(e.id),fileID:e.id,store:this.name,expires:Date.now()+this.opts.expires,data:e.data}))}async delete(e){return Xi((await this.#$e).transaction([Hi],"readwrite").objectStore(Hi).delete(this.key(e)))}static async cleanup(){const e=await Gi(Bi),t=e.transaction([Hi],"readwrite").objectStore(Hi).index("expires").openCursor(IDBKeyRange.upperBound(Date.now()));await new Promise((e,r)=>{t.onsuccess=t=>{const r=t.target.result;r?(r.delete(),r.continue()):e()},t.onerror=r}),e.close()}};function Ki(e){try{return JSON.parse(e)}catch{return null}}Qi.isSupported=$i;var Ji="uppyState:",Zi=class{opts;name;#Be;constructor(e){var t;this.opts={expires:864e5,throttleTime:500,...e},this.name=(t=e.storeName,`${Ji}${t}`),this.#Be=0===this.opts.throttleTime?this.save:(0,yi.default)(this.save,this.opts.throttleTime,{leading:!0,trailing:!0})}#He;load=()=>{!function(){const e=[];for(let r=0;r<localStorage.length;r++){const t=localStorage.key(r);t?.startsWith(Ji)&&e.push(t)}const t=Date.now();e.forEach(e=>{const r=localStorage.getItem(e);if(!r)return;const i=Ki(r);i?.expires&&i.expires<t&&localStorage.removeItem(e)})}();const e=localStorage.getItem(this.name);if(!e)return;const t=Ki(e);return t?(this.#He=t,t.metadata):void 0};get=()=>this.#He?.metadata;save=()=>{if(null===this.#He)return void localStorage.removeItem(this.name);const e=JSON.stringify(this.#He);localStorage.setItem(this.name,e)};set=e=>{this.#He=null===e?null:{metadata:e,expires:Date.now()+this.opts.expires},this.#Be()}},en="undefined"!=typeof navigator&&"serviceWorker"in navigator,tn=class{#$e;name;static isSupported;constructor(e){this.#$e=new Promise((e,t)=>{en?navigator.serviceWorker.controller?e():navigator.serviceWorker.addEventListener("controllerchange",()=>{e()}):t(/* @__PURE__ */new Error("Unsupported"))}).then(e=>{this.#$e=e}),this.name=e.storeName}get ready(){return Promise.resolve(this.#$e)}async list(){return await this.#$e,new Promise((e,t)=>{const r=i=>{i.data.store===this.name&&("uppy/ALL_FILES"===i.data.type?(e(i.data.files),navigator.serviceWorker.removeEventListener("message",r)):t())};navigator.serviceWorker.addEventListener("message",r),navigator.serviceWorker.controller.postMessage({type:"uppy/GET_FILES",store:this.name})})}async put(e){await this.#$e,navigator.serviceWorker.controller.postMessage({type:"uppy/ADD_FILE",store:this.name,file:e})}async delete(e){await this.#$e,navigator.serviceWorker.controller.postMessage({type:"uppy/REMOVE_FILE",store:this.name,fileID:e})}};tn.isSupported=en;var rn={expires:864e5,serviceWorker:!1},nn=class e extends $r{static VERSION="5.2.1";#Ve;#We;#Ge;static[Symbol.for("uppy test: throttleTime")];constructor(t,r){super(t,{...rn,...r}),this.type="debugger",this.id=this.opts.id||"GoldenRetriever",this.#Ve=new Zi({expires:this.opts.expires,storeName:t.getID(),throttleTime:e[Symbol.for("uppy test: throttleTime")]??void 0}),this.opts.serviceWorker&&(this.#We=new tn({storeName:t.getID()})),this.#Ge=new Qi({expires:this.opts.expires,...this.opts.indexedDB||{},storeName:t.getID()})}async#Xe(){const e=this.#Ve.load();if(!e)return;const t=e.currentUploads||{},r=Object.entries(e.files||{}),i=Object.fromEntries(r.every(([,e])=>e.progress.complete&&!e.error)?[]:r),n=Object.entries(i);this.uppy.log(`[GoldenRetriever] Recovered ${Object.keys(t).length} current uploads and ${n.length} files from Local Storage`);const o=n.length>0;o||this.uppy.log("[GoldenRetriever] No files need to be loaded, restored only processing state...");const[a,s]=await Promise.all([this.#Ye(),this.#Qe()]),l={...a,...s},d=Object.fromEntries(n.map(([e,t])=>{if(t.isRemote)return[e,{...t,isRestored:!0,data:{size:null}}];const r=l[e];return[e,t.progress.uploadComplete||null!=r?{...t,isRestored:!0,isGhost:!1,data:r}:{...t,isRestored:!0,isGhost:!0,data:void 0}]}));this.uppy.setState({recoveredState:o?e:null,currentUploads:o?t:{},files:d}),this.uppy.emit("restored",e.pluginData);const c=Object.keys(l).filter(e=>!i[e]);if(c.length)try{this.uppy.log(`[GoldenRetriever] Cleaning up ${c.length} old files`),await this.#Ke(c)}catch(u){this.uppy.log(`[GoldenRetriever] Could not clean up ${c.length} old files`,"warning"),this.uppy.log(u)}}#Je=({pluginData:e,...t})=>{const r=this.#Ve.get();this.#Ve.set({...r??{currentUploads:{},files:{}},...t,pluginData:{...r?.pluginData,...e}})};async#Ye(){if(!this.#We)return{};try{const e=await this.#We.list(),t=Object.keys(e).length;return this.uppy.log(t>0?`[GoldenRetriever] Successfully recovered ${t} blobs from Service Worker!`:"[GoldenRetriever] No blobs found in Service Worker"),e}catch(e){return this.uppy.log("[GoldenRetriever] Failed to recover blobs from Service Worker","warning"),this.uppy.log(e),{}}}async#Qe(){try{const e=await this.#Ge.list(),t=Object.keys(e).length;return this.uppy.log(t>0?`[GoldenRetriever] Successfully recovered ${t} blobs from IndexedDB!`:"[GoldenRetriever] No blobs found in IndexedDB"),e}catch(e){return this.uppy.log("[GoldenRetriever] Failed to recover blobs from IndexedDB","warning"),this.uppy.log(e),{}}}async#Ke(e){await Promise.all(e.map(async e=>{try{await Promise.all([this.#We?.delete(e),this.#Ge.delete(e)])}catch(t){this.uppy.log(`[GoldenRetriever] Could not remove file ${e} from all stores`,"warning"),this.uppy.log(t)}})),e.length>0&&this.uppy.log(`[GoldenRetriever] Removed ${e.length} blobs`)}async[Symbol.for("uppy test: deleteBlobs")](e){return this.#Ke(e)}#Ze=async e=>{const{id:t,data:r,isRemote:i}=e;i||null==r||await Promise.all([this.#We?.put({id:t,data:r}).catch(e=>{this.uppy.log("[GoldenRetriever] Could not store file in Service Worker","warning"),this.uppy.log(e)}),this.#Ge.put({id:t,data:r}).catch(e=>{e instanceof Event&&e.target instanceof IDBRequest&&"ConstraintError"===e.target.error?.name||(this.uppy.log("[GoldenRetriever] Could not store file in IndexedDB","warning"),this.uppy.log(e))})])};#et=(e,t,r)=>{if(t.currentUploads!==e.currentUploads){const{currentUploads:e}=this.uppy.getState();this.#Je({currentUploads:e})}if(t.files!==e.files){Object.values(e.files).some(e=>!e.progress.complete)&&(0===Object.values(t.files).length||Object.values(t.files).every(e=>e.progress.complete&&!e.error))&&(this.uppy.log("[GoldenRetriever] All files have been uploaded and processed successfully, clearing recovery state"),this.uppy.setState({recoveredState:null}));const r=Object.fromEntries(Object.entries(t.files).map(([e,{data:t,preview:r,...i}])=>[e,i]));this.#Je({files:r});const i=Object.values(t.files).filter(t=>null==e.files[t.id]),n=Object.values(t.files).flatMap(t=>{const r=e.files[t.id];return null!=r&&t.data!==r.data?[t]:[]}),o=[...Object.values(e.files).filter(e=>{const r=t.files[e.id];return null==r||r.progress.uploadComplete&&!e.progress.uploadComplete}),...n],a=[...i,...n];(async()=>{await this.#Ke(o.map(e=>e.id));for(const e of a)await this.#Ze(e);a.length>0&&this.uppy.log(`[GoldenRetriever] Added ${a.length} blobs`)})()}};#tt=()=>{this.uppy.log("[GoldenRetriever] Restore confirmed, proceeding...");const{currentUploads:e}=this.uppy.getState();Object.keys(e).length>0?(this.uppy.resumeAll(),Object.keys(e).forEach(e=>{this.uppy.restore(e)})):this.uppy.upload(),this.uppy.setState({recoveredState:null})};#rt=e=>{this.#Je({pluginData:e})};install(){this.#Xe(),this.uppy.on("state-update",this.#et),this.uppy.on("restore-confirmed",this.#tt),this.uppy.on("restore:plugin-data-changed",this.#rt)}uninstall(){this.uppy.off("state-update",this.#et),this.uppy.off("restore-confirmed",this.#tt),this.uppy.off("restore:plugin-data-changed",this.#rt)}};function on(){const e=Ve(),t=f(),r=a(null),n=a(null),o=a({}),s=a(0),l=a(null),d=a({}),c=a(void 0),u=a({}),h=a(!1);i(()=>{const e=t.user;c.current=e?.id??(e?._id?String(e._id):void 0),u.current={organizationId:t.props?.organizationId,token:e?.token}},[t.user,t.props?.organizationId]);const m=p(()=>{const{organizationId:e,token:t}=u.current,r={"Content-Type":"application/json"};return e&&(r["x-org-id"]=e),t&&(r.Authorization=`Bearer ${t}`),r},[]),g=p(()=>{if(!r.current){const t=new Si({autoProceed:!0}).use(nn,{id:"GoldenRetriever",expires:864e5,serviceWorker:!1}).use(ji,{shouldUseMultipart:!1,getUploadParameters:async e=>{const t=e.meta;return{method:"PUT",url:t.uploadUrl,fields:{},headers:{"Content-Type":t.rawContentType??e.type??"application/octet-stream"}}}});t.on("upload-progress",(t,r)=>{if(!t)return;const i=t.meta.uid;e.getState().setUploadState(i,{status:"uploading",bytesUploaded:r.bytesUploaded??0,bytesTotal:r.bytesTotal??0});const o=Date.now(),a=Object.values(e.getState().uploadStates).reduce((e,t)=>e+(t.bytesUploaded||0),0),s=n.current;if(s){const t=(o-s.time)/1e3;if(t>=.5){const r=Math.max(0,(a-s.bytes)/t),i=s.speed>0?.7*s.speed+.3*r:r;n.current={time:o,bytes:a,speed:i},e.getState().setUploadSpeedBps(i)}}else n.current={time:o,bytes:a,speed:0}}),t.on("upload-success",r=>{if(!r)return;const i=r.meta.uid,a=r.meta.contentId,s=r.meta.key,l=r.meta.uploadStartedAt;(async()=>{try{const e=await fetch(y.UPLOAD_COMPLETE,{method:"POST",headers:m(),body:JSON.stringify({contentId:a,key:s,clientUploadMs:l?Date.now()-l:void 0})});if(!e.ok){let t=`complete failed: ${e.status}`;try{const r=await e.json();r.error&&(t=`${r.error} (${e.status})`)}catch{}throw new Error(t)}}catch(d){return e.getState().setUploadState(i,{status:"error",error:d instanceof Error?d.message:String(d)}),ge(d instanceof Error?d:new Error(String(d)),{component:"useUpload",tags:["upload","complete"],extra:{uid:i,contentId:a}}),void(a&&fetch(y.UPLOAD_FAIL,{method:"POST",headers:m(),body:JSON.stringify({contentId:a})}).catch(()=>{}))}e.getState().setUploadState(i,{status:"success",contentId:a}),delete o.current[i];try{t.removeFile(r.id)}catch{}if(Object.values(e.getState().uploadStates).every(e=>"success"===e.status||"error"===e.status)&&(n.current=null,e.getState().setUploadSpeedBps(0),!h.current)){h.current=!0;const t=Object.values(e.getState().uploadStates).filter(e=>"success"===e.status).length;t>0&&R.success(`${t} file${1===t?"":"s"} uploaded`)}})()}),t.on("upload-error",(t,r)=>{if(!t)return;const i=t.meta.uid,o=t.meta.contentId;e.getState().setUploadState(i,{status:"error",error:r instanceof Error?r.message:String(r)}),o&&fetch(y.UPLOAD_FAIL,{method:"POST",headers:m(),body:JSON.stringify({contentId:o})}).catch(()=>{}),Object.values(e.getState().uploadStates).every(e=>"success"===e.status||"error"===e.status)&&(n.current=null,e.getState().setUploadSpeedBps(0))}),t.on("restored",()=>{const{eventId:r}=e.getState(),i=[],n={},a={};t.getFiles().forEach(e=>{const s=e.meta,l=s.uid;if(!(l&&s.eventId===r&&s.userId===c.current&&e.data instanceof Blob)){try{t.removeFile(e.id)}catch{}return}o.current[l]=e.id;const d=e.data instanceof File?e.data:new File([e.data],e.name,{type:e.type});i.push({uid:l,file:d}),"string"==typeof s.caption&&(n[l]=s.caption),a[l]={status:"uploading",bytesUploaded:e.progress?.bytesUploaded||0,bytesTotal:e.progress?.bytesTotal||e.size||0}}),0!==i.length&&e.setState(e=>({selectedFiles:[...e.selectedFiles,...i],captions:{...e.captions,...n},uploadStates:{...e.uploadStates,...a},hasStarted:!0,showRestoreDialog:!0,restoredUids:i.map(e=>e.uid)}))}),r.current=t}return r.current},[e,m]);i(()=>{g()},[g]);const v=p(async(t,r)=>{const{eventId:i,groupId:n,captions:a,originalFiles:u,trimRanges:h,cropSelections:p,activeFilters:f,skipUploadFilters:v,perFileFilterSkipped:b}=e.getState();let w=u[t];if(!w)return!1;const x=g();try{w=await D(w),e.getState().setUploadState(t,{status:"creating",bytesUploaded:0,bytesTotal:w.size,error:void 0});const u=L(w)?"VIDEO":"IMAGE",g=await z(w);if(s.current!==r)return!1;const S=d.current[t]??=await async function(e){try{return await(t=L(e)?function(e){return new Promise((t,r)=>{const i=URL.createObjectURL(e),n=document.createElement("video");n.muted=!0,n.playsInline=!0,n.preload="auto";let o=!1;const a=(e,a)=>{o||(o=!0,n.removeAttribute("src"),n.load(),URL.revokeObjectURL(i),e?t(e):r(a??/* @__PURE__ */new Error("video intrinsics failed")))};n.onloadedmetadata=()=>{try{n.currentTime=Math.min(.1,n.duration||.1)}catch{}},n.onseeked=()=>{const e=n.videoWidth,t=n.videoHeight,r={...e>0&&t>0&&{dimension:{width:e,height:t}},...Number.isFinite(n.duration)&&n.duration>0&&{duration:n.duration}};try{a({...r,...dr(n,e,t)})}catch(i){console.warn("[media-intrinsics] video frame sample failed:",i),a(r)}},n.onerror=()=>a(void 0,/* @__PURE__ */new Error("video load failed")),n.src=i})}(e):async function(e){const t=await D(e),r=await createImageBitmap(t);try{return{dimension:{width:r.width,height:r.height},...dr(r,r.width,r.height)}}finally{r.close()}}(e),new Promise((e,r)=>{const i=setTimeout(()=>r(/* @__PURE__ */new Error("intrinsics timeout")),8e3);t.then(t=>{clearTimeout(i),e(t)},e=>{clearTimeout(i),r(e)})}))}catch(r){return console.warn("[media-intrinsics] extraction failed:",r),{}}var t}(w);if(s.current!==r)return!1;const T=h[t],C=p[t],F=f.length>0?b[t]??v:void 0,k=await fetch(y.UPLOAD_CREATE,{method:"POST",headers:m(),signal:l.current?.signal,body:JSON.stringify({eventId:i,groupId:n,uid:t,type:u,fileName:w.name,fileSize:w.size,rawContentType:g,caption:a[t],trimInfo:T?{start:T.startTime,end:T.endTime}:void 0,cropInfo:C,dimension:S.dimension,blurhash:S.blurhash,colors:S.colors,duration:S.duration,filtersSkipped:F})});if(!k.ok){let e=`create failed: ${k.status}`;try{const t=await k.json();t.error&&(e=t.error)}catch{}throw new Error(e)}const{contentId:_,key:E,uploadUrl:M}=await k.json();if(s.current!==r)return fetch(y.UPLOAD_ABORT,{method:"POST",headers:m(),body:JSON.stringify({contentId:_,key:E})}).catch(()=>{}),!1;const U=o.current[t];if(U&&x.getFile(U))try{x.removeFile(U)}catch{}const R=x.addFile({name:w.name,type:g,data:w,meta:{uid:t,userId:c.current,contentId:_,key:E,uploadUrl:M,rawContentType:g,eventId:i,groupId:n,type:u,caption:a[t],uploadStartedAt:Date.now()}});return o.current[t]=R,!0}catch(S){return s.current!==r||S instanceof DOMException&&"AbortError"===S.name||(e.getState().setUploadState(t,{status:"error",error:S instanceof Error?S.message:String(S)}),ge(S instanceof Error?S:new Error(String(S)),{component:"useUpload",tags:["upload","create"],extra:{uid:t}})),!1}},[e,g,m]),b=p(async()=>{const{selectedFiles:t,oversizedUids:r}=e.getState(),i=t.filter(({uid:e})=>!r[e]);if(0===i.length)return;const n=++s.current;l.current=new AbortController;const o=g();e.getState().setHasStarted(!0),h.current=!1;for(const{uid:a}of i)e.getState().setUploadState(a,{status:"queued",bytesUploaded:0,bytesTotal:0});return await async function(e,t,r){const i=new Array(e.length);let n=0;const o=Array.from({length:Math.min(4,e.length)},async()=>{for(;n<e.length;){const t=n++;i[t]=await r(e[t])}});return await Promise.all(o),i}(i,0,({uid:e})=>v(e,n)),s.current===n?0===o.getFiles().length?(R.error("Could not start upload. Please try again."),void e.getState().setHasStarted(!1)):void(await o.upload()):void 0},[e,g,v]),w=p(()=>{s.current++,l.current?.abort(),n.current=null,o.current={},d.current={},r.current?.cancelAll(),e.getState().resetUploader()},[e]),x=p(t=>{const r=g();n.current=null;const i=o.current[t],a=i?r.getFile(i):void 0;if(a)return e.getState().setUploadState(t,{status:"uploading",bytesUploaded:0,bytesTotal:a.size??0,error:void 0}),void r.retryUpload(i).catch(r=>{e.getState().setUploadState(t,{status:"error",error:r instanceof Error?r.message:String(r)})});v(t,s.current)},[e,g,v]),S=p(()=>{Object.entries(e.getState().uploadStates).filter(([,e])=>"error"===e.status).map(([e])=>e).forEach(e=>x(e))},[e,x]);return i(()=>()=>{s.current++,l.current?.abort(),r.current?.cancelAll(),r.current?.destroy(),r.current=null},[]),{startUpload:b,cancelUpload:w,retryUpload:x,retryAllUploads:S,resumeRestoredUpload:p(()=>{const t=g();l.current=new AbortController,e.setState({showRestoreDialog:!1,restoredUids:[]}),t.upload()},[e,g]),discardRestoredUpload:p(()=>{const t=g(),{restoredUids:r}=e.getState();r.forEach(r=>{const i=o.current[r];if(i){try{t.removeFile(i)}catch{}delete o.current[r]}e.getState().removeFile(r)}),e.setState(e=>{const t={...e.uploadStates};return r.forEach(e=>delete t[e]),{showRestoreDialog:!1,restoredUids:[],uploadStates:t,hasStarted:0!==e.selectedFiles.length&&e.hasStarted}})},[e,g])}}function an({eventSlug:e,event:t}){const r=f(),n=F(),o=r.props?.organizationId,s=r.user,d=Ve(),c=He(e=>e.selectedFiles),u=He(e=>e.hasStarted),m=He(e=>e.oversizedUids),g=He(e=>e.showOversizedModal),C=He(e=>e.activeFilters),k=He(e=>e.showFilterChoice),_=He(e=>e.skipUploadFilters),E=He(e=>e.showRestoreDialog),M=He(e=>e.restoredUids),[U,I]=l(!1),[P,q]=l(!1),[O,D]=l({}),[j,z]=l(!0);i(()=>{if(!s||!o)return;let t=!1;return z(!0),v.get(y.GET_UPLOAD_COUNT,{searchParams:{eventSlug:e},headers:{"x-org-id":o,...s.token?{Authorization:`Bearer ${s.token}`}:{}}}).json().then(e=>{t||D(e?.data?.uploadCount??{})}).catch(()=>{t||R.error("Failed to fetch upload count")}).finally(()=>{t||z(!1)}),()=>{t=!0}},[s,o,e]);const $=!t.uploadLimit||t.uploadLimit<=0,B=(O[x.APPROVED]??0)+(O[x.IN_REVIEW]??0),H=$?1/0:Math.max(0,(t.uploadLimit??0)-B),V=j,W=$?"Unlimited":H,G=Math.min(H,100),X=!(t.status===w.OPEN)||u||V,Y=t.enableVideo?[...ie,...ne]:ie,Q=!!t.ada,J=function({effectiveFileLimit:e,eventSlug:t}){const r=Ve();return p(i=>{const n=r.getState();if(n.hasStarted)return;const o=e=>`${e.name}-${e.size}-${e.lastModified}`,a=n.selectedFiles,s=new Set(a.map(({file:e})=>o(e))),l=i.filter(e=>{const t=o(e);return!s.has(t)&&(s.add(t),!0)}).map(e=>({uid:te(),file:e})),d=Math.max(0,e-a.length),c=l.slice(0,d),u=l.length-c.length;u>0&&(R.warn(`${u} file${u>1?"s":""} not added — you've reached your upload limit.`),fe("Upload quota limit reached","warning",{component:"UploadPageClient",tags:["upload","quota"],extra:{eventSlug:t,dropped:u,effectiveFileLimit:e}}));const h={};c.forEach(({uid:e,file:t})=>{const r=function(e){const t=L(e),r=t?b:T;return e.size>r?t?"video":"image":void 0}(t);r&&(h[e]=r)}),Object.keys(h).length>0&&(r.getState().addOversizedUids(h),fe("File size limit exceeded","warning",{component:"UploadPageClient",tags:["upload","file-size"],extra:{eventSlug:t,oversizedCount:Object.keys(h).length}}));const p={};c.forEach(({uid:e,file:t})=>{p[e]=t}),r.getState().addOriginalFiles(p),r.getState().setSelectedFiles([...a,...c]),c.forEach(({uid:e,file:t})=>{L(t)&&ue(()=>{return e=t,new Promise(t=>{const r=URL.createObjectURL(e),i=document.createElement("video");i.preload="metadata";let n=!1;const o=e=>{n||(n=!0,clearTimeout(a),i.removeAttribute("src"),i.load(),URL.revokeObjectURL(r),t(e))},a=setTimeout(()=>o(0),1e4);i.onloadedmetadata=()=>o(i.duration),i.onerror=()=>o(0),i.src=r});var e}).then(t=>{t>60&&r.getState().setTrimRange(e,{startTime:0,endTime:60})}).catch(()=>{})})},[e,t,r])}({effectiveFileLimit:G,eventSlug:e}),{startUpload:Z,cancelUpload:ee,retryUpload:se,retryAllUploads:de,resumeRestoredUpload:ce,discardRestoredUpload:he}=on(),pe=p(()=>{q(!1),u?ee():d.getState().resetUploader()},[u,ee,d]);!function(e){const t=Ve(),r=f(),n=r.props?.organizationId,o=r.user?.token;i(()=>{if(!e||!n)return;let r=!1;return v.get(y.GET_POST_PROCESSING_SETTINGS,{searchParams:{eventId:e},headers:{"x-org-id":n,...o?{Authorization:`Bearer ${o}`}:{}}}).json().then(e=>{if(r||!e?.data)return;const i=e.data.filters??[],n=e.data.showChoice??!1;t.getState().setActiveFilters(i,n&&i.length>0)}).catch(e=>{ge(e instanceof Error?e:/* @__PURE__ */new Error("Failed to load upload filters"),{component:"useUploadFilters",tags:["upload","filters"]})}),()=>{r=!0}},[e,n,o,t])}(t._id?String(t._id):void 0),i(()=>{const e={},t=t=>{Object.entries(t.uploadStates).forEach(([r,i])=>{"success"!==i.status||e[r]||t.selectedFiles.some(e=>e.uid===r)&&(e[r]=setTimeout(()=>{delete e[r],d.getState().removeFile(r)},3e3))})};t(d.getState());const r=d.subscribe(t);return()=>{r(),Object.values(e).forEach(clearTimeout)}},[d]),i(()=>{0===c.length&&u&&d.getState().resetUploader()},[c.length,u,d]),i(()=>{if(!u)return;const e=e=>{Object.values(d.getState().uploadStates).some(e=>"queued"===e.status||"creating"===e.status||"uploading"===e.status)&&e.preventDefault()};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[u,d]);const me=p(e=>d.getState().removeFile(e),[d]),ve=p(()=>{if(!Q)return!0;const e=d.getState(),t=e.selectedFiles.some(({uid:t})=>!e.oversizedUids[t]&&!e.captions[t]?.trim());return t&&R.warn("This event requires a caption on every file before uploading."),!t},[Q,d]),be=p(()=>{ve()&&(Object.keys(d.getState().oversizedUids).length>0?d.getState().setShowOversizedModal(!0):Z())},[d,Z,ve]),ye=p(()=>{!s||s.tcAccepted?be():I(!0)},[s,be]),we=p(()=>{d.getState().removeOversizedFiles(),ve()&&Z()},[d,Z,ve]),[xe,Se]=l(!1),Te=a(0),Ce=X||c.length>=G;/* @__PURE__ */
|
|
74
|
+
/* @__PURE__ */h("div",{className:"text-muted-foreground mt-3 w-full text-center text-xs italic",children:"* Only your new, original photos will be eligible for upload."})]})})})})}function Et({enabledFileTypes:e,disabled:t,onFileSelect:r}){/* @__PURE__ */
|
|
75
|
+
return h(kt,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:({isDragActive:e})=>/* @__PURE__ */h("div",{className:g("mt-2 mb-4 rounded border-2 border-dashed px-4 py-24 text-center text-sm transition-colors",t?"border-border text-muted-foreground cursor-not-allowed":e?"border-primary bg-primary/15 text-primary cursor-copy":"border-border text-primary hover:bg-primary/5 hover:border-primary cursor-pointer"),children:/* @__PURE__ */h("span",{className:"text-lg font-medium",children:e?"Drop to add files...":"+ Add more files"})})})}function Mt({enabledFileTypes:e,disabled:t,onFileSelect:r}){/* @__PURE__ */
|
|
76
|
+
return h(kt,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:()=>/* @__PURE__ */h("div",{className:g("inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-sm font-medium transition-colors",t?"border-border text-muted-foreground cursor-not-allowed":"border-primary text-primary hover:bg-primary/5 cursor-pointer"),children:[/* @__PURE__ */h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:"size-4",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M11 13v3q0 .425.288.713T12 17t.713-.288T13 16v-3h3q.425 0 .713-.288T17 12t-.288-.712T16 11h-3V8q0-.425-.288-.712T12 7t-.712.288T11 8v3H8q-.425 0-.712.288T7 12t.288.713T8 13zm1 9q-2.075 0-3.9-.788t-3.175-2.137T2.788 15.9T2 12t.788-3.9t2.137-3.175T8.1 2.788T12 2t3.9.788t3.175 2.137T21.213 8.1T22 12t-.788 3.9t-2.137 3.175t-3.175 2.138T12 22m0-2q3.35 0 5.675-2.325T20 12t-2.325-5.675T12 4T6.325 6.325T4 12t2.325 5.675T12 20m0-8"})}),/* @__PURE__ */h("span",{children:"Add more"})]})})}function Ut({uploadDisabled:e,eventName:t,isQuotaLoading:r,remainingUploads:i}){const n=r?"-":i;/* @__PURE__ */
|
|
77
|
+
return h("div",{className:"relative overflow-hidden rounded-2xl px-3 pt-6 sm:pt-0",children:[/* @__PURE__ */h("div",{className:"absolute inset-0 opacity-50"}),/* @__PURE__ */h("div",{className:"relative z-10",children:/* @__PURE__ */h("div",{className:"flex flex-col items-center justify-center gap-3",children:/* @__PURE__ */h("div",{className:"flex items-center gap-3",children:/* @__PURE__ */h("div",{className:"space-y-1 text-center",children:[t&&/* @__PURE__ */h(E,{variant:"h4",align:"center",className:"line-clamp-2",children:t}),/* @__PURE__ */h("p",{className:g("text-sm font-medium",e?"text-muted-foreground":"text-foreground"),children:["Remaining Uploads: ",/* @__PURE__ */h("span",{className:"text-primary font-bold",children:n})]})]})})})})]})}var Rt=Object.defineProperty,It=Object.getOwnPropertyNames,Nt=(e,t)=>function(){return e&&(t=(0,e[It(e)[0]])(e=0)),t},Ot=(e,t)=>{for(var r in t)Rt(e,r,{get:t[r],enumerable:!0})};function Pt(e){const t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function qt(e){const t=e<=.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055;return Math.round(Math.max(0,Math.min(255,255*t)))}function At(e,t,r){const i=Pt(e),n=Pt(t),o=Pt(r),a=.4122214708*i+.5363325363*n+.0514459929*o,s=.2119034982*i+.6806995451*n+.1073969566*o,l=.0883024619*i+.2817188376*n+.6299787005*o,d=Math.cbrt(a),c=Math.cbrt(s),u=Math.cbrt(l),h=.2104542553*d+.793617785*c-.0040720468*u,p=1.9779984951*d-2.428592205*c+.4505937099*u,m=.0259040371*d+.7827717662*c-.808675766*u,g=Math.sqrt(p*p+m*m);let f=Math.atan2(m,p)*(180/Math.PI);return f<0&&(f+=360),{l:h,c:g,h:f}}function Dt(e,t,r){const i=r*(Math.PI/180),n=t*Math.cos(i),o=t*Math.sin(i),a=e+.3963377774*n+.2158037573*o,s=e-.1055613458*n-.0638541728*o,l=e-.0894841775*n-1.291485548*o,d=a*a*a,c=s*s*s,u=l*l*l,h=-1.2684380046*d+2.6097574011*c-.3413193965*u,p=-.0041960863*d-.7034186147*c+1.707614701*u;return[qt(4.0767416621*d-3.3077115913*c+.2309699292*u),qt(h),qt(p)]}var Lt,jt=Nt({"src/color-space.ts"(){}});function zt(e,t){return(Math.max(e,t)+.05)/(Math.min(e,t)+.05)}function $t(e,t,r,i,n=0){return new Lt(e,t,r,i,n)}var Bt=Nt({"src/color.ts"(){jt(),Lt=class{constructor(e,t,r,i,n){this._r=e,this._g=t,this._b=r,this.population=i,this.proportion=n}rgb(){return{r:this._r,g:this._g,b:this._b}}hex(){const e=e=>e.toString(16).padStart(2,"0");return`#${e(this._r)}${e(this._g)}${e(this._b)}`}hsl(){return this._hsl||(this._hsl=function(e,t,r){const i=e/255,n=t/255,o=r/255,a=Math.max(i,n,o),s=Math.min(i,n,o),l=(a+s)/2;let d=0,c=0;if(a!==s){const e=a-s;c=l>.5?e/(2-a-s):e/(a+s),d=a===i?((n-o)/e+(n<o?6:0))/6:a===n?((o-i)/e+2)/6:((i-n)/e+4)/6}return{h:Math.round(360*d),s:Math.round(100*c),l:Math.round(100*l)}}(this._r,this._g,this._b)),this._hsl}oklch(){return this._oklch||(this._oklch=At(this._r,this._g,this._b)),this._oklch}css(e="rgb"){switch(e){case"hsl":{const{h:e,s:t,l:r}=this.hsl();return`hsl(${e}, ${t}%, ${r}%)`}case"oklch":{const{l:e,c:t,h:r}=this.oklch();return`oklch(${e.toFixed(3)} ${t.toFixed(3)} ${r.toFixed(1)})`}default:return`rgb(${this._r}, ${this._g}, ${this._b})`}}array(){return[this._r,this._g,this._b]}toString(){return this.hex()}get textColor(){return this.isDark?"#ffffff":"#000000"}get luminance(){return void 0===this._luminance&&(this._luminance=function(e,t,r){const i=e=>{const t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)};return.2126*i(e)+.7152*i(t)+.0722*i(r)}(this._r,this._g,this._b)),this._luminance}get isDark(){return this.luminance<=.179}get isLight(){return!this.isDark}get contrast(){if(!this._contrast){const e=this.luminance,t=zt(e,1),r=zt(e,0),i=this.isDark?$t(255,255,255,0,0):$t(0,0,0,0,0);this._contrast={white:Math.round(100*t)/100,black:Math.round(100*r)/100,foreground:i}}return this._contrast}}}});function Ht(e){let{colorCount:t,quality:r}=e;if(void 0!==t&&Number.isInteger(t)){if(1===t)throw new Error("colorCount should be between 2 and 20. To get one color, call getColor() instead of getPalette()");t=Math.max(t,2),t=Math.min(t,20)}else t=10;return(void 0===r||!Number.isInteger(r)||r<1)&&(r=10),{colorCount:t,quality:r,ignoreWhite:void 0===e.ignoreWhite||!!e.ignoreWhite,whiteThreshold:"number"==typeof e.whiteThreshold?e.whiteThreshold:250,alphaThreshold:"number"==typeof e.alphaThreshold?e.alphaThreshold:125,minSaturation:"number"==typeof e.minSaturation?Math.max(0,Math.min(1,e.minSaturation)):0,colorSpace:e.colorSpace??"oklch"}}function Vt(e,t,r,i){const{ignoreWhite:n=!0,whiteThreshold:o=250,alphaThreshold:a=125,minSaturation:s=0}=i,l=[];for(let d=0;d<t;d+=r){const t=4*d,r=e[t],i=e[t+1],c=e[t+2],u=e[t+3];if(!(void 0!==u&&u<a||n&&r>o&&i>o&&c>o)){if(s>0){const e=Math.max(r,i,c);if(0===e||(e-Math.min(r,i,c))/e<s)continue}l.push([r,i,c])}}return l}function Wt(e,t,r){let i=0,n=0,o=0,a=0;for(let s=0;s<t;s+=r){const t=4*s;i+=e[t],n+=e[t+1],o+=e[t+2],a++}return 0===a?null:[Math.round(i/a),Math.round(n/a),Math.round(o/a)]}function Gt(e,t,r,i,n){const o=t*r,a={ignoreWhite:i.ignoreWhite,whiteThreshold:i.whiteThreshold,alphaThreshold:i.alphaThreshold,minSaturation:i.minSaturation};let s,l=Vt(e,o,i.quality,a);if(0===l.length&&(l=Vt(e,o,i.quality,{...a,ignoreWhite:!1})),0===l.length&&(l=Vt(e,o,i.quality,{...a,ignoreWhite:!1,alphaThreshold:0})),"oklch"===i.colorSpace){const e=function(e){const t=new Array(e.length);for(let r=0;r<e.length;r++){const[i,n,o]=e[r],{l:a,c:s,h:l}=At(i,n,o);t[r]=[Math.round(255*a),Math.round(s/.4*255),Math.round(l/360*255)]}return t}(l);s=n.quantize(e,i.colorCount).map(({color:[e,t,r],population:i})=>({color:Dt(e/255,t/255*.4,r/255*360),population:i}))}else s=n.quantize(l,i.colorCount);if(s.length>0){const e=s.reduce((e,t)=>e+t.population,0);return s.map(({color:[t,r,i],population:n})=>$t(t,r,i,n,e>0?n/e:0))}const d=Wt(e,o,i.quality);return d?[$t(d[0],d[1],d[2],1,1)]:null}Ot({},{computeFallbackColor:()=>Wt,createPixelArray:()=>Vt,extractPalette:()=>Gt,validateOptions:()=>Ht});var Xt,Yt=Nt({"src/pipeline.ts"(){Bt(),jt()}});Ot({},{BrowserPixelLoader:()=>Xt});var Qt,Kt,Jt,Zt,er,tr=Nt({"src/loaders/browser.ts"(){Xt=class{async load(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)return this.loadFromImage(e);if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement)return this.loadFromCanvas(e);if("undefined"!=typeof ImageData&&e instanceof ImageData)return{data:e.data,width:e.width,height:e.height};if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)return this.loadFromVideo(e);if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return this.loadFromImageBitmap(e);if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return this.loadFromOffscreenCanvas(e);throw new Error("Unsupported source type. Expected HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap, or OffscreenCanvas.")}loadFromImage(e){if(!e.complete)throw new Error('Image has not finished loading. Wait for the "load" event before calling getColor/getPalette.');if(!e.naturalWidth)throw new Error("Image has no dimensions. It may not have loaded successfully.");const t=document.createElement("canvas"),r=t.getContext("2d"),i=t.width=e.naturalWidth,n=t.height=e.naturalHeight;r.drawImage(e,0,0,i,n);try{return{data:r.getImageData(0,0,i,n).data,width:i,height:n}}catch(o){if(o instanceof DOMException&&"SecurityError"===o.name){const e=/* @__PURE__ */new Error('Image is tainted by cross-origin data. Add crossorigin="anonymous" to the <img> tag and ensure the server sends appropriate CORS headers.');throw e.cause=o,e}throw o}}loadFromCanvas(e){const t=e.getContext("2d"),{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}loadFromVideo(e){if(e.readyState<2)throw new Error('Video is not ready. Wait for the "loadeddata" or "canplay" event before calling getColor/getPalette.');const t=e.videoWidth,r=e.videoHeight;if(!t||!r)throw new Error("Video has no dimensions. It may not have loaded successfully.");const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=t,i.height=r,n.drawImage(e,0,0,t,r),{data:n.getImageData(0,0,t,r).data,width:t,height:r}}loadFromOffscreenCanvas(e){const t=e.getContext("2d");if(!t)throw new Error("Could not get 2D context from OffscreenCanvas.");const{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}loadFromImageBitmap(e){const t=document.createElement("canvas"),r=t.getContext("2d");return t.width=e.width,t.height=e.height,r.drawImage(e,0,0),{data:r.getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}}}}}),rr=Nt({"src/worker/worker-script.ts"(){Qt="\n'use strict';\n\n// -------------------------------------------------------------------------\n// Inlined MMCQ (Modified Median Cut Quantization)\n// -------------------------------------------------------------------------\n\nvar SIGBITS = 5;\nvar RSHIFT = 3;\nvar MAX_ITER = 1000;\nvar FRACT_POP = 0.75;\nvar HISTO_SIZE = 32768;\n\nfunction colorIndex(r, g, b) {\n return (r << 10) + (g << 5) + b;\n}\n\nfunction getHisto(pixels) {\n var h = new Uint32Array(HISTO_SIZE);\n for (var i = 0; i < pixels.length; i++) {\n var p = pixels[i];\n h[colorIndex(p[0] >> RSHIFT, p[1] >> RSHIFT, p[2] >> RSHIFT)]++;\n }\n return h;\n}\n\nfunction VBox(r1, r2, g1, g2, b1, b2, histo) {\n this.r1 = r1; this.r2 = r2;\n this.g1 = g1; this.g2 = g2;\n this.b1 = b1; this.b2 = b2;\n this.histo = histo;\n this._count = -1;\n this._volume = -1;\n this._avg = null;\n}\n\nVBox.prototype.volume = function(force) {\n if (this._volume < 0 || force) {\n this._volume = (this.r2 - this.r1 + 1) * (this.g2 - this.g1 + 1) * (this.b2 - this.b1 + 1);\n }\n return this._volume;\n};\n\nVBox.prototype.count = function(force) {\n if (this._count < 0 || force) {\n var n = 0;\n for (var i = this.r1; i <= this.r2; i++)\n for (var j = this.g1; j <= this.g2; j++)\n for (var k = this.b1; k <= this.b2; k++)\n n += this.histo[colorIndex(i, j, k)] || 0;\n this._count = n;\n }\n return this._count;\n};\n\nVBox.prototype.copy = function() {\n return new VBox(this.r1, this.r2, this.g1, this.g2, this.b1, this.b2, this.histo);\n};\n\nVBox.prototype.avg = function(force) {\n if (!this._avg || force) {\n var mult = 1 << RSHIFT;\n if (this.r1 === this.r2 && this.g1 === this.g2 && this.b1 === this.b2) {\n this._avg = [this.r1 << RSHIFT, this.g1 << RSHIFT, this.b1 << RSHIFT];\n } else {\n var ntot = 0, rsum = 0, gsum = 0, bsum = 0;\n for (var i = this.r1; i <= this.r2; i++)\n for (var j = this.g1; j <= this.g2; j++)\n for (var k = this.b1; k <= this.b2; k++) {\n var hval = this.histo[colorIndex(i, j, k)] || 0;\n ntot += hval;\n rsum += hval * (i + 0.5) * mult;\n gsum += hval * (j + 0.5) * mult;\n bsum += hval * (k + 0.5) * mult;\n }\n this._avg = ntot\n ? [~~(rsum / ntot), ~~(gsum / ntot), ~~(bsum / ntot)]\n : [~~(mult * (this.r1 + this.r2 + 1) / 2), ~~(mult * (this.g1 + this.g2 + 1) / 2), ~~(mult * (this.b1 + this.b2 + 1) / 2)];\n }\n }\n return this._avg;\n};\n\nfunction PQueue(comparator) {\n this.contents = [];\n this.sorted = false;\n this.comparator = comparator;\n}\n\nPQueue.prototype.push = function(item) { this.contents.push(item); this.sorted = false; };\nPQueue.prototype.pop = function() {\n if (!this.sorted) { this.contents.sort(this.comparator); this.sorted = true; }\n return this.contents.pop();\n};\nPQueue.prototype.size = function() { return this.contents.length; };\n\nfunction vboxFromPixels(pixels, histo) {\n var rmin = 1e6, rmax = 0, gmin = 1e6, gmax = 0, bmin = 1e6, bmax = 0;\n for (var i = 0; i < pixels.length; i++) {\n var p = pixels[i];\n var rv = p[0] >> RSHIFT, gv = p[1] >> RSHIFT, bv = p[2] >> RSHIFT;\n if (rv < rmin) rmin = rv; if (rv > rmax) rmax = rv;\n if (gv < gmin) gmin = gv; if (gv > gmax) gmax = gv;\n if (bv < bmin) bmin = bv; if (bv > bmax) bmax = bv;\n }\n return new VBox(rmin, rmax, gmin, gmax, bmin, bmax, histo);\n}\n\nfunction medianCutApply(histo, vbox) {\n if (!vbox.count()) return undefined;\n if (vbox.count() === 1) return [vbox.copy(), null];\n\n var rw = vbox.r2 - vbox.r1 + 1;\n var gw = vbox.g2 - vbox.g1 + 1;\n var bw = vbox.b2 - vbox.b1 + 1;\n var maxw = Math.max(rw, gw, bw);\n var total = 0;\n var partialsum = [];\n var lookaheadsum = [];\n var i, j, k, sum;\n\n if (maxw === rw) {\n for (i = vbox.r1; i <= vbox.r2; i++) {\n sum = 0;\n for (j = vbox.g1; j <= vbox.g2; j++)\n for (k = vbox.b1; k <= vbox.b2; k++)\n sum += histo[colorIndex(i, j, k)] || 0;\n total += sum; partialsum[i] = total;\n }\n } else if (maxw === gw) {\n for (i = vbox.g1; i <= vbox.g2; i++) {\n sum = 0;\n for (j = vbox.r1; j <= vbox.r2; j++)\n for (k = vbox.b1; k <= vbox.b2; k++)\n sum += histo[colorIndex(j, i, k)] || 0;\n total += sum; partialsum[i] = total;\n }\n } else {\n for (i = vbox.b1; i <= vbox.b2; i++) {\n sum = 0;\n for (j = vbox.r1; j <= vbox.r2; j++)\n for (k = vbox.g1; k <= vbox.g2; k++)\n sum += histo[colorIndex(j, k, i)] || 0;\n total += sum; partialsum[i] = total;\n }\n }\n\n partialsum.forEach(function(d, idx) { lookaheadsum[idx] = total - d; });\n\n function doCut(color) {\n var dim1 = color + '1', dim2 = color + '2';\n for (var i = vbox[dim1]; i <= vbox[dim2]; i++) {\n if (partialsum[i] > total / 2) {\n var vbox1 = vbox.copy(), vbox2 = vbox.copy();\n var left = i - vbox[dim1], right = vbox[dim2] - i;\n var d2 = left <= right\n ? Math.min(vbox[dim2] - 1, ~~(i + right / 2))\n : Math.max(vbox[dim1], ~~(i - 1 - left / 2));\n while (!partialsum[d2]) d2++;\n var count2 = lookaheadsum[d2];\n while (!count2 && partialsum[d2 - 1]) count2 = lookaheadsum[--d2];\n vbox1[dim2] = d2;\n vbox2[dim1] = d2 + 1;\n return [vbox1, vbox2];\n }\n }\n }\n\n if (maxw === rw) return doCut('r');\n if (maxw === gw) return doCut('g');\n return doCut('b');\n}\n\nfunction iterate(pq, target, histo) {\n var ncolors = pq.size(), niters = 0;\n while (niters < MAX_ITER) {\n if (ncolors >= target) return;\n niters++;\n var vbox = pq.pop();\n if (!vbox.count()) { pq.push(vbox); continue; }\n var result = medianCutApply(histo, vbox);\n if (!result || !result[0]) return;\n pq.push(result[0]);\n if (result[1]) { pq.push(result[1]); ncolors++; }\n }\n}\n\nfunction quantize(pixels, maxColors) {\n if (!pixels.length || maxColors < 2 || maxColors > 256) return [];\n\n var histo = getHisto(pixels);\n var vbox = vboxFromPixels(pixels, histo);\n var pq = new PQueue(function(a, b) { return a.count() - b.count(); });\n pq.push(vbox);\n iterate(pq, FRACT_POP * maxColors, histo);\n\n var pq2 = new PQueue(function(a, b) { return a.count() * a.volume() - b.count() * b.volume(); });\n while (pq.size()) pq2.push(pq.pop());\n iterate(pq2, maxColors, histo);\n\n var results = [];\n while (pq2.size()) {\n var box = pq2.pop();\n results.push({ color: box.avg(), population: box.count() });\n }\n return results;\n}\n\n// -------------------------------------------------------------------------\n// Worker message handler\n// -------------------------------------------------------------------------\n\nself.onmessage = function (e) {\n var data = e.data;\n var id = data.id;\n try {\n var palette = quantize(data.pixels, data.maxColors);\n self.postMessage({ id: id, palette: palette });\n } catch (err) {\n self.postMessage({ id: id, error: err.message || 'Unknown worker error' });\n }\n};\n"}});function ir(){return"undefined"!=typeof Worker}function nr(e,t,r){return new Promise((i,n)=>{if(r?.aborted)return void n(r.reason??new DOMException("Aborted","AbortError"));const o=Zt++;er.set(o,{resolve:i,reject:n});const a=()=>{er.delete(o),n(r.reason??new DOMException("Aborted","AbortError"))};r?.addEventListener("abort",a,{once:!0});try{(function(){if(Kt)return Kt;if(!ir())throw new Error("Web Workers are not supported in this environment.");return Jt=URL.createObjectURL(new Blob([Qt],{type:"application/javascript"})),(Kt=new Worker(Jt)).onmessage=e=>{const{id:t,palette:r,error:i}=e.data,n=er.get(t);if(n)if(er.delete(t),i)n.reject(new Error(i));else{const e=r,t=e.reduce((e,t)=>e+t.population,0),i=e.map(({color:[e,r,i],population:n})=>$t(e,r,i,n,t>0?n/t:0));n.resolve(i)}},Kt.onerror=e=>{for(const[,t]of er)t.reject(new Error(e.message));er.clear()},Kt})().postMessage({id:o,pixels:e,maxColors:t})}catch(s){er.delete(o),r?.removeEventListener("abort",a),n(s)}})}function or(){Kt&&(Kt.terminate(),Kt=null),Jt&&(URL.revokeObjectURL(Jt),Jt=null);for(const[,e]of er)e.reject(/* @__PURE__ */new Error("Worker terminated"));er.clear()}function ar(e,t,r){return(e<<10)+(t<<5)+r}Ot({},{extractInWorker:()=>nr,isWorkerSupported:()=>ir,terminateWorker:()=>or}),Nt({"src/worker/manager.ts"(){Bt(),rr(),Kt=null,Jt=null,Zt=0,er=/* @__PURE__ */new Map}}),Yt(),Yt(),Bt(),$t(255,255,255,0),$t(0,0,0,0);var sr=class e{constructor(e,t,r,i,n,o,a){this.r1=e,this.r2=t,this.g1=r,this.g2=i,this.b1=n,this.b2=o,this.histo=a}volume(e=!1){return(void 0===this._volume||e)&&(this._volume=(this.r2-this.r1+1)*(this.g2-this.g1+1)*(this.b2-this.b1+1)),this._volume}count(e=!1){if(void 0===this._count||e){let e=0;for(let t=this.r1;t<=this.r2;t++)for(let r=this.g1;r<=this.g2;r++)for(let i=this.b1;i<=this.b2;i++)e+=this.histo[ar(t,r,i)]||0;this._count=e}return this._count}copy(){return new e(this.r1,this.r2,this.g1,this.g2,this.b1,this.b2,this.histo)}avg(e=!1){if(void 0===this._avg||e){const e=8;if(this.r1===this.r2&&this.g1===this.g2&&this.b1===this.b2)this._avg=[this.r1<<3,this.g1<<3,this.b1<<3];else{let t=0,r=0,i=0,n=0;for(let o=this.r1;o<=this.r2;o++)for(let a=this.g1;a<=this.g2;a++)for(let s=this.b1;s<=this.b2;s++){const l=this.histo[ar(o,a,s)]||0;t+=l,r+=l*(o+.5)*e,i+=l*(a+.5)*e,n+=l*(s+.5)*e}this._avg=t?[~~(r/t),~~(i/t),~~(n/t)]:[~~(e*(this.r1+this.r2+1)/2),~~(e*(this.g1+this.g2+1)/2),~~(e*(this.b1+this.b2+1)/2)]}}return this._avg}},lr=class{constructor(e){this.comparator=e,this.contents=[],this.sorted=!1}sort(){this.contents.sort(this.comparator),this.sorted=!0}push(e){this.contents.push(e),this.sorted=!1}peek(e){return this.sorted||this.sort(),this.contents[e??this.contents.length-1]}pop(){return this.sorted||this.sort(),this.contents.pop()}size(){return this.contents.length}map(e){return this.contents.map(e)}};function dr(e,t){if(!t.count())return;if(1===t.count())return[t.copy(),null];const r=t.r2-t.r1+1,i=t.g2-t.g1+1,n=t.b2-t.b1+1,o=Math.max(r,i,n);let a=0;const s=[],l=[];if(o===r)for(let d=t.r1;d<=t.r2;d++){let r=0;for(let i=t.g1;i<=t.g2;i++)for(let n=t.b1;n<=t.b2;n++)r+=e[ar(d,i,n)]||0;a+=r,s[d]=a}else if(o===i)for(let d=t.g1;d<=t.g2;d++){let r=0;for(let i=t.r1;i<=t.r2;i++)for(let n=t.b1;n<=t.b2;n++)r+=e[ar(i,d,n)]||0;a+=r,s[d]=a}else for(let d=t.b1;d<=t.b2;d++){let r=0;for(let i=t.r1;i<=t.r2;i++)for(let n=t.g1;n<=t.g2;n++)r+=e[ar(i,n,d)]||0;a+=r,s[d]=a}return s.forEach((e,t)=>{l[t]=a-e}),function(e){const r=e+"1",i=e+"2";for(let n=t[r];n<=t[i];n++)if(s[n]>a/2){const e=t.copy(),o=t.copy(),a=n-t[r],d=t[i]-n;let c;for(c=a<=d?Math.min(t[i]-1,~~(n+d/2)):Math.max(t[r],~~(n-1-a/2));!s[c];)c++;let u=l[c];for(;!u&&s[c-1];)u=l[--c];return e[i]=c,o[r]=e[i]+1,[e,o]}}(o===r?"r":o===i?"g":"b")}function cr(e,t,r){let i=e.size(),n=0;for(;n<1e3;){if(i>=t)return;n++;const o=e.pop();if(!o.count()){e.push(o);continue}const a=dr(r,o);if(!a||!a[0])return;e.push(a[0]),a[1]&&(e.push(a[1]),i++)}}tr(),Yt(),new Xt;var ur=new class{async init(){}quantize(e,t){return function(e,t){if(!e.length||t<2||t>256)return[];const r=/* @__PURE__ */new Set,i=[];for(const d of e){const e=d.join(",");r.has(e)||(r.add(e),i.push(d))}if(i.length<=t){const t=/* @__PURE__ */new Map;for(const r of e){const e=r.join(",");t.set(e,(t.get(e)||0)+1)}return i.map(e=>({color:e,population:t.get(e.join(","))}))}const n=function(e){const t=new Uint32Array(32768);for(const r of e)t[ar(r[0]>>3,r[1]>>3,r[2]>>3)]++;return t}(e),o=function(e,t){let r=1e6,i=0,n=1e6,o=0,a=1e6,s=0;for(const l of e){const e=l[0]>>3,t=l[1]>>3,d=l[2]>>3;e<r?r=e:e>i&&(i=e),t<n?n=t:t>o&&(o=t),d<a?a=d:d>s&&(s=d)}return new sr(r,i,n,o,a,s,t)}(e,n),a=new lr((e,t)=>e.count()-t.count());a.push(o),cr(a,.75*t,n);const s=new lr((e,t)=>e.count()*e.volume()-t.count()*t.volume());for(;a.size();)s.push(a.pop());cr(s,t,n);const l=[];for(;s.size();){const e=s.pop();l.push({color:e.avg(),population:e.count()})}return l}(e,t)}};function hr(e,t,r){if(t<=0||r<=0)return{};const i=Math.min(1,128/Math.max(t,r)),n=Math.max(1,Math.round(t*i)),o=Math.max(1,Math.round(r*i)),a=new OffscreenCanvas(n,o),s=a.getContext("2d",{willReadFrequently:!0});if(!s)return{};s.drawImage(e,0,0,n,o);const l=s.getImageData(0,0,n,o),d={};try{d.blurhash=U(l.data,n,o,4,4)}catch(c){console.warn("[media-intrinsics] blurhash encode failed:",c)}try{const e=function(e,t){const r=Ht(t??{}),i=t?.quantizer??ur,n=function(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)return function(e){if(!e.complete)throw new Error('Image has not finished loading. Wait for the "load" event before calling getColorSync/getPaletteSync.');if(!e.naturalWidth)throw new Error("Image has no dimensions. It may not have loaded successfully.");const t=document.createElement("canvas"),r=t.getContext("2d"),i=t.width=e.naturalWidth,n=t.height=e.naturalHeight;r.drawImage(e,0,0,i,n);try{return{data:r.getImageData(0,0,i,n).data,width:i,height:n}}catch(o){if(o instanceof DOMException&&"SecurityError"===o.name){const e=/* @__PURE__ */new Error('Image is tainted by cross-origin data. Add crossorigin="anonymous" to the <img> tag and ensure the server sends appropriate CORS headers.');throw e.cause=o,e}throw o}}(e);if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement)return function(e){const t=e.getContext("2d"),{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}(e);if("undefined"!=typeof ImageData&&e instanceof ImageData)return{data:e.data,width:e.width,height:e.height};if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)return function(e){if(e.readyState<2)throw new Error('Video is not ready. Wait for the "loadeddata" or "canplay" event before calling getColorSync/getPaletteSync.');const t=e.videoWidth,r=e.videoHeight;if(!t||!r)throw new Error("Video has no dimensions. It may not have loaded successfully.");const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=t,i.height=r,n.drawImage(e,0,0,t,r),{data:n.getImageData(0,0,t,r).data,width:t,height:r}}(e);if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return function(e){const t=document.createElement("canvas"),r=t.getContext("2d");return t.width=e.width,t.height=e.height,r.drawImage(e,0,0),{data:r.getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}}(e);if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return function(e){const t=e.getContext("2d");if(!t)throw new Error("Could not get 2D context from OffscreenCanvas.");const{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}(e);throw new Error("Unsupported source type. Expected HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap, or OffscreenCanvas.")}(e);return Gt(n.data,n.width,n.height,r,i)}(a,{colorCount:5});e&&(d.colors={palette:e.map(e=>e.hex())})}catch(c){console.warn("[media-intrinsics] palette extraction failed:",c)}return d}function pr(e,t){return Object.hasOwn(e,t)}Bt();var{AbortController:mr}=globalThis,{AbortSignal:gr}=globalThis,fr=(e="Aborted",t)=>{const r=new DOMException(e,"AbortError");return null!=t&&pr(t,"cause")&&Object.defineProperty(r,"cause",{__proto__:null,configurable:!0,writable:!0,value:t.cause}),r},vr=class extends Error{isNetworkError;cause;constructor(e,t){super(e),this.cause=t?.cause,this.cause&&pr(this.cause,"isNetworkError")?this.isNetworkError=this.cause.isNetworkError:this.isNetworkError=!1}},br=class extends Error{cause;isNetworkError;request;constructor(e,t=null){super("This looks like a network error, the endpoint might be blocked by an internet provider or a firewall."),this.cause=e,this.isNetworkError=!0,this.request=t}};function yr(e){const t=e.lastIndexOf(".");return-1===t||t===e.length-1?{name:e,extension:void 0}:{name:e.slice(0,t),extension:e.slice(t+1)}}var wr={__proto__:null,md:"text/markdown",markdown:"text/markdown",mp4:"video/mp4",mp3:"audio/mp3",svg:"image/svg+xml",jpg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",heic:"image/heic",heif:"image/heif",yaml:"text/yaml",yml:"text/yaml",csv:"text/csv",tsv:"text/tab-separated-values",tab:"text/tab-separated-values",avi:"video/x-msvideo",mks:"video/x-matroska",mkv:"video/x-matroska",mov:"video/quicktime",dicom:"application/dicom",doc:"application/msword",msg:"application/vnd.ms-outlook",docm:"application/vnd.ms-word.document.macroenabled.12",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",dot:"application/msword",dotm:"application/vnd.ms-word.template.macroenabled.12",dotx:"application/vnd.openxmlformats-officedocument.wordprocessingml.template",xla:"application/vnd.ms-excel",xlam:"application/vnd.ms-excel.addin.macroenabled.12",xlc:"application/vnd.ms-excel",xlf:"application/x-xliff+xml",xlm:"application/vnd.ms-excel",xls:"application/vnd.ms-excel",xlsb:"application/vnd.ms-excel.sheet.binary.macroenabled.12",xlsm:"application/vnd.ms-excel.sheet.macroenabled.12",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xlt:"application/vnd.ms-excel",xltm:"application/vnd.ms-excel.template.macroenabled.12",xltx:"application/vnd.openxmlformats-officedocument.spreadsheetml.template",xlw:"application/vnd.ms-excel",txt:"text/plain",text:"text/plain",conf:"text/plain",log:"text/plain",pdf:"application/pdf",zip:"application/zip","7z":"application/x-7z-compressed",rar:"application/x-rar-compressed",tar:"application/x-tar",gz:"application/gzip",dmg:"application/x-apple-diskimage"};function xr(e){if(e.type)return e.type;const t=e.name?yr(e.name).extension?.toLowerCase():null;return t&&t in wr?wr[t]:"application/octet-stream"}function Sr(e){let t="";return e.replace(/[^A-Z0-9]/gi,e=>(t+=`-${function(e){return e.charCodeAt(0).toString(32)}(e)}`,"/"))+t}function Tr(e,t){return!0===e?Object.keys(t):Array.isArray(e)?e:[]}function Cr(e){return e<10?`0${e}`:e.toString()}function Fr(){const e=/* @__PURE__ */new Date;return`${Cr(e.getHours())}:${Cr(e.getMinutes())}:${Cr(e.getSeconds())}`}function kr(e){if(null!=e){const t=()=>this.abort(e.reason);e.addEventListener("abort",t,{once:!0});const r=()=>{e.removeEventListener("abort",t)};this.then?.(r,r)}return this}var _r=class{#e=0;#t=[];#r=!1;#i;#n=1;#o;#a;limit;constructor(e){this.limit="number"!=typeof e||0===e?1/0:e}#s(e){this.#e+=1;let t,r=!1;try{t=e()}catch(i){throw this.#e-=1,i}return{abort:e=>{r||(r=!0,this.#e-=1,t?.(e),this.#l())},done:()=>{r||(r=!0,this.#e-=1,this.#l())}}}#l(){queueMicrotask(()=>this.#d())}#d(){if(this.#r||this.#e>=this.limit)return;if(0===this.#t.length)return;const e=this.#t.shift();if(null==e)throw new Error("Invariant violation: next is null");const t=this.#s(e.fn);e.abort=t.abort,e.done=t.done}#c(e,t){const r={fn:e,priority:t?.priority||0,abort:()=>{this.#u(r)},done:()=>{throw new Error("Cannot mark a queued request as done: this indicates a bug")}},i=this.#t.findIndex(e=>r.priority>e.priority);return-1===i?this.#t.push(r):this.#t.splice(i,0,r),r}#u(e){const t=this.#t.indexOf(e);-1!==t&&this.#t.splice(t,1)}run(e,t){return!this.#r&&this.#e<this.limit?this.#s(e):this.#c(e,t)}wrapSyncFunction(e,t){return(...r)=>{const i=this.run(()=>(e(...r),queueMicrotask(()=>i.done()),()=>{}),t);return{abortOn:kr,abort(){i.abort()}}}}wrapPromiseFunction(e,t){return(...r)=>{let i;const n=new Promise((n,o)=>{i=this.run(()=>{let t,a;try{a=Promise.resolve(e(...r))}catch(s){a=Promise.reject(s)}return a.then(e=>{t?o(t):(i.done(),n(e))},e=>{t?o(t):(i.done(),o(e))}),e=>{t=function(e){return new Error("Cancelled",{cause:e})}(e)}},t)});return n.abort=e=>{i.abort(e)},n.abortOn=kr,n}}resume(){this.#r=!1,clearTimeout(this.#i);for(let e=0;e<this.limit;e++)this.#l()}#h=()=>this.resume();pause(e=null){this.#r=!0,clearTimeout(this.#i),null!=e&&(this.#i=setTimeout(this.#h,e))}rateLimit(e){clearTimeout(this.#a),this.pause(e),this.limit>1&&Number.isFinite(this.limit)&&(this.#o=this.limit-1,this.limit=this.#n,this.#a=setTimeout(this.#p,e))}#p=()=>{if(this.#r)this.#a=setTimeout(this.#p,0);else{this.#n=this.limit,this.limit=Math.ceil((this.#o+this.#n)/2);for(let e=this.#n;e<=this.limit;e++)this.#l();this.#o-this.#n>3?this.#a=setTimeout(this.#p,2e3):this.#n=Math.floor(this.#n/2)}};get isPaused(){return this.#r}};function Er(e,t,r){const i=[];return e.forEach(e=>"string"!=typeof e?i.push(e):t[Symbol.split](e).forEach((e,t,n)=>{""!==e&&i.push(e),t<n.length-1&&i.push(r)})),i}function Mr(e,t){const r=/\$/g;let i=[e];if(null==t)return i;for(const n of Object.keys(t))if("_"!==n){let e=t[n];"string"==typeof e&&(e=r[Symbol.replace](e,"$$$$")),i=Er(i,new RegExp(`%\\{${n}\\}`,"g"),e)}return i}var Ur=e=>{throw new Error(`missing string: ${e}`)},Rr=class{locale;constructor(e,{onMissingKey:t=Ur}={}){this.locale={strings:{},pluralize:e=>1===e?0:1},Array.isArray(e)?e.forEach(this.#m,this):this.#m(e),this.#g=t}#g;#m(e){if(!e?.strings)return;const t=this.locale;Object.assign(this.locale,{strings:{...t.strings,...e.strings},pluralize:e.pluralize||t.pluralize})}translate(e,t){return this.translateArray(e,t).join("")}translateArray(e,t){let r=this.locale.strings[e];if(null==r&&(this.#g(e),r=e),"object"==typeof r){if(t&&void 0!==t.smart_count)return Mr(r[this.locale.pluralize(t.smart_count)],t);throw new Error("Attempted to use a string with plural forms, but no value was given for %{smart_count}")}if("string"!=typeof r)throw new Error("string was not a string");return Mr(r,t)}},Ir=class extends Error{name="UserFacingApiError"},Nr=/* @__PURE__ */t((e,t)=>{function r(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=r,r.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},r.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},r.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=/* @__PURE__ */(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(/* @__PURE__ */new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},r),this._options.unref&&this._timer.unref(),!0},r.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=/* @__PURE__ */(new Date).getTime(),this._fn(this._attempts)},r.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},r.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},r.prototype.start=r.prototype.try,r.prototype.errors=function(){return this._errors},r.prototype.attempts=function(){return this._attempts},r.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,i=0;i<this._errors.length;i++){var n=this._errors[i],o=n.message,a=(e[o]||0)+1;e[o]=a,a>=r&&(t=n,r=a)}return t}}),Or=/* @__PURE__ */t(e=>{var t=Nr();e.operation=function(r){return new t(e.timeouts(r),{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],n=0;n<t.retries;n++)i.push(this.createTimeout(n,t));return e&&e.forever&&!i.length&&i.push(this.createTimeout(n,t)),i.sort(function(e,t){return e-t}),i},e.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,i=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(i,t.maxTimeout)},e.wrap=function(t,r,i){if(r instanceof Array&&(i=r,r=null),!i)for(var n in i=[],t)"function"==typeof t[n]&&i.push(n);for(var o=0;o<i.length;o++){var a=i[o],s=t[a];t[a]=function(i){var n=e.operation(r),o=Array.prototype.slice.call(arguments,1),a=o.pop();o.push(function(e){n.retry(e)||(e&&(arguments[0]=n.mainError()),a.apply(this,arguments))}),n.attempt(function(){i.apply(t,o)})}.bind(t,s),t[a].options=r}}}),Pr=/* @__PURE__ */t((e,t)=>{t.exports=Or()}),qr=Object.prototype.toString,Ar=/* @__PURE__ */new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);var Dr=/* @__PURE__ */e(Pr(),1),Lr=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},jr=(e,t,r)=>{const i=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=i,e};async function zr(e,t){return new Promise((r,i)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const n=Dr.operation(t),o=()=>{n.stop(),i(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",o,{once:!0});const a=()=>{t.signal?.removeEventListener("abort",o),n.stop()};n.attempt(async o=>{try{const t=await e(o);a(),r(t)}catch(s){try{if(!(s instanceof Error))throw new TypeError(`Non-error was thrown: "${s}". You should only throw errors.`);if(s instanceof Lr)throw s.originalError;if(s instanceof TypeError&&!function(e){if(!e||(t=e,"[object Error]"!==qr.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)return!1;var t;const{message:r,stack:i}=e;return"Load failed"===r||r.startsWith("Load failed (")&&r.endsWith(")")?void 0===i||"__sentry_captured__"in e:!!r.startsWith("error sending request for url")||!!("Failed to fetch"===r||r.startsWith("Failed to fetch (")&&r.endsWith(")"))||Ar.has(r)}(s))throw s;if(jr(s,o,t),await t.shouldRetry(s)||(n.stop(),i(s)),await t.onFailedAttempt(s),!n.retry(s))throw n.mainError()}catch(l){jr(l,o,t),a(),i(l)}}})})}var $r=class extends Error{isAuthError;constructor(){super("Authorization required"),this.name="AuthError",this.isAuthError=!0}},Br=class extends Error{statusCode;constructor({statusCode:e,message:t}){super(t),this.name="HttpError",this.statusCode=e}},Hr=class{static VERSION="5.1.1";#f;uppy;opts;constructor(e,t){this.uppy=e,this.opts=t,this.onReceiveResponse=this.onReceiveResponse.bind(this),this.#f=t.companionHeaders}setCompanionHeaders(e){this.#f=e}[Symbol.for("uppy test: getCompanionHeaders")](){return this.#f}get hostname(){const{companion:e}=this.uppy.getState(),t=this.opts.companionUrl;return(e?.[t]?e[t]:t).replace(/\/$/,"")}async headers(e=!1){return{Accept:"application/json",...e?void 0:{"Content-Type":"application/json"},...this.#f}}onReceiveResponse(e){const{headers:t}=e,r=this.uppy.getState().companion||{},i=this.opts.companionUrl;t.has("i-am")&&t.get("i-am")!==r[i]&&this.uppy.setState({companion:{...r,[i]:t.get("i-am")}})}#v(e){return/^(https?:|)\/\//.test(e)?e:`${this.hostname}/${e}`}async request({path:e,method:t="GET",data:r,skipPostResponse:i,signal:n}){try{const o=await this.headers(!r),a=await function(...e){return fetch(...e).catch(e=>{throw"AbortError"===e.name?e:new br(e)})}(this.#v(e),{method:t,signal:n,headers:o,credentials:this.opts.companionCookiesRule||"same-origin",body:r?JSON.stringify(r):null});return i||this.onReceiveResponse(a),await async function(e){if(401===e.status)throw new $r;if(e.ok)return e.json();let t,r=`Failed request with status: ${e.status}. ${e.statusText}`;try{t=await e.json(),t.message&&(r=`${r} message: ${t.message}`),t.requestId&&(r=`${r} request-Id: ${t.requestId}`)}catch(i){throw new Error(r,{cause:i})}if(e.status>=400&&e.status<=499&&t.message)throw new Ir(t.message);throw new Br({statusCode:e.status,message:r})}(a)}catch(o){if(o.isAuthError||"UserFacingApiError"===o.name||"AbortError"===o.name)throw o;throw new vr(`Could not ${t} ${this.#v(e)}`,{cause:o})}}async get(e,t){return this.request({...t,path:e})}async post(e,t,r){return this.request({...r,path:e,method:"POST",data:t})}async delete(e,t,r){return this.request({...r,path:e,method:"DELETE",data:t})}async uploadRemoteFile(e,t,r){try{const{signal:i,getQueue:n}=r||{};return await zr(async()=>{const r=this.uppy.getFile(e.id)?.serverToken;if(null!=r)return this.uppy.log(`Connecting to exiting websocket ${r}`),this.#b({file:e,queue:n(),signal:i});const o=await n().wrapPromiseFunction(async(...e)=>{try{return await this.#y(...e)}catch(t){if(t.isAuthError)throw new Lr(t);if(null==t.cause)throw t;const e=t.cause,r=()=>[408,409,429,418,423].includes(e.statusCode)||e.statusCode>=500&&e.statusCode<=599&&![501,505].includes(e.statusCode);if("HttpError"===e.name&&!r())throw new Lr(e);throw e}},{priority:-1})({file:e,postBody:t,signal:i}).abortOn(i);return this.uppy.getFile(e.id)?(this.uppy.setFileState(e.id,{serverToken:o}),this.#b({file:this.uppy.getFile(e.id),queue:n(),signal:i})):void 0},{retries:10,signal:i,onFailedAttempt:e=>this.uppy.log(`Retrying upload due to: ${e.message}`,"warning")})}catch(i){if("AbortError"===i.name)return;throw this.uppy.emit("upload-error",e,i),i}}#y=async({file:e,postBody:t,signal:r})=>{if(null==e.remote?.url)throw new Error("Cannot connect to an undefined URL");return(await this.post(e.remote.url,{...e.remote.body,...t},{signal:r})).token};async#b({file:e,queue:t,signal:r}){let i;const{capabilities:n}=this.uppy.getState();try{return await new Promise((o,a)=>{const s=e.serverToken,l=function(e){const t=/^(?:https?:\/\/|\/\/)?(?:[^@\n]+@)?([^\n]+)/i.exec(e)?.[1];return`${/^http:\/\//i.test(e)?"ws":"wss"}://${t}`}(e.remote.companionUrl);let d,c,u,{isPaused:h}=e;const p=(t,r)=>{null!=d&&d.readyState===d.OPEN?d.send(JSON.stringify({action:t,payload:r??{}})):this.uppy.log(`Cannot send "${t}" to socket ${e.id} because the socket state was ${String(d?.readyState)}`,"warning")};function m(){n.resumableUploads&&p(h?"pause":"resume")}const g=e=>{n.resumableUploads&&(h=e,d&&m())},f=t=>{n.individualCancellation&&t.id===e.id&&(p("cancel"),c?.abort?.(),this.uppy.log(`upload ${e.id} was removed`),o())},v=()=>{p("cancel"),c?.abort?.(),this.uppy.log(`upload ${e.id} was canceled`),o()},b=(t,r)=>{t?.id===e.id&&g(r)},y=()=>g(!0),w=()=>g(!1);this.uppy.on("file-removed",f),this.uppy.on("cancel-all",v),this.uppy.on("upload-pause",b),this.uppy.on("pause-all",y),this.uppy.on("resume-all",w),i=()=>{this.uppy.off("file-removed",f),this.uppy.off("cancel-all",v),this.uppy.off("upload-pause",b),this.uppy.off("pause-all",y),this.uppy.off("resume-all",w)},r.addEventListener("abort",()=>{c?.abort()}),(async()=>{c&&c.abort(),c=new AbortController;const r=t=>{this.uppy.setFileState(e.id,{serverToken:null}),c?.abort?.(),a(t)};function i(){clearTimeout(u),h||(u=setTimeout(()=>r(/* @__PURE__ */new Error("Timeout waiting for message from Companion socket")),3e5))}try{await t.wrapPromiseFunction(async()=>{await zr(async()=>new Promise((t,n)=>{d=new WebSocket(`${l}/api/${s}`),i(),d.addEventListener("close",()=>{d=void 0,n(/* @__PURE__ */new Error("Socket closed unexpectedly"))}),d.addEventListener("error",e=>{this.uppy.log(`Companion socket error ${JSON.stringify(e)}, closing socket`,"warning"),d?.close()}),d.addEventListener("open",()=>{m()}),d.addEventListener("message",t=>{i();try{const{action:r,payload:i}=JSON.parse(t.data);switch(r){case"progress":!function(e,t,r){const{progress:i,bytesUploaded:n,bytesTotal:o}=t;i&&(e.uppy.log(`Upload progress: ${i}`),e.uppy.emit("upload-progress",r,{uploadStarted:r.progress.uploadStarted??0,bytesUploaded:n,bytesTotal:o}))}(this,i,this.uppy.getFile(e.id));break;case"success":{const t=i.response?.responseText;this.uppy.emit("upload-success",this.uppy.getFile(e.id),{uploadURL:i.url,status:i.response?.status??200,body:t?JSON.parse(t):void 0}),c?.abort?.(),o();break}case"error":{const{message:e}=i.error;throw Object.assign(new Error(e),{cause:i.error})}default:this.uppy.log(`Companion socket unknown action ${r}`,"warning")}}catch(n){r(n)}});const a=()=>{this.uppy.log(`Closing socket ${e.id}`),clearTimeout(u),d&&d.close(),d=void 0};c.signal.addEventListener("abort",()=>{a()})}),{retries:10,signal:c.signal,onFailedAttempt:()=>{c.signal.aborted||this.uppy.log(`Retrying websocket ${e.id}`)}})})().abortOn(c.signal)}catch(n){if(c.signal.aborted)return;r(n)}})()})}finally{i?.()}}},Vr=class{uppy;opts;id;defaultLocale;i18n;i18nArray;type;VERSION;constructor(e,t){this.uppy=e,this.opts=t??{}}getPluginState(){const{plugins:e}=this.uppy.getState();return e?.[this.id]||{}}setPluginState(e){const{plugins:t}=this.uppy.getState();this.uppy.setState({plugins:{...t,[this.id]:{...t[this.id],...e}}})}setOptions(e){this.opts={...this.opts,...e},this.setPluginState(void 0),this.i18nInit()}i18nInit(){const e=new Rr([this.defaultLocale,this.uppy.locale,this.opts.locale]);this.i18n=e.translate.bind(e),this.i18nArray=e.translateArray.bind(e),this.setPluginState(void 0)}addTarget(e){throw new Error("Extend the addTarget method to add your plugin to another plugin's target")}install(){}uninstall(){}update(e){}afterUpdate(){}},Wr=class{#w;#x=[];constructor(e){this.#w=e}on(e,t){return this.#x.push([e,t]),this.#w.on(e,t)}remove(){for(const[e,t]of this.#x.splice(0))this.#w.off(e,t)}onFilePause(e,t){this.on("upload-pause",(r,i)=>{e===r?.id&&t(i)})}onFileRemove(e,t){this.on("file-removed",r=>{e===r.id&&t(r.id)})}onPause(e,t){this.on("upload-pause",(r,i)=>{e===r?.id&&t(i)})}onRetry(e,t){this.on("upload-retry",r=>{e===r?.id&&t()})}onRetryAll(e,t){this.on("retry-all",()=>{this.#w.getFile(e)&&t()})}onPauseAll(e,t){this.on("pause-all",()=>{this.#w.getFile(e)&&t()})}onCancelAll(e,t){this.on("cancel-all",(...r)=>{this.#w.getFile(e)&&t(...r)})}onResumeAll(e,t){this.on("resume-all",()=>{this.#w.getFile(e)&&t()})}},Gr=class{static VERSION="5.0.0";state={};#S=/* @__PURE__ */new Set;getState(){return this.state}setState(e){const t={...this.state},r={...this.state,...e};this.state=r,this.#T(t,r,e)}subscribe(e){return this.#S.add(e),()=>{this.#S.delete(e)}}#T(...e){this.#S.forEach(t=>{t(...e)})}},Xr=/* @__PURE__ */t((e,t)=>{t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}}),Yr=/* @__PURE__ */t((e,t)=>{var r="object"==typeof global&&global&&global.Object===Object&&global;t.exports=r}),Qr=/* @__PURE__ */t((e,t)=>{var r=Yr(),i="object"==typeof self&&self&&self.Object===Object&&self,n=r||i||Function("return this")();t.exports=n}),Kr=/* @__PURE__ */t((e,t)=>{var r=Qr();t.exports=function(){return r.Date.now()}}),Jr=/* @__PURE__ */t((e,t)=>{var r=/\s/;t.exports=function(e){for(var t=e.length;t--&&r.test(e.charAt(t)););return t}}),Zr=/* @__PURE__ */t((e,t)=>{var r=Jr(),i=/^\s+/;t.exports=function(e){return e?e.slice(0,r(e)+1).replace(i,""):e}}),ei=/* @__PURE__ */t((e,t)=>{var r=Qr().Symbol;t.exports=r}),ti=/* @__PURE__ */t((e,t)=>{var r=ei(),i=Object.prototype,n=i.hasOwnProperty,o=i.toString,a=r?r.toStringTag:void 0;t.exports=function(e){var t=n.call(e,a),r=e[a];try{e[a]=void 0;var i=!0}catch(l){}var s=o.call(e);return i&&(t?e[a]=r:delete e[a]),s}}),ri=/* @__PURE__ */t((e,t)=>{var r=Object.prototype.toString;t.exports=function(e){return r.call(e)}}),ii=/* @__PURE__ */t((e,t)=>{var r=ei(),i=ti(),n=ri(),o=r?r.toStringTag:void 0;t.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":o&&o in Object(e)?i(e):n(e)}}),ni=/* @__PURE__ */t((e,t)=>{t.exports=function(e){return null!=e&&"object"==typeof e}}),oi=/* @__PURE__ */t((e,t)=>{var r=ii(),i=ni();t.exports=function(e){return"symbol"==typeof e||i(e)&&"[object Symbol]"==r(e)}}),ai=/* @__PURE__ */t((e,t)=>{var r=Zr(),i=Xr(),n=oi(),o=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,s=/^0o[0-7]+$/i,l=parseInt;t.exports=function(e){if("number"==typeof e)return e;if(n(e))return NaN;if(i(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=i(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=r(e);var d=a.test(e);return d||s.test(e)?l(e.slice(2),d?2:8):o.test(e)?NaN:+e}}),si=/* @__PURE__ */t((e,t)=>{var r=Xr(),i=Kr(),n=ai(),o=Math.max,a=Math.min;t.exports=function(e,t,s){var l,d,c,u,h,p,m=0,g=!1,f=!1,v=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function b(t){var r=l,i=d;return l=d=void 0,m=t,u=e.apply(i,r)}function y(e){var r=e-p;return void 0===p||r>=t||r<0||f&&e-m>=c}function w(){var e=i();if(y(e))return x(e);h=setTimeout(w,function(e){var r=t-(e-p);return f?a(r,c-(e-m)):r}(e))}function x(e){return h=void 0,v&&l?b(e):(l=d=void 0,u)}function S(){var e=i(),r=y(e);if(l=arguments,d=this,p=e,r){if(void 0===h)return function(e){return m=e,h=setTimeout(w,t),g?b(e):u}(p);if(f)return clearTimeout(h),h=setTimeout(w,t),b(p)}return void 0===h&&(h=setTimeout(w,t)),u}return t=n(t)||0,r(s)&&(g=!!s.leading,c=(f="maxWait"in s)?o(n(s.maxWait)||0,t):c,v="trailing"in s?!!s.trailing:v),S.cancel=function(){void 0!==h&&clearTimeout(h),m=0,l=p=d=h=void 0},S.flush=function(){return void 0===h?u:x(i())},S}}),li=/* @__PURE__ */t((e,t)=>{var r=si(),i=Xr();t.exports=function(e,t,n){var o=!0,a=!0;if("function"!=typeof e)throw new TypeError("Expected a function");return i(n)&&(o="leading"in n?!!n.leading:o,a="trailing"in n?!!n.trailing:a),r(e,t,{leading:o,maxWait:t,trailing:a})}}),di=/* @__PURE__ */t((e,t)=>{t.exports=function(){var e={},t=e._fns={};return e.emit=function(e,r,i,n,o,a,s){var l=function(e){for(var r=t[e]?t[e]:[],i=e.indexOf(":"),n=-1===i?[e]:[e.substring(0,i),e.substring(i+1)],o=Object.keys(t),a=0,s=o.length;a<s;a++){var l=o[a];if("*"===l&&(r=r.concat(t[l])),2===n.length&&n[0]===l){r=r.concat(t[l]);break}}return r}(e);l.length&&function(e,t,r){for(var i=0,n=t.length;i<n&&t[i];i++)t[i].event=e,t[i].apply(t[i],r)}(e,l,[r,i,n,o,a,s])},e.on=function(e,r){t[e]||(t[e]=[]),t[e].push(r)},e.once=function(t,r){this.on(t,function i(){r.apply(this,arguments),e.off(t,i)})},e.off=function(e,t){var r=[];if(e&&t)for(var i=this._fns[e],n=0,o=i?i.length:0;n<o;n++)i[n]!==t&&r.push(i[n]);r.length?this._fns[e]=r:delete this._fns[e]},e}}),ci={strings:{addBulkFilesFailed:{0:"Failed to add %{smart_count} file due to an internal error",1:"Failed to add %{smart_count} files due to internal errors"},youCanOnlyUploadX:{0:"You can only upload %{smart_count} file",1:"You can only upload %{smart_count} files"},youHaveToAtLeastSelectX:{0:"You have to select at least %{smart_count} file",1:"You have to select at least %{smart_count} files"},aggregateExceedsSize:"You selected %{size} of files, but maximum allowed size is %{sizeAllowed}",exceedsSize:"%{file} exceeds maximum allowed size of %{size}",missingRequiredMetaField:"Missing required meta fields",missingRequiredMetaFieldOnFile:"Missing required meta fields in %{fileName}",inferiorSize:"This file is smaller than the allowed size of %{size}",youCanOnlyUploadFileTypes:"You can only upload: %{types}",noMoreFilesAllowed:"Cannot add more files",noDuplicates:"Cannot add the duplicate file '%{fileName}', it already exists",companionError:"Connection with Companion failed",authAborted:"Authentication aborted",companionUnauthorizeHint:"To unauthorize to your %{provider} account, please go to %{url}",failedToUpload:"Failed to upload %{file}",noInternetConnection:"No Internet connection",connectedToInternet:"Connected to the Internet",noFilesFound:"You have no files or folders here",noSearchResults:"Unfortunately, there are no results for this search",selectX:{0:"Select %{smart_count}",1:"Select %{smart_count}"},allFilesFromFolderNamed:"All files from folder %{name}",openFolderNamed:"Open folder %{name}",cancel:"Cancel",logOut:"Log out",logIn:"Log in",pickFiles:"Pick files",pickPhotos:"Pick photos",filter:"Filter",resetFilter:"Reset filter",loading:"Loading...",loadedXFiles:"Loaded %{numFiles} files",authenticateWithTitle:"Please authenticate with %{pluginName} to select files",authenticateWith:"Connect to %{pluginName}",signInWithGoogle:"Sign in with Google",searchImages:"Search for images",enterTextToSearch:"Enter text to search for images",search:"Search",resetSearch:"Reset search",emptyFolderAdded:"No files were added from empty folder",addedNumFiles:"Added %{numFiles} file(s)",folderAlreadyAdded:'The folder "%{folder}" was already added',folderAdded:{0:"Added %{smart_count} file from %{folder}",1:"Added %{smart_count} files from %{folder}"},additionalRestrictionsFailed:"%{count} additional restrictions were not fulfilled",unnamed:"Unnamed",pleaseWait:"Please wait"}},ui={debug:()=>{},warn:()=>{},error:(...e)=>console.error(`[Uppy] [${Fr()}]`,...e)},hi={debug:(...e)=>console.debug(`[Uppy] [${Fr()}]`,...e),warn:(...e)=>console.warn(`[Uppy] [${Fr()}]`,...e),error:(...e)=>console.error(`[Uppy] [${Fr()}]`,...e)},pi=/* @__PURE__ */t((e,t)=>{t.exports=function(e){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("Expected a number, got "+typeof e);const t=e<0;let r=Math.abs(e);if(t&&(r=-r),0===r)return"0 B";const i=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],n=Math.min(Math.floor(Math.log(r)/Math.log(1024)),i.length-1),o=Number(r/1024**n),a=i[n];return`${o>=10||o%1==0?Math.round(o):o.toFixed(1)} ${a}`}}),mi=/* @__PURE__ */t((e,t)=>{function r(e,t){this.text=e=e||"",this.hasWild=~e.indexOf("*"),this.separator=t,this.parts=e.split(t)}r.prototype.match=function(e){var t,r,i=!0,n=this.parts,o=n.length;if("string"==typeof e||e instanceof String)if(this.hasWild||this.text==e){for(r=(e||"").split(this.separator),t=0;i&&t<o;t++)"*"!==n[t]&&(i=t<r.length&&n[t]===r[t]);i=i&&r}else i=!1;else if("function"==typeof e.splice)for(i=[],t=e.length;t--;)this.match(e[t])&&(i[i.length]=e[t]);else if("object"==typeof e)for(var a in i={},e)this.match(a)&&(i[a]=e[a]);return i},t.exports=function(e,t,i){var n=new r(e,i||/[\/\.]/);return void 0!==t?n.match(t):n}}),gi=/* @__PURE__ */t((e,t)=>{var r=mi(),i=/[\/\+\.]/;t.exports=function(e,t){function n(t){var n=r(t,e,i);return n&&n.length>=2}return t?n(t.split(";")[0]):n}}),fi=/* @__PURE__ */e(pi(),1),vi=/* @__PURE__ */e(gi(),1),bi={maxFileSize:null,minFileSize:null,maxTotalFileSize:null,maxNumberOfFiles:null,minNumberOfFiles:null,allowedFileTypes:null,requiredMetaFields:[]},yi=class extends Error{isUserFacing;file;constructor(e,t){super(e),this.isUserFacing=t?.isUserFacing??!0,t?.file&&(this.file=t.file)}isRestriction=!0},wi=class{getI18n;getOpts;constructor(e,t){this.getI18n=t,this.getOpts=()=>{const t=e();if(null!=t.restrictions?.allowedFileTypes&&!Array.isArray(t.restrictions.allowedFileTypes))throw new TypeError("`restrictions.allowedFileTypes` must be an array");return t}}validateAggregateRestrictions(e,t){const{maxTotalFileSize:r,maxNumberOfFiles:i}=this.getOpts().restrictions;if(i&&e.filter(e=>!e.isGhost).length+t.length>i)throw new yi(`${this.getI18n()("youCanOnlyUploadX",{smart_count:i})}`);if(r){const i=[...e,...t].reduce((e,t)=>e+(t.size??0),0);if(i>r)throw new yi(this.getI18n()("aggregateExceedsSize",{sizeAllowed:(0,fi.default)(r),size:(0,fi.default)(i)}))}}validateSingleFile(e){const{maxFileSize:t,minFileSize:r,allowedFileTypes:i}=this.getOpts().restrictions;if(i&&!i.some(t=>t.includes("/")?!!e.type&&(0,vi.default)(e.type.replace(/;.*?$/,""),t):!("."!==t[0]||!e.extension)&&e.extension.toLowerCase()===t.slice(1).toLowerCase())){const t=i.join(", ");throw new yi(this.getI18n()("youCanOnlyUploadFileTypes",{types:t}),{file:e})}if(t&&null!=e.size&&e.size>t)throw new yi(this.getI18n()("exceedsSize",{size:(0,fi.default)(t),file:e.name??this.getI18n()("unnamed")}),{file:e});if(r&&null!=e.size&&e.size<r)throw new yi(this.getI18n()("inferiorSize",{size:(0,fi.default)(r)}),{file:e})}validate(e,t){t.forEach(e=>{this.validateSingleFile(e)}),this.validateAggregateRestrictions(e,t)}validateMinNumberOfFiles(e){const{minNumberOfFiles:t}=this.getOpts().restrictions;if(t&&Object.keys(e).length<t)throw new yi(this.getI18n()("youHaveToAtLeastSelectX",{smart_count:t}))}getMissingRequiredMetaFields(e){const t=new yi(this.getI18n()("missingRequiredMetaFieldOnFile",{fileName:e.name??this.getI18n()("unnamed")})),{requiredMetaFields:r}=this.getOpts().restrictions,i=[];for(const n of r)Object.hasOwn(e.meta,n)&&""!==e.meta[n]||i.push(n);return{missingFields:i,error:t}}};function xi(e){if(null==e&&"undefined"!=typeof navigator&&(e=navigator.userAgent),!e)return!0;const t=/Edge\/(\d+\.\d+)/.exec(e);if(!t)return!0;const r=t[1].split(".",2),i=parseInt(r[0],10),n=parseInt(r[1],10);return i<15||15===i&&n<15063||i>18||18===i&&n>=18218}var Si=/* @__PURE__ */e(li(),1),Ti=/* @__PURE__ */e(di(),1),Ci={totalProgress:0,allowNewUpload:!0,error:null,recoveredState:null},Fi=class e{static VERSION="5.2.0";#C=Object.create(null);#F;#k;#_=(0,Ti.default)();#E=/* @__PURE__ */new Set;#M=/* @__PURE__ */new Set;#U=/* @__PURE__ */new Set;defaultLocale;locale;opts;store;i18n;i18nArray;scheduledAutoProceed=null;wasOffline=!1;constructor(t){this.defaultLocale=ci;const r={id:"uppy",autoProceed:!1,allowMultipleUploadBatches:!0,debug:!1,restrictions:bi,meta:{},onBeforeFileAdded:(e,t)=>!Object.hasOwn(t,e.id),onBeforeUpload:e=>e,store:new Gr,logger:ui,infoTimeout:5e3},i={...r,...t};this.opts={...i,restrictions:{...r.restrictions,...t?.restrictions}},t?.logger&&t.debug?this.log("You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.","warning"):t?.debug&&(this.opts.logger=hi),this.log(`Using Core v${e.VERSION}`),this.i18nInit(),this.store=this.opts.store,this.setState({...Ci,plugins:{},files:{},currentUploads:{},capabilities:{uploadProgress:xi(),individualCancellation:!0,resumableUploads:!1},meta:{...this.opts.meta},info:[]}),this.#F=new wi(()=>this.opts,()=>this.i18n),this.#k=this.store.subscribe((e,t,r)=>{this.emit("state-update",e,t,r),this.updateAll(t)}),this.opts.debug&&"undefined"!=typeof window&&(window[this.opts.id]=this),this.#R()}emit(e,...t){this.#_.emit(e,...t)}on(e,t){return this.#_.on(e,t),this}once(e,t){return this.#_.once(e,t),this}off(e,t){return this.#_.off(e,t),this}updateAll(e){this.iteratePlugins(t=>{t.update(e)})}setState(e){this.store.setState(e)}getState(){return this.store.getState()}patchFilesState(e){const t=this.getState().files;this.setState({files:{...t,...Object.fromEntries(Object.entries(e).map(([e,r])=>[e,{...t[e],...r}]))}})}setFileState(e,t){if(!this.getState().files[e])throw new Error(`Can’t set state for ${e} (the file could have been removed)`);this.patchFilesState({[e]:t})}i18nInit(){const e=new Rr([this.defaultLocale,this.opts.locale],{onMissingKey:e=>this.log(`Missing i18n string: ${e}`,"error")});this.i18n=e.translate.bind(e),this.i18nArray=e.translateArray.bind(e),this.locale=e.locale}setOptions(e){this.opts={...this.opts,...e,restrictions:{...this.opts.restrictions,...e?.restrictions}},e.meta&&this.setMeta(e.meta),this.i18nInit(),e.locale&&this.iteratePlugins(t=>{t.setOptions(e)}),this.setState(void 0)}resetProgress(){const e={percentage:0,bytesUploaded:!1,uploadComplete:!1,uploadStarted:null},t={...this.getState().files},r=Object.create(null);Object.keys(t).forEach(i=>{r[i]={...t[i],progress:{...t[i].progress,...e},tus:void 0,transloadit:void 0}}),this.setState({files:r,...Ci})}clear(){const{capabilities:e,currentUploads:t}=this.getState();if(Object.keys(t).length>0&&!e.individualCancellation)throw new Error("The installed uploader plugin does not allow removing files during an upload.");this.setState({...Ci,files:{}})}addPreProcessor(e){this.#E.add(e)}removePreProcessor(e){return this.#E.delete(e)}addPostProcessor(e){this.#U.add(e)}removePostProcessor(e){return this.#U.delete(e)}addUploader(e){this.#M.add(e)}removeUploader(e){return this.#M.delete(e)}setMeta(e){const t={...this.getState().meta,...e},r={...this.getState().files};Object.keys(r).forEach(t=>{r[t]={...r[t],meta:{...r[t].meta,...e}}}),this.log("Adding metadata:"),this.log(e),this.setState({meta:t,files:r})}setFileMeta(e,t){const r={...this.getState().files};if(!r[e])return void this.log(`Was trying to set metadata for a file that has been removed: ${e}`);const i={...r[e].meta,...t};r[e]={...r[e],meta:i},this.setState({files:r})}getFile(e){return this.getState().files[e]}getFiles(){const{files:e}=this.getState();return Object.values(e)}getFilesByIds(e){return e.map(e=>this.getFile(e))}getObjectOfFilesPerState(){const{files:e,totalProgress:t,error:r}=this.getState(),i=Object.values(e),n=[],o=[],a=[],s=[],l=[],d=[],c=[],u=[],h=[];for(const p of i){const{progress:e}=p;!e.uploadComplete&&e.uploadStarted&&(n.push(p),p.isPaused||u.push(p)),e.uploadStarted||o.push(p),(e.uploadStarted||e.preprocess||e.postprocess)&&a.push(p),e.uploadStarted&&s.push(p),p.isPaused&&l.push(p),e.uploadComplete&&d.push(p),p.error&&c.push(p),(e.preprocess||e.postprocess)&&h.push(p)}return{newFiles:o,startedFiles:a,uploadStartedFiles:s,pausedFiles:l,completeFiles:d,erroredFiles:c,inProgressFiles:n,inProgressNotPausedFiles:u,processingFiles:h,isUploadStarted:s.length>0,isAllComplete:100===t&&d.length===i.length&&0===h.length,isAllErrored:!!r&&c.length===i.length,isAllPaused:0!==n.length&&l.length===n.length,isUploadInProgress:n.length>0,isSomeGhost:i.some(e=>e.isGhost)}}#I(e){for(const n of e)n.isRestriction?this.emit("restriction-failed",n.file,n):this.emit("error",n,n.file),this.log(n,"warning");const t=e.filter(e=>e.isUserFacing),r=t.slice(0,4),i=t.slice(4);r.forEach(({message:e,details:t=""})=>{this.info({message:e,details:t},"error",this.opts.infoTimeout)}),i.length>0&&this.info({message:this.i18n("additionalRestrictionsFailed",{count:i.length})})}validateRestrictions(e,t=this.getFiles()){try{this.#F.validate(t,[e])}catch(r){return r}return null}validateSingleFile(e){try{this.#F.validateSingleFile(e)}catch(t){return t.message}return null}validateAggregateRestrictions(e){const t=this.getFiles();try{this.#F.validateAggregateRestrictions(t,e)}catch(r){return r.message}return null}#N(e){const{missingFields:t,error:r}=this.#F.getMissingRequiredMetaFields(e);return t.length>0?(this.setFileState(e.id,{missingRequiredMetaFields:t,error:r.message}),this.log(r.message),this.emit("restriction-failed",e,r),!1):(0===t.length&&e.missingRequiredMetaFields&&this.setFileState(e.id,{missingRequiredMetaFields:[]}),!0)}#O(e){let t=!0;for(const r of Object.values(e))this.#N(r)||(t=!1);return t}#P(e){const{allowNewUpload:t}=this.getState();if(!1===t){const t=new yi(this.i18n("noMoreFilesAllowed"),{file:e});throw this.#I([t]),t}}checkIfFileAlreadyExists(e){const{files:t}=this.getState();return!(!t[e]||t[e].isGhost)}#q(e){const t=e instanceof File?{name:e.name,type:e.type,size:e.size,data:e,meta:{},isRemote:!1,source:void 0,preview:void 0}:e,r=xr(t),i=function(e,t){return t.name?t.name:"image"===e.split("/")[0]?`${e.split("/")[0]}.${e.split("/")[1]}`:"noname"}(r,t),n=yr(i).extension,o=function(e,t){if(function(e){return!(!e.isRemote||!e.remote)&&/* @__PURE__ */new Set(["box","dropbox","drive","facebook","unsplash"]).has(e.remote.provider)}(e))return e.id;const r=xr(e);return function(e,t){let r=t||"uppy";return"string"==typeof e.name&&(r+=`-${Sr(e.name.toLowerCase())}`),void 0!==e.type&&(r+=`-${e.type}`),e.meta&&"string"==typeof e.meta.relativePath&&(r+=`-${Sr(e.meta.relativePath.toLowerCase())}`),void 0!==e.data?.size&&(r+=`-${e.data.size}`),void 0!==e.data.lastModified&&(r+=`-${e.data.lastModified}`),r}({...e,type:r},t)}(t,this.getID()),a={...t.meta,name:i,type:r},s=Number.isFinite(t.data.size)?t.data.size:null;return{source:t.source||"",id:o,name:i,extension:n||"",meta:{...this.getState().meta,...a},type:r,progress:{percentage:0,bytesUploaded:!1,bytesTotal:s,uploadComplete:!1,uploadStarted:null},size:s,isGhost:!1,...t.isRemote?{isRemote:!0,remote:t.remote,data:t.data}:{isRemote:!1,data:t.data},preview:t.preview}}#A(){this.opts.autoProceed&&!this.scheduledAutoProceed&&(this.scheduledAutoProceed=setTimeout(()=>{this.scheduledAutoProceed=null,this.upload().catch(e=>{e.isRestriction||this.log(e.stack||e.message||e)})},4))}#D(e){let{files:t}=this.getState(),r={...t};const i=[],n=[];for(const a of e)try{let e=this.#q(a);this.#P(e);const n=t[e.id],o=n?.isGhost;if(o&&!e.isRemote){if(null==e.data)throw new Error("File data is missing");e={...n,isGhost:!1,data:e.data},this.log(`Replaced the blob in the restored ghost file: ${e.name}, ${e.id}`)}const s=this.opts.onBeforeFileAdded(e,r);if(t=this.getState().files,r={...t,...r},!s&&this.checkIfFileAlreadyExists(e.id))throw new yi(this.i18n("noDuplicates",{fileName:e.name??this.i18n("unnamed")}),{file:e});if(!1===s&&!o)throw new yi("Cannot add the file because onBeforeFileAdded returned false.",{isUserFacing:!1,file:e});"object"==typeof s&&null!==s&&(e=s),this.#F.validateSingleFile(e),r[e.id]=e,i.push(e)}catch(o){n.push(o)}try{this.#F.validateAggregateRestrictions(Object.values(t),i)}catch(o){return n.push(o),{nextFilesState:t,validFilesToAdd:[],errors:n}}return{nextFilesState:r,validFilesToAdd:i,errors:n}}addFile(e){const{nextFilesState:t,validFilesToAdd:r,errors:i}=this.#D([e]),n=i.filter(e=>e.isRestriction);if(this.#I(n),i.length>0)throw i[0];this.setState({files:t});const[o]=r;return this.emit("file-added",o),this.emit("files-added",r),this.log(`Added file: ${o.name}, ${o.id}, mime type: ${o.type}`),this.#A(),o.id}addFiles(e){const{nextFilesState:t,validFilesToAdd:r,errors:i}=this.#D(e),n=i.filter(e=>e.isRestriction);this.#I(n);const o=i.filter(e=>!e.isRestriction);if(o.length>0){let e="Multiple errors occurred while adding files:\n";if(o.forEach(t=>{e+=`\n * ${t.message}`}),this.info({message:this.i18n("addBulkFilesFailed",{smart_count:o.length}),details:e},"error",this.opts.infoTimeout),"function"==typeof AggregateError)throw new AggregateError(o,e);{const t=new Error(e);throw t.errors=o,t}}this.setState({files:t}),r.forEach(e=>{this.emit("file-added",e)}),this.emit("files-added",r),r.length>5?this.log(`Added batch of ${r.length} files`):Object.values(r).forEach(e=>{this.log(`Added file: ${e.name}\n id: ${e.id}\n type: ${e.type}`)}),r.length>0&&this.#A()}removeFiles(e){const{files:t,currentUploads:r}=this.getState(),i={...t},n={...r},o=Object.create(null);function a(e){return void 0===o[e]}e.forEach(e=>{t[e]&&(o[e]=t[e],delete i[e])}),Object.keys(n).forEach(e=>{const t=r[e].fileIDs.filter(a);if(0===t.length)return void delete n[e];const{capabilities:i}=this.getState();if(t.length!==r[e].fileIDs.length&&!i.individualCancellation)throw new Error("The installed uploader plugin does not allow removing files during an upload.");n[e]={...r[e],fileIDs:t}});const s={currentUploads:n,files:i};0===Object.keys(i).length&&(s.allowNewUpload=!0,s.error=null,s.recoveredState=null),this.setState(s),this.#L();const l=Object.keys(o);l.forEach(e=>{this.emit("file-removed",o[e])}),l.length>5?this.log(`Removed ${l.length} files`):this.log(`Removed files: ${l.join(", ")}`)}removeFile(e){this.removeFiles([e])}pauseResume(e){if(!this.getState().capabilities.resumableUploads||this.getFile(e).progress.uploadComplete)return;const t=this.getFile(e),r=!t.isPaused;return this.setFileState(e,{isPaused:r}),this.emit("upload-pause",t,r),r}pauseAll(){const e={...this.getState().files};Object.keys(e).filter(t=>!e[t].progress.uploadComplete&&e[t].progress.uploadStarted).forEach(t=>{e[t]={...e[t],isPaused:!0}}),this.setState({files:e}),this.emit("pause-all")}resumeAll(){const e={...this.getState().files};Object.keys(e).filter(t=>!e[t].progress.uploadComplete&&e[t].progress.uploadStarted).forEach(t=>{e[t]={...e[t],isPaused:!1,error:null}}),this.setState({files:e}),this.emit("resume-all")}#j(){const{files:e}=this.getState();return Object.keys(e).filter(t=>{const r=e[t];return r.error&&(!r.missingRequiredMetaFields||0===r.missingRequiredMetaFields.length)})}async#z(){const e=this.#j(),t={...this.getState().files};if(e.forEach(e=>{t[e]={...t[e],isPaused:!1,error:null}}),this.setState({files:t,error:null}),this.emit("retry-all",this.getFilesByIds(e)),0===e.length)return{successful:[],failed:[]};const r=this.#$(e,{forceAllowNewUpload:!0});return this.#B(r)}async retryAll(){const e=await this.#z();return this.emit("complete",e),e}cancelAll(){this.emit("cancel-all");const{files:e}=this.getState(),t=Object.keys(e);t.length&&this.removeFiles(t),this.setState(Ci)}retryUpload(e){this.setFileState(e,{error:null,isPaused:!1}),this.emit("upload-retry",this.getFile(e));const t=this.#$([e],{forceAllowNewUpload:!0});return this.#B(t)}logout(){this.iteratePlugins(e=>{e.provider?.logout?.()})}#H=(e,t)=>{const r=e?this.getFile(e.id):void 0;if(null==e||!r)return void this.log(`Not setting progress for a file that has been removed: ${e?.id}`);if(100===r.progress.percentage)return void this.log(`Not setting progress for a file that has been already uploaded: ${e.id}`);const i={bytesTotal:t.bytesTotal,percentage:null!=t.bytesTotal&&Number.isFinite(t.bytesTotal)&&t.bytesTotal>0?Math.round(t.bytesUploaded/t.bytesTotal*100):void 0};null!=r.progress.uploadStarted?this.setFileState(e.id,{progress:{...r.progress,...i,bytesUploaded:t.bytesUploaded}}):this.setFileState(e.id,{progress:{...r.progress,...i}}),this.#L()};#V(){const e=this.#W();let t=null;null!=e&&(t=Math.round(100*e),t>100?t=100:t<0&&(t=0)),this.emit("progress",t??0),this.setState({totalProgress:t??0})}#L=(0,Si.default)(()=>this.#V(),500,{leading:!0,trailing:!0});[Symbol.for("uppy test: updateTotalProgress")](){return this.#V()}#W(){const e=this.getFiles().filter(e=>e.progress.uploadStarted||e.progress.preprocess||e.progress.postprocess);if(0===e.length)return 0;if(e.every(e=>e.progress.uploadComplete))return 1;const t=e=>null!=e.progress.bytesTotal&&0!==e.progress.bytesTotal,r=e.filter(t),i=e.filter(e=>!t(e));if(r.every(e=>e.progress.uploadComplete)&&i.length>0&&!i.every(e=>e.progress.uploadComplete))return null;const n=r.reduce((e,t)=>e+(t.progress.bytesTotal??0),0),o=r.reduce((e,t)=>e+(t.progress.bytesUploaded||0),0);return 0===n?0:o/n}#R(){const e=(e,t,r)=>{let i=e.message||"Unknown error";e.details&&(i+=` ${e.details}`),this.setState({error:i}),null!=t&&t.id in this.getState().files&&this.setFileState(t.id,{error:i,response:r})};this.on("error",e),this.on("upload-error",(t,r,i)=>{if(e(r,t,i),"object"==typeof r&&r.message){this.log(r.message,"error");const e=new Error(this.i18n("failedToUpload",{file:t?.name??""}));e.isUserFacing=!0,e.details=r.message,r.details&&(e.details+=` ${r.details}`),this.#I([e])}else this.#I([r])});let t=null;this.on("upload-stalled",(e,r)=>{const{message:i}=e,n=r.map(e=>e.meta.name).join(", ");t||(this.info({message:i,details:n},"warning",this.opts.infoTimeout),t=setTimeout(()=>{t=null},this.opts.infoTimeout)),this.log(`${i} ${n}`.trim(),"warning")}),this.on("upload",()=>{this.setState({error:null})}),this.on("upload-start",e=>{const t=e.filter(e=>{const t=null!=e&&this.getFile(e.id);return t||this.log(`Not setting progress for a file that has been removed: ${e?.id}`),t}),r=Object.fromEntries(t.map(e=>[e.id,{progress:{uploadStarted:Date.now(),uploadComplete:!1,bytesUploaded:0,bytesTotal:e.size}}]));this.patchFilesState(r)}),this.on("upload-progress",this.#H),this.on("upload-success",(e,t)=>{if(null==e||!this.getFile(e.id))return void this.log(`Not setting progress for a file that has been removed: ${e?.id}`);const r=this.getFile(e.id).progress,i=this.#U.size>0;this.setFileState(e.id,{progress:{...r,postprocess:i?{mode:"indeterminate"}:void 0,uploadComplete:!0,...!i&&{complete:!0},percentage:100,bytesUploaded:r.bytesTotal},response:t,uploadURL:t.uploadURL,isPaused:!1}),null==e.size&&this.setFileState(e.id,{size:t.bytesUploaded||r.bytesTotal}),this.#L()}),this.on("preprocess-progress",(e,t)=>{null!=e&&this.getFile(e.id)?this.setFileState(e.id,{progress:{...this.getFile(e.id).progress,preprocess:t}}):this.log(`Not setting progress for a file that has been removed: ${e?.id}`)}),this.on("preprocess-complete",e=>{if(null==e||!this.getFile(e.id))return void this.log(`Not setting progress for a file that has been removed: ${e?.id}`);const t={...this.getState().files};t[e.id]={...t[e.id],progress:{...t[e.id].progress}},delete t[e.id].progress.preprocess,this.setState({files:t})}),this.on("postprocess-progress",(e,t)=>{null!=e&&this.getFile(e.id)?this.setFileState(e.id,{progress:{...this.getState().files[e.id].progress,postprocess:t}}):this.log(`Not setting progress for a file that has been removed: ${e?.id}`)}),this.on("postprocess-complete",e=>{const t=e&&this.getFile(e.id);if(null==t)return void this.log(`Not setting progress for a file that has been removed: ${e?.id}`);const{postprocess:r,...i}=t.progress;this.patchFilesState({[t.id]:{progress:{...i,complete:!0}}})}),this.on("restored",()=>{this.#L()}),this.on("dashboard:file-edit-complete",e=>{e&&this.#N(e)}),"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("online",this.#G),window.addEventListener("offline",this.#G),setTimeout(this.#G,3e3))}updateOnlineStatus(){window.navigator.onLine??1?(this.emit("is-online"),this.wasOffline&&(this.emit("back-online"),this.info(this.i18n("connectedToInternet"),"success",3e3),this.wasOffline=!1)):(this.emit("is-offline"),this.info(this.i18n("noInternetConnection"),"error",0),this.wasOffline=!0)}#G=this.updateOnlineStatus.bind(this);getID(){return this.opts.id}use(e,...t){if("function"!=typeof e)throw new TypeError(`Expected a plugin class, but got ${null===e?"null":typeof e}. Please verify that the plugin was imported and spelled correctly.`);const r=new e(this,...t),i=r.id;if(!i)throw new Error("Your plugin must have an id");if(!r.type)throw new Error("Your plugin must have a type");const n=this.getPlugin(i);if(n){const e=`Already found a plugin named '${n.id}'. Tried to use: '${i}'.\nUppy plugins must have unique \`id\` options.`;throw new Error(e)}return e.VERSION&&this.log(`Using ${i} v${e.VERSION}`),r.type in this.#C?this.#C[r.type].push(r):this.#C[r.type]=[r],r.install(),this.emit("plugin-added",r),this}getPlugin(e){for(const t of Object.values(this.#C)){const r=t.find(t=>t.id===e);if(null!=r)return r}}[Symbol.for("uppy test: getPlugins")](e){return this.#C[e]}iteratePlugins(e){Object.values(this.#C).flat(1).forEach(e)}removePlugin(e){this.log(`Removing plugin ${e.id}`),this.emit("plugin-remove",e),e.uninstall&&e.uninstall();const t=this.#C[e.type],r=t.findIndex(t=>t.id===e.id);-1!==r&&t.splice(r,1);const i={plugins:{...this.getState().plugins,[e.id]:void 0}};this.setState(i)}destroy(){this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`),this.cancelAll(),this.#k(),this.iteratePlugins(e=>{this.removePlugin(e)}),"undefined"!=typeof window&&window.removeEventListener&&(window.removeEventListener("online",this.#G),window.removeEventListener("offline",this.#G))}hideInfo(){const{info:e}=this.getState();this.setState({info:e.slice(1)}),this.emit("info-hidden")}info(e,t="info",r=3e3){const i="object"==typeof e;this.setState({info:[...this.getState().info,{type:t,message:i?e.message:e,details:i?e.details:null}]}),setTimeout(()=>this.hideInfo(),r),this.emit("info-visible")}log(e,t){const{logger:r}=this.opts;switch(t){case"error":r.error(e);break;case"warning":r.warn(e);break;default:r.debug(e)}}#X=/* @__PURE__ */new Map;registerRequestClient(e,t){this.#X.set(e,t)}getRequestClientForFile(e){if(!("remote"in e)||!e.remote)throw new Error(`Tried to get RequestClient for a non-remote file ${e.id}`);const t=this.#X.get(e.remote.requestClientId);if(null==t)throw new Error(`requestClientId "${e.remote.requestClientId}" not registered for file "${e.id}"`);return t}async restore(e){this.log(`Core: Running restored upload "${e}"`);const t=await this.#B(e);return this.emit("complete",t),t}#$(e,t={}){const{forceAllowNewUpload:r=!1}=t,{allowNewUpload:i,currentUploads:n}=this.getState();if(!i&&!r)throw new Error("Cannot create a new upload: already uploading.");const o=((e=21)=>{let t="",r=0|e;for(;r-- >0;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t})();return this.emit("upload",o,this.getFilesByIds(e)),this.setState({allowNewUpload:!1!==this.opts.allowMultipleUploadBatches&&!1!==this.opts.allowMultipleUploads,currentUploads:{...n,[o]:{fileIDs:e,step:0,result:{}}}}),o}[Symbol.for("uppy test: createUpload")](...e){return this.#$(...e)}#Y(e){const{currentUploads:t}=this.getState();return t[e]}addResultData(e,t){if(!this.#Y(e))return void this.log(`Not setting result for an upload that has been removed: ${e}`);const{currentUploads:r}=this.getState(),i={...r[e],result:{...r[e].result,...t}};this.setState({currentUploads:{...r,[e]:i}})}#Q(e){const{[e]:t,...r}=this.getState().currentUploads;this.setState({currentUploads:r})}async#B(e){const t=()=>{const{currentUploads:t}=this.getState();return t[e]};let r=t();if(!r)throw new Error("Nonexistent upload");const i=[...this.#E,...this.#M,...this.#U];try{for(let n=r.step||0;n<i.length;n++){const o=i[n];this.setState({currentUploads:{...this.getState().currentUploads,[e]:{...r,step:n}}});const{fileIDs:a}=r;if(await o(a,e),r=t(),!r)break}}catch(o){throw this.#Q(e),o}if(r){r.fileIDs.forEach(e=>{const t=this.getFile(e);t?.progress.postprocess&&this.emit("postprocess-complete",t)});const i=r.fileIDs.map(e=>this.getFile(e)),n=i.filter(e=>!e.error),o=i.filter(e=>e.error);this.addResultData(e,{successful:n,failed:o,uploadID:e}),r=t()}let n;return r&&(n=r.result,this.#Q(e)),null==n&&(this.log(`Not setting result for an upload that has been removed: ${e}`),n={successful:[],failed:[],uploadID:e}),n}async upload(){this.#C.uploader?.length||this.log("No uploader type plugins are used","warning");let{files:e}=this.getState();if(this.#j().length>0){const t=await this.#z();if(!(this.getFiles().filter(e=>null==e.progress.uploadStarted).length>0))return this.emit("complete",t),t;({files:e}=this.getState())}const t=this.opts.onBeforeUpload(e);if(!1===t)throw new Error("Not starting the upload because onBeforeUpload returned false");t&&"object"==typeof t&&(e=t,this.setState({files:e}));try{if(this.#F.validateMinNumberOfFiles(e),!this.#O(e))throw new yi(this.i18n("missingRequiredMetaField"));const{currentUploads:t}=this.getState(),r=Object.values(t).flatMap(e=>e.fileIDs),i=Object.keys(e).filter(e=>{const t=this.getFile(e);return t&&!t.progress.uploadStarted&&!r.includes(e)}),n=this.#$(i),o=await this.#B(n);return this.emit("complete",o),o}catch(r){throw this.#I([r]),r}}};function ki({method:e="PUT",CanonicalUri:t="/",CanonicalQueryString:r="",SignedHeaders:i,HashedPayload:n}){const o=Object.keys(i).map(e=>e.toLowerCase()).sort();return[e,t,r,...o.map(e=>`${e}:${i[e]}`),"",o.join(";"),n].join("\n")}var _i=new TextEncoder,Ei={name:"HMAC",hash:"SHA-256"};async function Mi(e){const{subtle:t}=globalThis.crypto;return t.digest(Ei.hash,_i.encode(e))}function Ui(e){const t=new Uint8Array(e);let r="";for(let i=0;i<t.length;i++)r+=t[i].toString(16).padStart(2,"0");return r}async function Ri(e,t){const{subtle:r}=globalThis.crypto;return r.sign(Ei,await async function(e){const{subtle:t}=globalThis.crypto;return t.importKey("raw","string"==typeof e?_i.encode(e):e,Ei,!1,["sign"])}(e),_i.encode(t))}async function Ii({accountKey:e,accountSecret:t,sessionToken:r,bucketName:i,Key:n,Region:o,expires:a,uploadId:s,partNumber:l}){const d="s3",c=`${d}.${o}.amazonaws.com`,u=`/${i}/${encodeURI(n).replace(/[;?:@&=+$,#!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}`,h="UNSIGNED-PAYLOAD",p=/* @__PURE__ */(new Date).toISOString().replace(/[-:]|\.\d+/g,""),m=p.slice(0,8),g=`${m}/${o}/${d}/aws4_request`,f=new URL(`https://${c}${u}`);f.searchParams.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),f.searchParams.set("X-Amz-Content-Sha256",h),f.searchParams.set("X-Amz-Credential",`${e}/${g}`),f.searchParams.set("X-Amz-Date",p),f.searchParams.set("X-Amz-Expires",a),f.searchParams.set("X-Amz-Security-Token",r),f.searchParams.set("X-Amz-SignedHeaders","host"),l&&f.searchParams.set("partNumber",l),s&&f.searchParams.set("uploadId",s),f.searchParams.set("x-id",l&&s?"UploadPart":"PutObject");const v=["AWS4-HMAC-SHA256",p,g,Ui(await Mi(ki({CanonicalUri:u,CanonicalQueryString:f.search.slice(1),SignedHeaders:{host:c},HashedPayload:h})))].join("\n"),b=Ui(await Ri(await Ri(await Ri(await Ri(await Ri(`AWS4${t}`,m),o),d),"aws4_request"),v));return f.searchParams.set("X-Amz-Signature",b),f}var Ni={getChunkSize:e=>Math.ceil(e.size/1e4),onProgress(){},onPartComplete(){},onSuccess(){},onError(e){throw e}},Oi=Symbol("pausing upload, not an actual error"),Pi=class{options;#K=new mr;#J=[];#Z=[];#ee;#te;#re=!1;#ie;#ne;#oe;#ae;#se=e=>e?.cause===Oi?null:this.#ie(e);#le=1e4;#de=5242880;constructor(e,t){this.options={...Ni,...t},this.options.getChunkSize??=Ni.getChunkSize,this.#ee=e,this.#te=t.file,this.#ne=this.options.onSuccess,this.#ie=this.options.onError,this.#oe=this.options.shouldUseMultipart,this.#ae=t.uploadId&&t.key,this.#ce()}#ce(){const e=this.#ee.size,t="function"==typeof this.#oe?this.#oe(this.#te):Boolean(this.#oe);if(t&&e>this.#de){let r=Math.max(this.options.getChunkSize(this.#ee),this.#de),i=Math.floor(e/r);i>this.#le&&(i=this.#le,r=e/this.#le),this.#J=Array(i);for(let n=0,o=0;n<e;n+=r,o++){const i=Math.min(e,n+r),a=()=>{const e=n;return this.#ee.slice(e,i)};if(this.#J[o]={getData:a,onProgress:this.#ue(o),onComplete:this.#he(o),shouldUseMultipart:t},this.#ae){const t=n+r>e?e-n:r;this.#J[o].setAsUploaded=()=>{this.#J[o]=null,this.#Z[o].uploaded=t}}}}else this.#J=[{getData:()=>this.#ee,onProgress:this.#ue(0),onComplete:this.#he(0),shouldUseMultipart:t}];this.#Z=this.#J.map(()=>({uploaded:0}))}#$(){this.options.companionComm.uploadFile(this.#te,this.#J,this.#K.signal).then(this.#ne,this.#se),this.#re=!0}#pe(){this.options.companionComm.resumeUploadFile(this.#te,this.#J,this.#K.signal).then(this.#ne,this.#se)}#ue=e=>t=>{if(!t.lengthComputable)return;this.#Z[e].uploaded=function(e){if("string"==typeof e)return parseInt(e,10);if("number"==typeof e)return e;throw new TypeError("Expected a number")}(t.loaded);const r=this.#Z.reduce((e,t)=>e+t.uploaded,0);this.options.onProgress(r,this.#ee.size)};#he=e=>t=>{this.#J[e]=null,this.#Z[e].etag=t,this.#Z[e].done=!0;const r={PartNumber:e+1,ETag:t};this.options.onPartComplete(r)};#me(){this.#K.abort(),this.options.companionComm.abortFileUpload(this.#te).catch(e=>this.options.log(e))}start(){this.#re?(this.#K.signal.aborted||this.#K.abort(Oi),this.#K=new mr,this.#pe()):this.#ae?(this.options.companionComm.restoreUploadFile(this.#te,{uploadId:this.options.uploadId,key:this.options.key}),this.#pe()):this.#$()}pause(){this.#K.abort(Oi),this.#K=new mr}abort(e){e?.really?this.#me():this.pause()}[Symbol.for("uppy test: getChunkState")](){return this.#Z}};function qi(e){if(e?.aborted)throw fr("The operation was aborted",{cause:e.reason})}function Ai(e){const t=new URL(e);return t.search="",t.hash="",t.href}var Di=class{#ge;#fe=/* @__PURE__ */new WeakMap;#ve;#be;#ye;#we;#xe;#Se;#Te;#Ce;#Fe;#ke;#_e;constructor(e,t,r,i){this.#Se=e,this.#Fe=r,this.#_e=i,this.setOptions(t)}setOptions(e){const t=this.#Se;"abortMultipartUpload"in e&&(this.#ge=t.wrapPromiseFunction(e.abortMultipartUpload,{priority:1})),"createMultipartUpload"in e&&(this.#ve=t.wrapPromiseFunction(e.createMultipartUpload,{priority:-1})),"signPart"in e&&(this.#be=t.wrapPromiseFunction(e.signPart)),"listParts"in e&&(this.#we=t.wrapPromiseFunction(e.listParts)),"completeMultipartUpload"in e&&(this.#Ce=t.wrapPromiseFunction(e.completeMultipartUpload,{priority:1})),"retryDelays"in e&&(this.#Te=e.retryDelays??[]),"uploadPartBytes"in e&&(this.#ke=t.wrapPromiseFunction(e.uploadPartBytes,{priority:1/0})),"getUploadParameters"in e&&(this.#ye=t.wrapPromiseFunction(e.getUploadParameters))}async#Ee(e,t){const r=this.#Se,i=e?.source?.status;if(null==i)return!1;if(403===i&&"Request has expired"===e.message){if(!r.isPaused){if(1===r.limit||null==this.#xe){const e=t.next();if(null==e||e.done)return!1;this.#xe=e.value}r.rateLimit(0),await new Promise(e=>setTimeout(e,this.#xe))}}else if(429===i){if(!r.isPaused){const e=t.next();if(null==e||e.done)return!1;r.rateLimit(e.value)}}else{if(i>400&&i<500&&409!==i)return!1;if("undefined"!=typeof navigator&&!1===navigator.onLine)r.isPaused||(r.pause(),window.addEventListener("online",()=>{r.resume()},{once:!0}));else{const e=t.next();if(null==e||e.done)return!1;await new Promise(t=>setTimeout(t,e.value))}}return!0}async getUploadId(e,t){let r;for(;;){if(null==e.data)throw new Error("File data is empty");if(r=this.#fe.get(e.data),null==r)break;try{return await r}catch{}}const i=this.#ve(this.#_e(e),t),n=()=>{if(null==e.data)throw new Error("File data is empty");i.abort(t.reason),this.#fe.delete(e.data)};return t.addEventListener("abort",n,{once:!0}),this.#fe.set(e.data,i),i.then(async r=>{if(t.removeEventListener("abort",n),this.#Fe(e,r),null==e.data)throw new Error("File data is empty");this.#fe.set(e.data,r)},()=>{if(t.removeEventListener("abort",n),null==e.data)throw new Error("File data is empty");this.#fe.delete(e.data)}),i}async abortFileUpload(e){if(null==e.data)throw new Error("File data is empty");const t=this.#fe.get(e.data);if(null==t)return;let r;this.#fe.delete(e.data),this.#Fe(e,Object.create(null));try{r=await t}catch{return}await this.#ge(this.#_e(e),r)}async#Me(e,t,r){const{method:i="POST",url:n,fields:o,headers:a}=await this.#ye(this.#_e(e),{signal:r}).abortOn(r);let s;const l=t.getData();if("POST"===i.toUpperCase()){const e=new FormData;Object.entries(o).forEach(([t,r])=>e.set(t,r)),e.set("file",l),s=e}else s=l;const{onProgress:d,onComplete:c}=t,u=await this.#ke({signature:{url:n,headers:a,method:i},body:s,size:l.size,onProgress:d,onComplete:c,signal:r}).abortOn(r),h=o?.key;return this.#Fe(e,{key:h}),{...u,location:u.location??Ai(n),bucket:o?.bucket,key:h}}async uploadFile(e,t,r){if(qi(r),1===t.length&&!t[0].shouldUseMultipart)return this.#Me(e,t[0],r);const{uploadId:i,key:n}=await this.getUploadId(e,r);qi(r);try{const o=await Promise.all(t.map((t,i)=>this.uploadChunk(e,i+1,t,r)));return qi(r),await this.#Ce(this.#_e(e),{key:n,uploadId:i,parts:o,signal:r},r).abortOn(r)}catch(o){throw o?.cause!==Oi&&"AbortError"!==o?.name&&this.abortFileUpload(e),o}}restoreUploadFile(e,t){if(null==e.data)throw new Error("File data is empty");this.#fe.set(e.data,t)}async resumeUploadFile(e,t,r){if(qi(r),1===t.length&&null!=t[0]&&!t[0].shouldUseMultipart)return this.#Me(e,t[0],r);const{uploadId:i,key:n}=await this.getUploadId(e,r);qi(r);const o=await this.#we(this.#_e(e),{uploadId:i,key:n,signal:r},r).abortOn(r);qi(r);const a=await Promise.all(t.map((t,i)=>{const n=i+1,a=o.find(({PartNumber:e})=>e===n);return null==a?this.uploadChunk(e,n,t,r):(t?.setAsUploaded?.(),{PartNumber:n,ETag:a.ETag})}));return qi(r),this.#Ce(this.#_e(e),{key:n,uploadId:i,parts:a,signal:r},r).abortOn(r)}async uploadChunk(e,t,r,i){qi(i);const{uploadId:n,key:o}=await this.getUploadId(e,i),a=this.#Te.values(),s=this.#Te.values(),l=()=>{const e=a.next();return null==e||e.done?null:e.value};for(;;){qi(i);const a=r.getData(),{onProgress:c,onComplete:u}=r;let h;try{h=await this.#be(this.#_e(e),{uploadId:n,key:o,partNumber:t,body:a,signal:i}).abortOn(i)}catch(d){const e=l();if(null==e||i.aborted)throw d;await new Promise(t=>setTimeout(t,e));continue}qi(i);try{return{PartNumber:t,...await this.#ke({signature:h,body:a,size:a.size,onProgress:c,onComplete:u,signal:i}).abortOn(i)}}catch(d){if(!(await this.#Ee(d,s)))throw d}}}};function Li(e){if(e?.error){const t=new Error(e.message);throw Object.assign(t,e.error),t}return e}function ji(e){const t=e.Expiration;if(t){const e=Math.floor((new Date(t)-Date.now())/1e3);if(e>9)return e}}function zi({meta:e,allowedMetaFields:t,querify:r=!1}){const i=t??Object.keys(e);return e?Object.fromEntries(i.filter(t=>null!=e[t]).map(t=>[r?`metadata[${t}]`:t,String(e[t])])):{}}var $i={allowedMetaFields:!0,limit:6,getTemporarySecurityCredentials:!1,shouldUseMultipart:e=>(e.size||0)>104857600,retryDelays:[0,1e3,3e3,5e3]},Bi=class e extends Vr{static VERSION="5.1.0";#Ue;#Re;requests;uploaderEvents;uploaders;constructor(t,r){super(t,{...$i,uploadPartBytes:e.uploadPartBytes,createMultipartUpload:null,listParts:null,abortMultipartUpload:null,completeMultipartUpload:null,signPart:null,getUploadParameters:null,...r}),this.type="uploader",this.id=this.opts.id||"AwsS3Multipart",this.#Ie(r);const i={createMultipartUpload:this.createMultipartUpload,listParts:this.listParts,abortMultipartUpload:this.abortMultipartUpload,completeMultipartUpload:this.completeMultipartUpload,signPart:r?.getTemporarySecurityCredentials?this.createSignedURL:this.signPart,getUploadParameters:r?.getTemporarySecurityCredentials?this.createSignedURL:this.getUploadParameters};for(const e of Object.keys(i))null==this.opts[e]&&(this.opts[e]=i[e].bind(this));this.requests=this.opts.rateLimitedQueue??new _r(this.opts.limit),this.#Ue=new Di(this.requests,this.opts,this.#Fe,this.#_e),this.uploaders=Object.create(null),this.uploaderEvents=Object.create(null)}[Symbol.for("uppy test: getClient")](){return this.#Re}#Ie(e){null!=e&&("endpoint"in e||"companionUrl"in e||"headers"in e||"companionHeaders"in e||"cookiesRule"in e||"companionCookiesRule"in e)&&("companionUrl"in e&&!("endpoint"in e)&&this.uppy.log("`companionUrl` option has been removed in @uppy/aws-s3, use `endpoint` instead.","warning"),"companionHeaders"in e&&!("headers"in e)&&this.uppy.log("`companionHeaders` option has been removed in @uppy/aws-s3, use `headers` instead.","warning"),"companionCookiesRule"in e&&!("cookiesRule"in e)&&this.uppy.log("`companionCookiesRule` option has been removed in @uppy/aws-s3, use `cookiesRule` instead.","warning"),"endpoint"in e?this.#Re=new Hr(this.uppy,{pluginId:this.id,provider:"AWS",companionUrl:this.opts.endpoint,companionHeaders:this.opts.headers,companionCookiesRule:this.opts.cookiesRule}):("headers"in e&&this.#Ne(),"cookiesRule"in e&&(this.#Re.opts.companionCookiesRule=e.cookiesRule)))}setOptions(e){this.#Ue.setOptions(e),super.setOptions(e),this.#Ie(e)}resetUploaderReferences(e,t){this.uploaders[e]&&(this.uploaders[e].abort({really:t?.abort||!1}),this.uploaders[e]=null),this.uploaderEvents[e]&&(this.uploaderEvents[e].remove(),this.uploaderEvents[e]=null)}#Oe(e){if(!this.#Re)throw new Error(`Expected a \`endpoint\` option containing a URL, or if you are not using Companion, a custom \`${e}\` implementation.`)}createMultipartUpload(e,t){this.#Oe("createMultipartUpload"),qi(t);const r=Tr(this.opts.allowedMetaFields,e.meta),i=zi({meta:e.meta,allowedMetaFields:r});return this.#Re.post("s3/multipart",{filename:e.name,type:e.type,metadata:i},{signal:t}).then(Li)}listParts(e,{key:t,uploadId:r,signal:i},n){i??=n,this.#Oe("listParts"),qi(i);const o=encodeURIComponent(t);return this.#Re.get(`s3/multipart/${encodeURIComponent(r)}?key=${o}`,{signal:i}).then(Li)}completeMultipartUpload(e,{key:t,uploadId:r,parts:i,signal:n},o){n??=o,this.#Oe("completeMultipartUpload"),qi(n);const a=encodeURIComponent(t),s=encodeURIComponent(r);return this.#Re.post(`s3/multipart/${s}/complete?key=${a}`,{parts:i.map(({ETag:e,PartNumber:t})=>({ETag:e,PartNumber:t}))},{signal:n}).then(Li)}#Pe;async#qe(e){if(qi(e?.signal),null==this.#Pe){const{getTemporarySecurityCredentials:t}=this.opts;!0===t?(this.#Oe("getTemporarySecurityCredentials"),this.#Pe=this.#Re.get("s3/sts",e).then(Li)):this.#Pe=t(e),this.#Pe=await this.#Pe,setTimeout(()=>{this.#Pe=null},500*(ji(this.#Pe.credentials)||0))}return this.#Pe}async createSignedURL(e,t){const r=await this.#qe(t),i=ji(r.credentials)||604800,{uploadId:n,key:o,partNumber:a}=t;return{method:"PUT",expires:i,fields:{},url:`${await Ii({accountKey:r.credentials.AccessKeyId,accountSecret:r.credentials.SecretAccessKey,sessionToken:r.credentials.SessionToken,expires:i,bucketName:r.bucket,Region:r.region,Key:o??`${crypto.randomUUID()}-${e.name}`,uploadId:n,partNumber:a})}`,headers:{"Content-Type":e.type}}}signPart(e,{uploadId:t,key:r,partNumber:i,signal:n}){if(this.#Oe("signPart"),qi(n),null==t||null==r||null==i)throw new Error("Cannot sign without a key, an uploadId, and a partNumber");const o=encodeURIComponent(r);return this.#Re.get(`s3/multipart/${encodeURIComponent(t)}/${i}?key=${o}`,{signal:n}).then(Li)}abortMultipartUpload(e,{key:t,uploadId:r,signal:i}){this.#Oe("abortMultipartUpload");const n=encodeURIComponent(t),o=encodeURIComponent(r);return this.#Re.delete(`s3/multipart/${o}?key=${n}`,void 0,{signal:i}).then(Li)}getUploadParameters(e,t){this.#Oe("getUploadParameters");const{meta:r}=e,{type:i,name:n}=r,o=zi({meta:r,allowedMetaFields:Tr(this.opts.allowedMetaFields,e.meta),querify:!0}),a=new URLSearchParams({filename:n,type:i,...o});return this.#Re.get(`s3/params?${a}`,t)}static async uploadPartBytes({signature:{url:e,expires:t,headers:r,method:i="PUT"},body:n,size:o=n.size,onProgress:a,onComplete:s,signal:l}){if(qi(l),null==e)throw new Error("Cannot upload to an undefined URL");return new Promise((d,c)=>{const u=new XMLHttpRequest;function h(){u.abort()}function p(){l?.removeEventListener("abort",h)}u.open(i,e,!0),r&&Object.keys(r).forEach(e=>{u.setRequestHeader(e,r[e])}),u.responseType="text","number"==typeof t&&(u.timeout=1e3*t),l?.addEventListener("abort",h),u.upload.addEventListener("progress",e=>{a(e)}),u.addEventListener("abort",()=>{p(),c(fr())}),u.addEventListener("timeout",()=>{p();const e=/* @__PURE__ */new Error("Request has expired");e.source={status:403},c(e)}),u.addEventListener("load",()=>{if(p(),403===u.status&&u.responseText.includes("<Message>Request has expired</Message>")){const e=/* @__PURE__ */new Error("Request has expired");return e.source=u,void c(e)}if(u.status<200||u.status>=300){const e=/* @__PURE__ */new Error("Non 2xx");return e.source=u,void c(e)}a?.({loaded:o,lengthComputable:!0});const e=u.getAllResponseHeaders().trim().split(/[\r\n]+/),t={__proto__:null};for(const i of e){const e=i.split(": ");t[e.shift()]=e.join(": ")}const{etag:r,location:n}=t;"POST"===i.toUpperCase()&&null==n&&console.error("@uppy/aws-s3: Could not read the Location header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3/#setting-up-your-s3-bucket"),null!=r?(s?.(r),d({...t,ETag:r})):console.error("@uppy/aws-s3: Could not read the ETag header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3/#setting-up-your-s3-bucket")}),u.addEventListener("error",e=>{p();const t=/* @__PURE__ */new Error("Unknown error");t.source=e.target,c(t)}),u.send(n)})}#Fe=(e,{key:t,uploadId:r})=>{const i=this.uppy.getFile(e.id);null!=i&&this.uppy.setFileState(e.id,{s3Multipart:{...i.s3Multipart,key:t,uploadId:r}})};#_e=e=>this.uppy.getFile(e.id)||e;#Ae(e){return new Promise((t,r)=>{if(null==e.data)throw new Error("File data is empty");const i=new Pi(e.data,{companionComm:this.#Ue,log:(...e)=>this.uppy.log(...e),getChunkSize:this.opts.getChunkSize?this.opts.getChunkSize.bind(this):void 0,onProgress:(t,r)=>{const i=this.uppy.getFile(e.id);this.uppy.emit("upload-progress",i,{uploadStarted:i.progress.uploadStarted??0,bytesUploaded:t,bytesTotal:r})},onError:t=>{this.uppy.log(t),this.uppy.emit("upload-error",e,t),this.resetUploaderReferences(e.id),r(t)},onSuccess:r=>{const i={body:{...r},status:200,uploadURL:r.location};this.resetUploaderReferences(e.id),this.uppy.emit("upload-success",this.#_e(e),i),r.location&&this.uppy.log(`Download ${e.name} from ${r.location}`),t(void 0)},onPartComplete:t=>{this.uppy.emit("s3-multipart:part-uploaded",this.#_e(e),t)},file:e,shouldUseMultipart:this.opts.shouldUseMultipart,...e.s3Multipart});this.uploaders[e.id]=i;const n=new Wr(this.uppy);this.uploaderEvents[e.id]=n,n.onFileRemove(e.id,r=>{i.abort(),this.resetUploaderReferences(e.id,{abort:!0}),t(`upload ${r} was removed`)}),n.onCancelAll(e.id,()=>{i.abort(),this.resetUploaderReferences(e.id,{abort:!0}),t(`upload ${e.id} was canceled`)}),n.onFilePause(e.id,e=>{e?i.pause():i.start()}),n.onPauseAll(e.id,()=>{i.pause()}),n.onResumeAll(e.id,()=>{i.start()}),i.start()})}#De(e){return{..."remote"in e&&e.remote?.body,protocol:"s3-multipart",size:e.data.size,metadata:e.meta}}#Le=async e=>{if(0===e.length)return;const t=this.uppy.getFilesByIds(e).filter(e=>!(e=>"error"in e&&!!e.error)(e)&&!(e=>e.progress.uploadComplete)(e)),r=function(e){return e.filter(e=>!e.progress?.uploadStarted||!e.isRestored)}(t);this.uppy.emit("upload-start",r);const i=t.map(e=>{if(e.isRemote){const t=()=>this.requests;this.#je(!1);const r=new AbortController,i=t=>{t.id===e.id&&r.abort()};this.uppy.on("file-removed",i);const n=this.uppy.getRequestClientForFile(e).uploadRemoteFile(e,this.#De(e),{signal:r.signal,getQueue:t});return this.requests.wrapSyncFunction(()=>{this.uppy.off("file-removed",i)},{priority:-1})(),n}return this.#Ae(e)}),n=await Promise.allSettled(i);return this.#je(!0),n};#Ne=()=>{this.#Re?.setCompanionHeaders(this.opts.headers)};#je=e=>{const{capabilities:t}=this.uppy.getState();this.uppy.setState({capabilities:{...t,resumableUploads:e}})};#ze=()=>{this.#je(!0)};install(){this.#je(!0),this.uppy.addPreProcessor(this.#Ne),this.uppy.addUploader(this.#Le),this.uppy.on("cancel-all",this.#ze)}uninstall(){this.uppy.removePreProcessor(this.#Ne),this.uppy.removeUploader(this.#Le),this.uppy.off("cancel-all",this.#ze)}},Hi="undefined"!=typeof window&&(window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB),Vi=!!Hi,Wi="uppy-blobs",Gi="files",Xi=864e5,Yi=1048576;function Qi(e){const t=Hi.open(e,3);return new Promise((e,r)=>{t.onupgradeneeded=t=>{const r=t.target.result,i=t.currentTarget.transaction;if(t.oldVersion<2&&r.createObjectStore(Gi,{keyPath:"id"}).createIndex("store","store",{unique:!1}),t.oldVersion<3){const e=i.objectStore(Gi);e.createIndex("expires","expires",{unique:!1}),function(e){e.openCursor().onsuccess=e=>{const t=e.target.result;if(!t)return;const r=t.value;r.expires=Date.now()+Xi,t.update(r)}}(e)}i.oncomplete=()=>{e(r)}},t.onsuccess=t=>{e(t.target.result)},t.onerror=r})}function Ki(e){return new Promise((t,r)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=r})}var Ji=!1,Zi=class e{#$e;opts;name;static isSupported;constructor(t){this.opts={dbName:Wi,storeName:"default",expires:Xi,maxFileSize:10*Yi,maxTotalSize:300*Yi,...t},this.name=this.opts.storeName;const r=async()=>{const e=await Qi(this.opts.dbName);return this.#$e=e,e};Ji?this.#$e=r():(Ji=!0,this.#$e=e.cleanup().then(r,r))}get ready(){return Promise.resolve(this.#$e)}key(e){return`${this.name}!${e}`}async list(){const e=await Ki((await this.#$e).transaction([Gi],"readonly").objectStore(Gi).index("store").getAll(IDBKeyRange.only(this.name)));return Object.fromEntries(e.map(e=>[e.fileID,e.data]))}async get(e){const{data:t}=await Ki((await this.#$e).transaction([Gi],"readonly").objectStore(Gi).get(this.key(e)));return{id:t.fileID,data:t.data}}async getSize(){const e=(await this.#$e).transaction([Gi],"readonly").objectStore(Gi).index("store").openCursor(IDBKeyRange.only(this.name));return new Promise((t,r)=>{let i=0;e.onsuccess=e=>{const r=e.target.result;r?(i+=r.value.data.size,r.continue()):t(i)},e.onerror=()=>{r(/* @__PURE__ */new Error("Could not retrieve stored blobs size"))}})}async put(e){if(null!=e.data.size&&e.data.size>this.opts.maxFileSize)throw new Error("File is too big to store.");if(await this.getSize()>this.opts.maxTotalSize)throw new Error("No space left");return Ki((await this.#$e).transaction([Gi],"readwrite").objectStore(Gi).add({id:this.key(e.id),fileID:e.id,store:this.name,expires:Date.now()+this.opts.expires,data:e.data}))}async delete(e){return Ki((await this.#$e).transaction([Gi],"readwrite").objectStore(Gi).delete(this.key(e)))}static async cleanup(){const e=await Qi(Wi),t=e.transaction([Gi],"readwrite").objectStore(Gi).index("expires").openCursor(IDBKeyRange.upperBound(Date.now()));await new Promise((e,r)=>{t.onsuccess=t=>{const r=t.target.result;r?(r.delete(),r.continue()):e()},t.onerror=r}),e.close()}};function en(e){try{return JSON.parse(e)}catch{return null}}Zi.isSupported=Vi;var tn="uppyState:",rn=class{opts;name;#Be;constructor(e){var t;this.opts={expires:864e5,throttleTime:500,...e},this.name=(t=e.storeName,`${tn}${t}`),this.#Be=0===this.opts.throttleTime?this.save:(0,Si.default)(this.save,this.opts.throttleTime,{leading:!0,trailing:!0})}#He;load=()=>{!function(){const e=[];for(let r=0;r<localStorage.length;r++){const t=localStorage.key(r);t?.startsWith(tn)&&e.push(t)}const t=Date.now();e.forEach(e=>{const r=localStorage.getItem(e);if(!r)return;const i=en(r);i?.expires&&i.expires<t&&localStorage.removeItem(e)})}();const e=localStorage.getItem(this.name);if(!e)return;const t=en(e);return t?(this.#He=t,t.metadata):void 0};get=()=>this.#He?.metadata;save=()=>{if(null===this.#He)return void localStorage.removeItem(this.name);const e=JSON.stringify(this.#He);localStorage.setItem(this.name,e)};set=e=>{this.#He=null===e?null:{metadata:e,expires:Date.now()+this.opts.expires},this.#Be()}},nn="undefined"!=typeof navigator&&"serviceWorker"in navigator,on=class{#$e;name;static isSupported;constructor(e){this.#$e=new Promise((e,t)=>{nn?navigator.serviceWorker.controller?e():navigator.serviceWorker.addEventListener("controllerchange",()=>{e()}):t(/* @__PURE__ */new Error("Unsupported"))}).then(e=>{this.#$e=e}),this.name=e.storeName}get ready(){return Promise.resolve(this.#$e)}async list(){return await this.#$e,new Promise((e,t)=>{const r=i=>{i.data.store===this.name&&("uppy/ALL_FILES"===i.data.type?(e(i.data.files),navigator.serviceWorker.removeEventListener("message",r)):t())};navigator.serviceWorker.addEventListener("message",r),navigator.serviceWorker.controller.postMessage({type:"uppy/GET_FILES",store:this.name})})}async put(e){await this.#$e,navigator.serviceWorker.controller.postMessage({type:"uppy/ADD_FILE",store:this.name,file:e})}async delete(e){await this.#$e,navigator.serviceWorker.controller.postMessage({type:"uppy/REMOVE_FILE",store:this.name,fileID:e})}};on.isSupported=nn;var an={expires:864e5,serviceWorker:!1},sn=class e extends Vr{static VERSION="5.2.1";#Ve;#We;#Ge;static[Symbol.for("uppy test: throttleTime")];constructor(t,r){super(t,{...an,...r}),this.type="debugger",this.id=this.opts.id||"GoldenRetriever",this.#Ve=new rn({expires:this.opts.expires,storeName:t.getID(),throttleTime:e[Symbol.for("uppy test: throttleTime")]??void 0}),this.opts.serviceWorker&&(this.#We=new on({storeName:t.getID()})),this.#Ge=new Zi({expires:this.opts.expires,...this.opts.indexedDB||{},storeName:t.getID()})}async#Xe(){const e=this.#Ve.load();if(!e)return;const t=e.currentUploads||{},r=Object.entries(e.files||{}),i=Object.fromEntries(r.every(([,e])=>e.progress.complete&&!e.error)?[]:r),n=Object.entries(i);this.uppy.log(`[GoldenRetriever] Recovered ${Object.keys(t).length} current uploads and ${n.length} files from Local Storage`);const o=n.length>0;o||this.uppy.log("[GoldenRetriever] No files need to be loaded, restored only processing state...");const[a,s]=await Promise.all([this.#Ye(),this.#Qe()]),l={...a,...s},d=Object.fromEntries(n.map(([e,t])=>{if(t.isRemote)return[e,{...t,isRestored:!0,data:{size:null}}];const r=l[e];return[e,t.progress.uploadComplete||null!=r?{...t,isRestored:!0,isGhost:!1,data:r}:{...t,isRestored:!0,isGhost:!0,data:void 0}]}));this.uppy.setState({recoveredState:o?e:null,currentUploads:o?t:{},files:d}),this.uppy.emit("restored",e.pluginData);const c=Object.keys(l).filter(e=>!i[e]);if(c.length)try{this.uppy.log(`[GoldenRetriever] Cleaning up ${c.length} old files`),await this.#Ke(c)}catch(u){this.uppy.log(`[GoldenRetriever] Could not clean up ${c.length} old files`,"warning"),this.uppy.log(u)}}#Je=({pluginData:e,...t})=>{const r=this.#Ve.get();this.#Ve.set({...r??{currentUploads:{},files:{}},...t,pluginData:{...r?.pluginData,...e}})};async#Ye(){if(!this.#We)return{};try{const e=await this.#We.list(),t=Object.keys(e).length;return this.uppy.log(t>0?`[GoldenRetriever] Successfully recovered ${t} blobs from Service Worker!`:"[GoldenRetriever] No blobs found in Service Worker"),e}catch(e){return this.uppy.log("[GoldenRetriever] Failed to recover blobs from Service Worker","warning"),this.uppy.log(e),{}}}async#Qe(){try{const e=await this.#Ge.list(),t=Object.keys(e).length;return this.uppy.log(t>0?`[GoldenRetriever] Successfully recovered ${t} blobs from IndexedDB!`:"[GoldenRetriever] No blobs found in IndexedDB"),e}catch(e){return this.uppy.log("[GoldenRetriever] Failed to recover blobs from IndexedDB","warning"),this.uppy.log(e),{}}}async#Ke(e){await Promise.all(e.map(async e=>{try{await Promise.all([this.#We?.delete(e),this.#Ge.delete(e)])}catch(t){this.uppy.log(`[GoldenRetriever] Could not remove file ${e} from all stores`,"warning"),this.uppy.log(t)}})),e.length>0&&this.uppy.log(`[GoldenRetriever] Removed ${e.length} blobs`)}async[Symbol.for("uppy test: deleteBlobs")](e){return this.#Ke(e)}#Ze=async e=>{const{id:t,data:r,isRemote:i}=e;i||null==r||await Promise.all([this.#We?.put({id:t,data:r}).catch(e=>{this.uppy.log("[GoldenRetriever] Could not store file in Service Worker","warning"),this.uppy.log(e)}),this.#Ge.put({id:t,data:r}).catch(e=>{e instanceof Event&&e.target instanceof IDBRequest&&"ConstraintError"===e.target.error?.name||(this.uppy.log("[GoldenRetriever] Could not store file in IndexedDB","warning"),this.uppy.log(e))})])};#et=(e,t,r)=>{if(t.currentUploads!==e.currentUploads){const{currentUploads:e}=this.uppy.getState();this.#Je({currentUploads:e})}if(t.files!==e.files){Object.values(e.files).some(e=>!e.progress.complete)&&(0===Object.values(t.files).length||Object.values(t.files).every(e=>e.progress.complete&&!e.error))&&(this.uppy.log("[GoldenRetriever] All files have been uploaded and processed successfully, clearing recovery state"),this.uppy.setState({recoveredState:null}));const r=Object.fromEntries(Object.entries(t.files).map(([e,{data:t,preview:r,...i}])=>[e,i]));this.#Je({files:r});const i=Object.values(t.files).filter(t=>null==e.files[t.id]),n=Object.values(t.files).flatMap(t=>{const r=e.files[t.id];return null!=r&&t.data!==r.data?[t]:[]}),o=[...Object.values(e.files).filter(e=>{const r=t.files[e.id];return null==r||r.progress.uploadComplete&&!e.progress.uploadComplete}),...n],a=[...i,...n];(async()=>{await this.#Ke(o.map(e=>e.id));for(const e of a)await this.#Ze(e);a.length>0&&this.uppy.log(`[GoldenRetriever] Added ${a.length} blobs`)})()}};#tt=()=>{this.uppy.log("[GoldenRetriever] Restore confirmed, proceeding...");const{currentUploads:e}=this.uppy.getState();Object.keys(e).length>0?(this.uppy.resumeAll(),Object.keys(e).forEach(e=>{this.uppy.restore(e)})):this.uppy.upload(),this.uppy.setState({recoveredState:null})};#rt=e=>{this.#Je({pluginData:e})};install(){this.#Xe(),this.uppy.on("state-update",this.#et),this.uppy.on("restore-confirmed",this.#tt),this.uppy.on("restore:plugin-data-changed",this.#rt)}uninstall(){this.uppy.off("state-update",this.#et),this.uppy.off("restore-confirmed",this.#tt),this.uppy.off("restore:plugin-data-changed",this.#rt)}};function ln(){const e=Ke(),t=f(),r=a(null),n=a(null),o=a({}),s=a(0),l=a(null),d=a({}),c=a(void 0),u=a({}),h=a(!1);i(()=>{const e=t.user;c.current=e?.id??(e?._id?String(e._id):void 0),u.current={organizationId:t.props?.organizationId,token:e?.token}},[t.user,t.props?.organizationId]);const m=p(()=>{const{organizationId:e,token:t}=u.current,r={"Content-Type":"application/json"};return e&&(r["x-org-id"]=e),t&&(r.Authorization=`Bearer ${t}`),r},[]),g=p(()=>{if(!r.current){const t=new Fi({autoProceed:!0}).use(sn,{id:"GoldenRetriever",expires:864e5,serviceWorker:!1}).use(Bi,{shouldUseMultipart:!1,getUploadParameters:async e=>{const t=e.meta;return{method:"PUT",url:t.uploadUrl,fields:{},headers:{"Content-Type":t.rawContentType??e.type??"application/octet-stream"}}}});t.on("upload-progress",(t,r)=>{if(!t)return;const i=t.meta.uid;e.getState().setUploadState(i,{status:"uploading",bytesUploaded:r.bytesUploaded??0,bytesTotal:r.bytesTotal??0});const o=Date.now(),a=Object.values(e.getState().uploadStates).reduce((e,t)=>e+(t.bytesUploaded||0),0),s=n.current;if(s){const t=(o-s.time)/1e3;if(t>=.5){const r=Math.max(0,(a-s.bytes)/t),i=s.speed>0?.7*s.speed+.3*r:r;n.current={time:o,bytes:a,speed:i},e.getState().setUploadSpeedBps(i)}}else n.current={time:o,bytes:a,speed:0}}),t.on("upload-success",r=>{if(!r)return;const i=r.meta.uid,a=r.meta.contentId,s=r.meta.key,l=r.meta.uploadStartedAt;(async()=>{try{const e=await fetch(y.UPLOAD_COMPLETE,{method:"POST",headers:m(),body:JSON.stringify({contentId:a,key:s,clientUploadMs:l?Date.now()-l:void 0})});if(!e.ok){let t=`complete failed: ${e.status}`;try{const r=await e.json();r.error&&(t=`${r.error} (${e.status})`)}catch{}throw new Error(t)}}catch(d){return e.getState().setUploadState(i,{status:"error",error:d instanceof Error?d.message:String(d)}),de(d instanceof Error?d:new Error(String(d)),{component:"useUpload",tags:["upload","complete"],extra:{uid:i,contentId:a}}),void(a&&fetch(y.UPLOAD_FAIL,{method:"POST",headers:m(),body:JSON.stringify({contentId:a})}).catch(()=>{}))}e.getState().setUploadState(i,{status:"success",contentId:a}),delete o.current[i];try{t.removeFile(r.id)}catch{}if(Object.values(e.getState().uploadStates).every(e=>"success"===e.status||"error"===e.status)&&(n.current=null,e.getState().setUploadSpeedBps(0),!h.current)){h.current=!0;const t=Object.values(e.getState().uploadStates).filter(e=>"success"===e.status).length;t>0&&I.success(`${t} file${1===t?"":"s"} uploaded`)}})()}),t.on("upload-error",(t,r)=>{if(!t)return;const i=t.meta.uid,o=t.meta.contentId;e.getState().setUploadState(i,{status:"error",error:r instanceof Error?r.message:String(r)}),o&&fetch(y.UPLOAD_FAIL,{method:"POST",headers:m(),body:JSON.stringify({contentId:o})}).catch(()=>{}),Object.values(e.getState().uploadStates).every(e=>"success"===e.status||"error"===e.status)&&(n.current=null,e.getState().setUploadSpeedBps(0))}),t.on("restored",()=>{const{eventId:r}=e.getState(),i=[],n={},a={};t.getFiles().forEach(e=>{const s=e.meta,l=s.uid;if(!(l&&s.eventId===r&&s.userId===c.current&&e.data instanceof Blob)){try{t.removeFile(e.id)}catch{}return}o.current[l]=e.id;const d=e.data instanceof File?e.data:new File([e.data],e.name,{type:e.type});i.push({uid:l,file:d}),"string"==typeof s.caption&&(n[l]=s.caption),a[l]={status:"uploading",bytesUploaded:e.progress?.bytesUploaded||0,bytesTotal:e.progress?.bytesTotal||e.size||0}}),0!==i.length&&e.setState(e=>({selectedFiles:[...e.selectedFiles,...i],captions:{...e.captions,...n},uploadStates:{...e.uploadStates,...a},hasStarted:!0,showRestoreDialog:!0,restoredUids:i.map(e=>e.uid)}))}),r.current=t}return r.current},[e,m]);i(()=>{g()},[g]);const v=p(async(t,r)=>{const{eventId:i,groupId:n,captions:a,originalFiles:u,trimRanges:h,cropSelections:p,activeFilters:f,skipUploadFilters:v,perFileFilterSkipped:b,filterOverrides:w}=e.getState();let x=u[t];if(!x)return!1;const S=g();try{x=await D(x),e.getState().setUploadState(t,{status:"creating",bytesUploaded:0,bytesTotal:x.size,error:void 0});const u=L(x)?"VIDEO":"IMAGE",g=await z(x);if(s.current!==r)return!1;const T=d.current[t]??=await fe(()=>async function(e){try{return await(t=L(e)?function(e){return new Promise((t,r)=>{const i=URL.createObjectURL(e),n=document.createElement("video");n.muted=!0,n.playsInline=!0,n.preload="auto";let o=!1;const a=(e,a)=>{o||(o=!0,n.removeAttribute("src"),n.load(),URL.revokeObjectURL(i),e?t(e):r(a??/* @__PURE__ */new Error("video intrinsics failed")))};n.onloadedmetadata=()=>{try{n.currentTime=Math.min(.1,n.duration||.1)}catch{}},n.onseeked=()=>{const e=n.videoWidth,t=n.videoHeight,r={...e>0&&t>0&&{dimension:{width:e,height:t}},...Number.isFinite(n.duration)&&n.duration>0&&{duration:n.duration}};try{a({...r,...hr(n,e,t)})}catch(i){console.warn("[media-intrinsics] video frame sample failed:",i),a(r)}},n.onerror=()=>a(void 0,/* @__PURE__ */new Error("video load failed")),n.src=i})}(e):async function(e){const t=await D(e),r=await createImageBitmap(t);try{return{dimension:{width:r.width,height:r.height},...hr(r,r.width,r.height)}}finally{r.close()}}(e),new Promise((e,r)=>{const i=setTimeout(()=>r(/* @__PURE__ */new Error("intrinsics timeout")),8e3);t.then(t=>{clearTimeout(i),e(t)},e=>{clearTimeout(i),r(e)})}))}catch(r){return console.warn("[media-intrinsics] extraction failed:",r),{}}var t}(x));if(s.current!==r)return!1;const C=h[t],F=p[t],k=f.length>0?b[t]??v:void 0,_=await fetch(y.UPLOAD_CREATE,{method:"POST",headers:m(),signal:l.current?.signal,body:JSON.stringify({eventId:i,groupId:n,uid:t,type:u,fileName:x.name,fileSize:x.size,rawContentType:g,caption:a[t],trimInfo:C?{start:C.startTime,end:C.endTime}:void 0,cropInfo:F,dimension:T.dimension,blurhash:T.blurhash,colors:T.colors,duration:T.duration,filtersSkipped:k,filterOverrides:w[t]})});if(!_.ok){let e=`create failed: ${_.status}`;try{const t=await _.json();t.error&&(e=t.error)}catch{}throw new Error(e)}const{contentId:E,key:M,uploadUrl:U}=await _.json();if(s.current!==r)return fetch(y.UPLOAD_ABORT,{method:"POST",headers:m(),body:JSON.stringify({contentId:E,key:M})}).catch(()=>{}),!1;const R=o.current[t];if(R&&S.getFile(R))try{S.removeFile(R)}catch{}const I=S.addFile({name:x.name,type:g,data:x,meta:{uid:t,userId:c.current,contentId:E,key:M,uploadUrl:U,rawContentType:g,eventId:i,groupId:n,type:u,caption:a[t],uploadStartedAt:Date.now()}});return o.current[t]=I,!0}catch(T){return s.current!==r||T instanceof DOMException&&"AbortError"===T.name||(e.getState().setUploadState(t,{status:"error",error:T instanceof Error?T.message:String(T)}),de(T instanceof Error?T:new Error(String(T)),{component:"useUpload",tags:["upload","create"],extra:{uid:t}})),!1}},[e,g,m]),b=p(async()=>{const{selectedFiles:t,oversizedUids:r}=e.getState(),i=t.filter(({uid:e})=>!r[e]);if(0===i.length)return;const n=++s.current;l.current=new AbortController;const o=g();e.getState().setHasStarted(!0),h.current=!1;for(const{uid:a}of i)e.getState().setUploadState(a,{status:"queued",bytesUploaded:0,bytesTotal:0});return await async function(e,t,r){const i=new Array(e.length);let n=0;const o=Array.from({length:Math.min(4,e.length)},async()=>{for(;n<e.length;){const t=n++;i[t]=await r(e[t])}});return await Promise.all(o),i}(i,0,({uid:e})=>v(e,n)),s.current===n?0===o.getFiles().length?(I.error("Could not start upload. Please try again."),void e.getState().setHasStarted(!1)):void(await o.upload()):void 0},[e,g,v]),w=p(()=>{s.current++,l.current?.abort(),n.current=null,o.current={},d.current={},r.current?.cancelAll(),e.getState().resetUploader()},[e]),x=p(t=>{const r=g();n.current=null;const i=o.current[t],a=i?r.getFile(i):void 0;if(a)return e.getState().setUploadState(t,{status:"uploading",bytesUploaded:0,bytesTotal:a.size??0,error:void 0}),void r.retryUpload(i).catch(r=>{e.getState().setUploadState(t,{status:"error",error:r instanceof Error?r.message:String(r)})});v(t,s.current)},[e,g,v]),S=p(()=>{Object.entries(e.getState().uploadStates).filter(([,e])=>"error"===e.status).map(([e])=>e).forEach(e=>x(e))},[e,x]);return i(()=>()=>{s.current++,l.current?.abort(),r.current?.cancelAll(),r.current?.destroy(),r.current=null},[]),{startUpload:b,cancelUpload:w,retryUpload:x,retryAllUploads:S,resumeRestoredUpload:p(()=>{const t=g();l.current=new AbortController,e.setState({showRestoreDialog:!1,restoredUids:[]}),t.upload()},[e,g]),discardRestoredUpload:p(()=>{const t=g(),{restoredUids:r}=e.getState();r.forEach(r=>{const i=o.current[r];if(i){try{t.removeFile(i)}catch{}delete o.current[r]}e.getState().removeFile(r)}),e.setState(e=>{const t={...e.uploadStates};return r.forEach(e=>delete t[e]),{showRestoreDialog:!1,restoredUids:[],uploadStates:t,hasStarted:0!==e.selectedFiles.length&&e.hasStarted}})},[e,g])}}function dn({eventSlug:e,event:t}){const r=f(),n=F(),o=r.props?.organizationId,s=r.user,d=Ke(),c=Qe(e=>e.selectedFiles),u=Qe(e=>e.hasStarted),m=Qe(e=>e.oversizedUids),g=Qe(e=>e.showOversizedModal),C=Qe(e=>e.activeFilters),k=Qe(e=>e.showFilterChoice),_=Qe(e=>e.skipUploadFilters),E=Qe(e=>e.showRestoreDialog),M=Qe(e=>e.restoredUids),[U,R]=l(!1),[N,O]=l(!1),[q,D]=l({}),[j,z]=l(!0);i(()=>{if(!s||!o)return;let t=!1;return z(!0),v.get(y.GET_UPLOAD_COUNT,{searchParams:{eventSlug:e},headers:{"x-org-id":o,...s.token?{Authorization:`Bearer ${s.token}`}:{}}}).json().then(e=>{t||D(e?.data?.uploadCount??{})}).catch(()=>{t||I.error("Failed to fetch upload count")}).finally(()=>{t||z(!1)}),()=>{t=!0}},[s,o,e]);const $=!t.uploadLimit||t.uploadLimit<=0,B=(q[x.APPROVED]??0)+(q[x.IN_REVIEW]??0),H=$?1/0:Math.max(0,(t.uploadLimit??0)-B),V=j,W=$?"Unlimited":H,G=Math.min(H,100),X=!(t.status===w.OPEN)||u||V,Y=t.enableVideo?[...ie,...ne]:ie,Q=!!t.ada,J=function({effectiveFileLimit:e,eventSlug:t}){const r=Ke();return p(i=>{const n=r.getState();if(n.hasStarted)return;const o=e=>`${e.name}-${e.size}-${e.lastModified}`,a=n.selectedFiles,s=new Set(a.map(({file:e})=>o(e))),l=i.filter(e=>{const t=o(e);return!s.has(t)&&(s.add(t),!0)}).map(e=>({uid:te(),file:e})),d=Math.max(0,e-a.length),c=l.slice(0,d),u=l.length-c.length;u>0&&(I.warn(`${u} file${u>1?"s":""} not added — you've reached your upload limit.`),ce("Upload quota limit reached","warning",{component:"UploadPageClient",tags:["upload","quota"],extra:{eventSlug:t,dropped:u,effectiveFileLimit:e}}));const h={};c.forEach(({uid:e,file:t})=>{const r=function(e){const t=L(e),r=t?b:T;return e.size>r?t?"video":"image":void 0}(t);r&&(h[e]=r)}),Object.keys(h).length>0&&(r.getState().addOversizedUids(h),ce("File size limit exceeded","warning",{component:"UploadPageClient",tags:["upload","file-size"],extra:{eventSlug:t,oversizedCount:Object.keys(h).length}}));const p={};c.forEach(({uid:e,file:t})=>{p[e]=t}),r.getState().addOriginalFiles(p),r.getState().setSelectedFiles([...a,...c]),c.forEach(({uid:e,file:t})=>{L(t)&&ge(()=>{return e=t,new Promise(t=>{const r=URL.createObjectURL(e),i=document.createElement("video");i.preload="metadata";let n=!1;const o=e=>{n||(n=!0,clearTimeout(a),i.removeAttribute("src"),i.load(),URL.revokeObjectURL(r),t(e))},a=setTimeout(()=>o(0),1e4);i.onloadedmetadata=()=>o(i.duration),i.onerror=()=>o(0),i.src=r});var e}).then(t=>{t>60&&r.getState().setTrimRange(e,{startTime:0,endTime:60})}).catch(()=>{})})},[e,t,r])}({effectiveFileLimit:G,eventSlug:e}),{startUpload:Z,cancelUpload:ee,retryUpload:se,retryAllUploads:le,resumeRestoredUpload:ue,discardRestoredUpload:pe}=ln(),me=p(()=>{O(!1),u?ee():d.getState().resetUploader()},[u,ee,d]);!function(e){const t=Ke(),r=f(),n=r.props?.organizationId,o=r.user?.token;i(()=>{if(!e||!n)return;let r=!1;return v.get(y.GET_POST_PROCESSING_SETTINGS,{searchParams:{eventId:e},headers:{"x-org-id":n,...o?{Authorization:`Bearer ${o}`}:{}}}).json().then(e=>{if(r||!e?.data)return;const i=e.data.filters??[],n=e.data.showChoice??!1;t.getState().setActiveFilters(i,n&&i.length>0)}).catch(e=>{de(e instanceof Error?e:/* @__PURE__ */new Error("Failed to load upload filters"),{component:"useUploadFilters",tags:["upload","filters"]})}),()=>{r=!0}},[e,n,o,t])}(t._id?String(t._id):void 0),i(()=>{const e={},t=t=>{Object.entries(t.uploadStates).forEach(([r,i])=>{"success"!==i.status||e[r]||t.selectedFiles.some(e=>e.uid===r)&&(e[r]=setTimeout(()=>{delete e[r],d.getState().removeFile(r)},3e3))})};t(d.getState());const r=d.subscribe(t);return()=>{r(),Object.values(e).forEach(clearTimeout)}},[d]),i(()=>{0===c.length&&u&&d.getState().resetUploader()},[c.length,u,d]),i(()=>{if(!u)return;const e=e=>{Object.values(d.getState().uploadStates).some(e=>"queued"===e.status||"creating"===e.status||"uploading"===e.status)&&e.preventDefault()};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[u,d]);const fe=p(e=>d.getState().removeFile(e),[d]),ve=p(()=>{if(!Q)return!0;const e=d.getState(),t=e.selectedFiles.some(({uid:t})=>!e.oversizedUids[t]&&!e.captions[t]?.trim());return t&&I.warn("This event requires a caption on every file before uploading."),!t},[Q,d]),be=p(()=>{ve()&&(Object.keys(d.getState().oversizedUids).length>0?d.getState().setShowOversizedModal(!0):Z())},[d,Z,ve]),ye=p(()=>{!s||s.tcAccepted?be():R(!0)},[s,be]),we=p(()=>{d.getState().removeOversizedFiles(),ve()&&Z()},[d,Z,ve]),[xe,Se]=l(!1),Te=a(0),Ce=X||c.length>=G;/* @__PURE__ */
|
|
76
78
|
return h("div",{className:"bg-background relative min-h-screen px-3 pb-9 lg:px-0",onDragEnter:e=>{e.preventDefault(),Ce||(Te.current+=1,Se(!0))},onDragOver:e=>e.preventDefault(),onDragLeave:()=>{Te.current=Math.max(0,Te.current-1),0===Te.current&&Se(!1)},onDrop:p(e=>{if(e.preventDefault(),Te.current=0,Se(!1),Ce)return;const t=e.dataTransfer?.files;t&&t.length>0&&J(Array.from(t))},[Ce,J]),children:[xe&&/* @__PURE__ */h("div",{className:"border-primary bg-background/90 fixed inset-0 z-2003 flex items-center justify-center border-4 border-dashed",children:/* @__PURE__ */h("p",{className:"text-primary text-2xl font-semibold",children:"Drop to add files"})}),
|
|
77
79
|
/* @__PURE__ */h("div",{className:"mx-auto max-w-4xl space-y-6",children:[
|
|
78
|
-
/* @__PURE__ */h(
|
|
79
|
-
/* @__PURE__ */h("div",{className:"flex items-center justify-between py-2",children:[/* @__PURE__ */h("p",{className:"text-muted-foreground text-sm font-medium",children:[c.length," selected"]}),!u&&c.length<G&&/* @__PURE__ */h(
|
|
80
|
-
/* @__PURE__ */h("div",{className:"grid grid-cols-1 gap-4 py-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:c.map(({uid:e,file:t})=>/* @__PURE__ */h(
|
|
81
|
-
/* @__PURE__ */h(
|
|
80
|
+
/* @__PURE__ */h(Ut,{uploadDisabled:X,eventName:t.name,isQuotaLoading:V,remainingUploads:W}),!t.enableVideo&&/* @__PURE__ */h("div",{className:"mx-auto max-w-lg rounded border border-blue-500/20 bg-blue-500/10 p-3 text-center text-sm font-medium text-blue-600 dark:text-blue-400",children:"Video upload turned off by event admin"}),0===c.length&&!u&&/* @__PURE__ */h(_t,{enabledFileTypes:Y,disabled:X,onFileSelect:J,selectedCount:c.length,maxCount:G,enableVideo:t.enableVideo})]}),c.length>0&&/* @__PURE__ */h("div",{className:"mx-auto mt-8 w-full max-w-full pb-36 sm:px-0 md:pb-24",children:[k&&C.length>0&&!u&&/* @__PURE__ */h("div",{className:"border-border bg-card mb-4 flex items-center gap-3 rounded-lg border p-3",children:[/* @__PURE__ */h(re,{checked:!_,onChange:e=>{d.getState().setSkipUploadFilters(!e);const t={};e||c.forEach(({uid:e})=>{t[e]=!0}),d.setState({perFileFilterSkipped:t})},label:"Apply filters"}),/* @__PURE__ */h("span",{className:"text-muted-foreground -ml-1 text-sm",children:"— upload with filters applied"})]}),
|
|
81
|
+
/* @__PURE__ */h("div",{className:"flex items-center justify-between py-2",children:[/* @__PURE__ */h("p",{className:"text-muted-foreground text-sm font-medium",children:[c.length," selected"]}),!u&&c.length<G&&/* @__PURE__ */h(Mt,{enabledFileTypes:Y,disabled:X,onFileSelect:J})]}),
|
|
82
|
+
/* @__PURE__ */h("div",{className:"grid grid-cols-1 gap-4 py-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:c.map(({uid:e,file:t})=>/* @__PURE__ */h(Tt,{uid:e,file:t,onRemove:fe,disabled:u,adaRequired:Q,onRetry:se},e))}),!u&&c.length<G&&/* @__PURE__ */h(Et,{enabledFileTypes:Y,disabled:X,onFileSelect:J}),!u&&/* @__PURE__ */h(P,{className:"mt-2 w-full gap-2",onClick:ye,disabled:X||0===c.length,children:[/* @__PURE__ */h(A,{className:"size-4"}),"Upload"]}),
|
|
83
|
+
/* @__PURE__ */h(Ft,{selectedCount:c.length,onUpload:ye,onCancel:()=>O(!0),onRetryAll:le,uploadDisabled:X||0===c.length})]}),!u&&/* @__PURE__ */h("div",{className:"mx-auto mt-12 max-w-4xl text-center",children:/* @__PURE__ */h(P,{onClick:()=>n(S.GALLERY(e)),children:"View gallery"})}),
|
|
82
84
|
/* @__PURE__ */h(oe,{open:g,oversizedUids:m,onClose:()=>d.getState().setShowOversizedModal(!1),onRemoveAndUpload:we}),
|
|
83
|
-
/* @__PURE__ */h(ae,{open:E,count:M.length,onResume:
|
|
84
|
-
/* @__PURE__ */h(K,{open:
|
|
85
|
-
/* @__PURE__ */h(
|
|
85
|
+
/* @__PURE__ */h(ae,{open:E,count:M.length,onResume:ue,onDiscard:pe}),
|
|
86
|
+
/* @__PURE__ */h(K,{open:N,onOpenChange:O,title:"Cancel upload?",description:u?"Active uploads will be stopped and any in-progress files may be lost.":"Your selected files will be cleared.",cancelText:"Keep uploading",confirmText:u?"Stop upload":"Clear selection",confirmColor:"error",onCancel:()=>O(!1),onConfirm:me}),
|
|
87
|
+
/* @__PURE__ */h(he,{open:U,onClose:()=>R(!1),onSuccess:()=>{R(!1),be()}})]})}var cn=()=>{const{eventSlug:e}=_(),t=C(),r=F(),{loadingUser:n,user:o}=f();i(()=>{n||o||r("/auth/login",{state:{referrer:t.pathname},replace:!0})},[n,o]);const{loading:s,event:l}=O({eventSlug:e}),d=a(te());return s||l&&l.status!==w.CLOSED?/* @__PURE__ */h("div",l&&e?{className:"bg-background mx-auto min-h-screen pt-16",children:/* @__PURE__ */h(Ye,{eventId:String(l._id),groupId:d.current,children:/* @__PURE__ */h(dn,{eventSlug:e,event:l})})}:{className:"bg-background min-h-screen"}):/* @__PURE__ */h("div",{className:"bg-background mx-auto min-h-[80] pt-16 pb-36",children:/* @__PURE__ */h(pe,{event:l,locationState:t?.state})})};export{cn as default};
|