@qratilabs/qrati-connect 2.23.0-beta.2 → 2.23.0-beta.3
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/{BxeYKf-v2.js → CdHR1K3m2.js} +25 -25
- package/element/web.es.js +46 -46
- package/package.json +1 -1
- package/umd/{BxeYKf-v2.js → CdHR1K3m2.js} +25 -25
- package/umd/web.es.js +46 -46
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e,t}from"./Cko4QHwX.js";import{C as r,D as i,a as n,b as o,c as a,d as s,f as l,g as d,h as c,o as u,p as h,s as p,t as m,v as g,y as f}from"./qbHuxVSe.js";import{D as v,E as w,N as b,T as y,i as x,n as S,p as C,u as T,y as F}from"./WtQ5axEj.js";import{c as k,l as _,n as E,u as M}from"./lVJD5cJY.js";import{t as U}from"./BekfKWcG.js";import{r as R}from"./DWbLshVZ.js";import{t as I}from"./2SYk3iBo.js";import{t as D}from"./BkIDQGIs.js";import{t as
|
|
1
|
+
import{n as e,t}from"./Cko4QHwX.js";import{C as r,D as i,a as n,b as o,c as a,d as s,f as l,g as d,h as c,o as u,p as h,s as p,t as m,v as g,y as f}from"./qbHuxVSe.js";import{D as v,E as w,N as b,T as y,i as x,n as S,p as C,u as T,y as F}from"./WtQ5axEj.js";import{c as k,l as _,n as E,u as M}from"./lVJD5cJY.js";import{t as U}from"./BekfKWcG.js";import{r as R}from"./DWbLshVZ.js";import{t as I}from"./2SYk3iBo.js";import{t as D}from"./BkIDQGIs.js";import{t as N}from"./C9HFLidt.js";import{n as P}from"./CYQ06kUR.js";import{t as O}from"./C0vZ8zxT.js";import{r as A,t as q}from"./D8Se70tP2.js";import{a as L,i as z,n as j,o as $,r as B,t as H}from"./CMQUiMWC2.js";import{t as W}from"./BCu0TrNB2.js";import{a as V,n as G,r as X,t as Y}from"./Wun_Og5n2.js";var K,Q=[];for(let wn=0;wn<256;++wn)Q.push((wn+256).toString(16).slice(1));var J=new Uint8Array(16),Z={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ee(e,t,r){return!Z.randomUUID||t||e?function(e,t,r){const i=(e=e||{}).random??e.rng?.()??function(){if(!K){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");K=crypto.getRandomValues.bind(crypto)}return K(J)}();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(Q[e[t+0]]+Q[e[t+1]]+Q[e[t+2]]+Q[e[t+3]]+"-"+Q[e[t+4]]+Q[e[t+5]]+"-"+Q[e[t+6]]+Q[e[t+7]]+"-"+Q[e[t+8]]+Q[e[t+9]]+"-"+Q[e[t+10]]+Q[e[t+11]]+Q[e[t+12]]+Q[e[t+13]]+Q[e[t+14]]+Q[e[t+15]]).toLowerCase()}(i)}(e,t,r):Z.randomUUID()}function te({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
2
|
return m("label",{className:x("flex items-center gap-2",a&&"cursor-not-allowed opacity-50",!a&&"cursor-pointer"),children:[/* @__PURE__ */m("button",{type:"button",role:"switch","aria-checked":s,disabled:a,"data-state":l,onBlur:i,onClick:()=>!a&&r?.(!s),className:x("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__ */m("span",{"data-state":l,className:x("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__ */m("span",{className:"text-sm font-medium",children:n})]})}var re=["jpg","jpeg","png","webp","heic","tiff","bmp","avif"],ie=["mp4","webm","ogg","mov","avi","flv","wmv","mkv","3gp","m4v","mpg","mpeg"];function ne({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__ */m(H,{open:e,onOpenChange:e=>!e&&r(),children:/* @__PURE__ */m(j,{children:[/* @__PURE__ */m(L,{children:[/* @__PURE__ */m($,{children:"Some files are too large"}),/* @__PURE__ */m(B,{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__ */m(z,{children:/* @__PURE__ */m(I,{onClick:i,children:"Remove and Upload"})})]})})}function oe({open:e,count:t,onResume:r,onDiscard:i}){/* @__PURE__ */
|
|
3
3
|
return m(H,{open:e,onOpenChange:e=>!e&&i(),children:/* @__PURE__ */m(j,{children:[/* @__PURE__ */m(L,{children:[/* @__PURE__ */m($,{children:"Resume your upload?"}),/* @__PURE__ */m(B,{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__ */m(z,{children:[/* @__PURE__ */m(I,{variant:"outlined",onClick:i,children:"Remove All"}),/* @__PURE__ */m(I,{onClick:r,children:"Resume"})]})]})})}var ae=({open:e,onClose:t,onSuccess:r})=>{const{t:i}=R(),[n,o]=c(!1),a=S(),s=a.props?.organizationId,{user:l,updateUser:d}=a;/* @__PURE__ */
|
|
4
4
|
return m(H,{open:e,onOpenChange:e=>!e&&t(),children:/* @__PURE__ */m(j,{children:/* @__PURE__ */m("div",{className:"mx-auto max-w-sm p-4 text-center sm:max-w-lg",children:[
|
|
@@ -7,10 +7,10 @@ return m(H,{open:e,onOpenChange:e=>!e&&t(),children:/* @__PURE__ */m(j,{children
|
|
|
7
7
|
/* @__PURE__ */m("div",{className:"mt-4 mb-6",children:/* @__PURE__ */m("p",{className:"bg-background text-base",children:[i("upload.terms_prompt","I agree to the")," ",
|
|
8
8
|
/* @__PURE__ */m("a",{href:"https://beta.qratilabs.com/terms-of-use",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__ */m("a",{href:"https://beta.qratilabs.com/privacy-policy",className:"text-info inline-flex items-center gap-1 underline",target:"_blank",rel:"noopener noreferrer",children:i("upload.privacy_policy","Privacy Policy")})," "]})}),
|
|
10
|
-
/* @__PURE__ */m(I,{fullWidth:!0,color:"success",disabled:n,loading:n,onClick:async()=>{o(!0);try{const e=await b.post(T.ACCEPT_TERMS,{headers:{"x-org-id":s,Authorization:l?.token?`Bearer ${l.token}`:void 0}}).json();if(e.error)throw new Error(e.error);await d({tcAccepted:!0}),o(!1),r()}catch(e){console.error("Error accepting terms:",e),
|
|
10
|
+
/* @__PURE__ */m(I,{fullWidth:!0,color:"success",disabled:n,loading:n,onClick:async()=>{o(!0);try{const e=await b.post(T.ACCEPT_TERMS,{headers:{"x-org-id":s,Authorization:l?.token?`Bearer ${l.token}`:void 0}}).json();if(e.error)throw new Error(e.error);await d({tcAccepted:!0}),o(!1),r()}catch(e){console.error("Error accepting terms:",e),P.error(i("upload.accept_failed","Failed to accept terms"))}o(!1)},children:i("button.accept","Accept")})]})})})},se=({event:e,locationState:t})=>{const{t:r}=R();/* @__PURE__ */
|
|
11
11
|
return m("div",{className:"mx-auto mt-24 w-fit max-w-xl space-y-8",children:[
|
|
12
12
|
/* @__PURE__ */m(U,{variant:"h3",align:"center",children:r("upload.event_closed","Upload Closed")}),
|
|
13
|
-
/* @__PURE__ */m(U,{variant:"h5",align:"center",color:"muted",children:r("upload.closed_description","This event is no longer accepting uploads.")}),e?.status!==F.CLOSED&&/* @__PURE__ */m("div",{className:"flex flex-row justify-end",children:/* @__PURE__ */m(E,{to:v.PUBLIC_EVENTS,state:t,children:/* @__PURE__ */m(I,{children:r("button.back_to_events","Back to Events")})})})]})};function le(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 de=le(2,!1),ce=le(1,!0),ue="error";function he(e){try{const t=JSON.stringify(e);fetch(T.REPORT_ERROR,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0}).catch(()=>{})}catch{}}function pe(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??""),he({message:r,stack:i,level:t?.level??ue,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 me(e,t="info",r){t===ue||"fatal"===t?console.error(`[${r?.component??"app"}]`,e,r?.extra??""):console.warn(`[${r?.component??"app"}]`,e,r?.extra??""),he({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 ge(e,t,r,i,n,o,a,s,l,d,c,u,h,p,m,g,f,v,w,b){return y=>{const{data:x,width:S,height:C}=y,T=new Uint8ClampedArray(x.length);for(let F=0;F<x.length;F+=4){const y=x[F],S=x[F+1],C=x[F+2],k=x[F+3];T[F]=Math.min(255,Math.max(0,Math.round(e*y+t*S+r*C+i*k+255*n))),T[F+1]=Math.min(255,Math.max(0,Math.round(o*y+a*S+s*C+l*k+255*d))),T[F+2]=Math.min(255,Math.max(0,Math.round(c*y+u*S+h*C+p*k+255*m))),T[F+3]=Math.min(255,Math.max(0,Math.round(g*y+f*S+v*C+w*k+255*b)))}return new ImageData(T,S,C)}}function fe(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 ve(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(),be=[{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=new Int32Array(256),a=new Int32Array(256),s=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=fe(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=fe(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],w=[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&&w.push(M);f.push(255),v.push(255),w.push(255);const b=ve(f),y=ve(v),x=ve(w),S=256/Math.max(1,b.high-b.low),C=256/Math.max(1,y.high-y.low),T=256/Math.max(1,x.high-x.low),F=-b.low/256*S,k=-y.low/256*C,_=-x.low/256*T,E=fe(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:C,gB:0,gA:0,gOff:k,bR:0,bG:0,bB:T,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 ge(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=>ge(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:[]}],ye="\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(),xe=new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),Se=null,Ce=null,Te=null;function Fe(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),pe(/* @__PURE__ */new Error(`WebGL shader compilation failed: ${r}`),{component:"webgl-filter-engine",tags:["uploadv2","filter","webgl","shader"],extra:{shaderType:t===e.VERTEX_SHADER?"vertex":"fragment"}}),e.deleteShader(i),null}return i}function ke(e,t){const r=Fe(e,e.VERTEX_SHADER,ye),i=Fe(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),pe(/* @__PURE__ */new Error(`WebGL program link failed: ${r}`),{component:"webgl-filter-engine",tags:["uploadv2","filter","webgl","link"],extra:{fragmentLength:t.length}}),e.deleteProgram(n),null}return n}function _e(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 Ee(e,t,r){const i=_e(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 Me(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 Ue(e){const t=e.config,r=t?.templateId,i=t?.fragShader;if(r){const e=(n=r,be.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 Re(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 Ie(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=Se??new OffscreenCanvas(l,d);g.width===l&&g.height===d||(g.width=l,g.height=d),Se=g;let f=Ce;if(f||(f=g.getContext("webgl",{preserveDrawingBuffer:!0,alpha:!0})||g.getContext("experimental-webgl",{preserveDrawingBuffer:!0,alpha:!0}),Ce=f),!f||f.isContextLost())return m.close(),Ce=null,Se=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}=Ue(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=_e(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 w=[Ee(f,l,d),Ee(f,l,d)],b=f.createBuffer();f.bindBuffer(f.ARRAY_BUFFER,b),f.bufferData(f.ARRAY_BUFFER,xe,f.STATIC_DRAW);const y=Te??/* @__PURE__ */new Map;Te=y;const x=[];let S=v,C=0;try{for(let e=0;e<a.length;e++){const t=a[e],r=e===a.length-1,{def:i,fragShader:n}=Ue(t);if(!n)continue;const o=t.config?.templateId??n;y.has(o)||y.set(o,ke(f,n));const s=y.get(o);if(!s)continue;f.useProgram(s);const c=f.getAttribLocation(s,"a_position");f.bindBuffer(f.ARRAY_BUFFER,b),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),Me(f,s,Re(t)),i?.analyze&&Me(f,s,i.analyze(p,t.config?.variables??{})),r)f.bindFramebuffer(f.FRAMEBUFFER,null),f.drawArrays(f.TRIANGLES,0,6);else{const e=w[C];f.bindFramebuffer(f.FRAMEBUFFER,e.fbo),f.drawArrays(f.TRIANGLES,0,6),S=e.tex,C=1-C}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 w)f.deleteFramebuffer(e),f.deleteTexture(t);f.deleteTexture(v),f.deleteBuffer(b)}}async function De(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}=Ue(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),pe(c instanceof Error?c:/* @__PURE__ */new Error(`buildCpuTransform failed for ${u.id}`),{component:"webgl-filter-engine",tags:["uploadv2","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 Pe=800;async function Ne(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)})}function Oe({label:e,info:t,className:r,error:i,disabled:n,id:o,...a}){const s=d(),l=o??s,c=[t?`${l}-info`:null,i?`${l}-error`:null].filter(Boolean);/* @__PURE__ */
|
|
13
|
+
/* @__PURE__ */m(U,{variant:"h5",align:"center",color:"muted",children:r("upload.closed_description","This event is no longer accepting uploads.")}),e?.status!==F.CLOSED&&/* @__PURE__ */m("div",{className:"flex flex-row justify-end",children:/* @__PURE__ */m(E,{to:v.PUBLIC_EVENTS,state:t,children:/* @__PURE__ */m(I,{children:r("button.back_to_events","Back to Events")})})})]})};function le(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 de=le(2,!1),ce=le(1,!0),ue="error";function he(e){try{const t=JSON.stringify(e);fetch(T.REPORT_ERROR,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0}).catch(()=>{})}catch{}}function pe(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??""),he({message:r,stack:i,level:t?.level??ue,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 me(e,t="info",r){t===ue||"fatal"===t?console.error(`[${r?.component??"app"}]`,e,r?.extra??""):console.warn(`[${r?.component??"app"}]`,e,r?.extra??""),he({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 ge(e,t,r,i,n,o,a,s,l,d,c,u,h,p,m,g,f,v,w,b){return y=>{const{data:x,width:S,height:C}=y,T=new Uint8ClampedArray(x.length);for(let F=0;F<x.length;F+=4){const y=x[F],S=x[F+1],C=x[F+2],k=x[F+3];T[F]=Math.min(255,Math.max(0,Math.round(e*y+t*S+r*C+i*k+255*n))),T[F+1]=Math.min(255,Math.max(0,Math.round(o*y+a*S+s*C+l*k+255*d))),T[F+2]=Math.min(255,Math.max(0,Math.round(c*y+u*S+h*C+p*k+255*m))),T[F+3]=Math.min(255,Math.max(0,Math.round(g*y+f*S+v*C+w*k+255*b)))}return new ImageData(T,S,C)}}function fe(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 ve(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(),be=[{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=new Int32Array(256),a=new Int32Array(256),s=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=fe(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=fe(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],w=[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&&w.push(M);f.push(255),v.push(255),w.push(255);const b=ve(f),y=ve(v),x=ve(w),S=256/Math.max(1,b.high-b.low),C=256/Math.max(1,y.high-y.low),T=256/Math.max(1,x.high-x.low),F=-b.low/256*S,k=-y.low/256*C,_=-x.low/256*T,E=fe(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:C,gB:0,gA:0,gOff:k,bR:0,bG:0,bB:T,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 ge(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=>ge(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:[]}],ye="\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(),xe=new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),Se=null,Ce=null,Te=null;function Fe(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),pe(/* @__PURE__ */new Error(`WebGL shader compilation failed: ${r}`),{component:"webgl-filter-engine",tags:["uploadv2","filter","webgl","shader"],extra:{shaderType:t===e.VERTEX_SHADER?"vertex":"fragment"}}),e.deleteShader(i),null}return i}function ke(e,t){const r=Fe(e,e.VERTEX_SHADER,ye),i=Fe(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),pe(/* @__PURE__ */new Error(`WebGL program link failed: ${r}`),{component:"webgl-filter-engine",tags:["uploadv2","filter","webgl","link"],extra:{fragmentLength:t.length}}),e.deleteProgram(n),null}return n}function _e(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 Ee(e,t,r){const i=_e(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 Me(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 Ue(e){const t=e.config,r=t?.templateId,i=t?.fragShader;if(r){const e=(n=r,be.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 Re(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 Ie(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=Se??new OffscreenCanvas(l,d);g.width===l&&g.height===d||(g.width=l,g.height=d),Se=g;let f=Ce;if(f||(f=g.getContext("webgl",{preserveDrawingBuffer:!0,alpha:!0})||g.getContext("experimental-webgl",{preserveDrawingBuffer:!0,alpha:!0}),Ce=f),!f||f.isContextLost())return m.close(),Ce=null,Se=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}=Ue(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=_e(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 w=[Ee(f,l,d),Ee(f,l,d)],b=f.createBuffer();f.bindBuffer(f.ARRAY_BUFFER,b),f.bufferData(f.ARRAY_BUFFER,xe,f.STATIC_DRAW);const y=Te??/* @__PURE__ */new Map;Te=y;const x=[];let S=v,C=0;try{for(let e=0;e<a.length;e++){const t=a[e],r=e===a.length-1,{def:i,fragShader:n}=Ue(t);if(!n)continue;const o=t.config?.templateId??n;y.has(o)||y.set(o,ke(f,n));const s=y.get(o);if(!s)continue;f.useProgram(s);const c=f.getAttribLocation(s,"a_position");f.bindBuffer(f.ARRAY_BUFFER,b),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),Me(f,s,Re(t)),i?.analyze&&Me(f,s,i.analyze(p,t.config?.variables??{})),r)f.bindFramebuffer(f.FRAMEBUFFER,null),f.drawArrays(f.TRIANGLES,0,6);else{const e=w[C];f.bindFramebuffer(f.FRAMEBUFFER,e.fbo),f.drawArrays(f.TRIANGLES,0,6),S=e.tex,C=1-C}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 w)f.deleteFramebuffer(e),f.deleteTexture(t);f.deleteTexture(v),f.deleteBuffer(b)}}async function De(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}=Ue(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),pe(c instanceof Error?c:/* @__PURE__ */new Error(`buildCpuTransform failed for ${u.id}`),{component:"webgl-filter-engine",tags:["uploadv2","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 Ne=800;async function Pe(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)})}function Oe({label:e,info:t,className:r,error:i,disabled:n,id:o,...a}){const s=d(),l=o??s,c=[t?`${l}-info`:null,i?`${l}-error`:null].filter(Boolean);/* @__PURE__ */
|
|
14
14
|
return m("div",{className:"space-y-1.5",children:[e&&/* @__PURE__ */m("label",{htmlFor:l,className:"block text-base font-medium",children:e}),
|
|
15
15
|
/* @__PURE__ */m("textarea",{id:l,className:x("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__ */m("p",{id:`${l}-info`,className:"text-muted-foreground text-xs",children:t}),i&&/* @__PURE__ */m("p",{id:`${l}-error`,className:"text-destructive text-xs",children:i})]})}var Ae=/\.(mp4|mov|avi|mkv|webm|qt)$/i,qe=/\.(heic|heif)$/i,Le=/\.(heic|heif|jpg|jpeg|png|webp|gif)$/i;function ze(e){return e.type.startsWith("video/")||Ae.test(e.name)}var je=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},$e=e=>e;var Be=i(null);function He({children:e,...t}){const r=l(null),i=l(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:{},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};return delete d[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}}),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};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]}),{selectedFiles:e.selectedFiles.filter(e=>!t.has(e.uid)),captions:r,trimRanges:i,originalFiles:n,cropSelections:o,uploadStates:a,filteredThumbs:s,perFileFilterSkipped:l,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}})),setFilteredThumb:(e,r)=>t(t=>({filteredThumbs:{...t.filteredThumbs,[e]:r}})),resetUploader:()=>t({selectedFiles:[],originalFiles:{},captions:{},hasStarted:!1,oversizedUids:{},showOversizedModal:!1,trimRanges:{},cropSelections:{},uploadStates:{},uploadSpeedBps:0,skipUploadFilters:!1,perFileFilterSkipped:{},filteredThumbs:{}})}))?je(t):je;var t}(t),i.current=t),/* @__PURE__ */m(Be.Provider,{value:r.current,children:e})}function We(e){const t=f(Be);if(!t)throw new Error("useUploadStore must be used within UploadStoreProvider");return function(e,t=$e){const r=a.useSyncExternalStore(e.subscribe,a.useCallback(()=>t(e.getState()),[e,t]),a.useCallback(()=>t(e.getInitialState()),[e,t]));return a.useDebugValue(r),r}(t,e)}function Ve(){const e=f(Be);if(!e)throw new Error("useUploadStoreInstance must be used within UploadStoreProvider");return e}var Ge=/* @__PURE__ */new Map,Xe=null;function Ye({className:e}){/* @__PURE__ */
|
|
16
16
|
return m("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__ */m("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 Ke({className:e}){/* @__PURE__ */
|
|
@@ -24,14 +24,14 @@ return m("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",view
|
|
|
24
24
|
return m("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__ */m("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 nt({className:e}){/* @__PURE__ */
|
|
25
25
|
return m("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__ */m("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 ot({className:e}){/* @__PURE__ */
|
|
26
26
|
return m("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__ */m("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 at({className:e}){/* @__PURE__ */
|
|
27
|
-
return m("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__ */m("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"})})}var st=s(()=>import("./CKk0UYyd.js").then(e=>({default:e.ReactCompareSlider})));function lt({open:e,onClose:t,file:r,filters:i,isVideo:n,trimRange:a}){const[s,d]=c(),[u,h]=c(),[g,f]=c(!0),[v,w]=c(!1),[b,y]=c(),[S,C]=c(0),[T,F]=c(!1),[k,_]=c(null),[E,M]=c(null),[U,R]=c(!1),[I,D]=c(!0),[P
|
|
28
|
-
return m(H,{open:e,onOpenChange:e=>!e&&t(),children:/* @__PURE__ */m(j,{className:x(T?"max-w-none rounded-none":"max-w-2xl sm:w-2xl"),children:/* @__PURE__ */m("div",{className:"bg-background",children:[/* @__PURE__ */m(L,{className:"flex-row items-center justify-between space-y-0",children:[/* @__PURE__ */m($,{children:"Compare original & filtered"}),/* @__PURE__ */m(G,{size:"sm",variant:"ghost","aria-label":T?"Exit fullscreen":"Fullscreen",tooltip:T?"Exit fullscreen":"Fullscreen",icon:/* @__PURE__ */m(T?ot:at,{}),onClick:A})]}),/* @__PURE__ */m("div",{ref:O,className:x("p-4 pt-0",T&&"bg-background relative flex h-screen w-screen items-center justify-center p-0"),children:[T&&/* @__PURE__ */m(G,{size:"sm",variant:"ghost","aria-label":"Exit fullscreen",tooltip:"Exit fullscreen",className:"absolute top-2 right-2 z-30",icon:/* @__PURE__ */m(ot,{}),onClick:A}),g&&/* @__PURE__ */m("div",{className:"flex h-64 flex-col items-center justify-center gap-2",children:[/* @__PURE__ */m(V,{}),n&&/* @__PURE__ */m("p",{className:"text-muted-foreground text-sm",children:["Generating preview… ",S,"%"]})]}),v&&/* @__PURE__ */m("div",{className:"text-muted-foreground flex h-64 items-center justify-center text-sm",children:"Couldn't generate preview."}),!n&&!g&&!v&&s&&u&&/* @__PURE__ */m(p,{fallback:null,children:/* @__PURE__ */m(st,{style:{width:"100%",maxHeight:q,aspectRatio:b},position:50,onlyHandleDraggable:!0,itemOne:/* @__PURE__ */m("div",{className:"relative size-full",children:[/* @__PURE__ */m("img",{alt:"Original",className:"size-full object-contain",src:s}),/* @__PURE__ */m(dt,{position:"left",children:"Original"})]}),itemTwo:/* @__PURE__ */m("div",{className:"relative size-full",children:[/* @__PURE__ */m("img",{alt:"Filtered",className:"size-full object-contain",src:u}),/* @__PURE__ */m(dt,{position:"right",children:"Filtered"})]})})}),n&&/* @__PURE__ */m("div",{className:"relative",style:{visibility:g||v?"hidden":"visible"},children:[/* @__PURE__ */m(p,{fallback:null,children:/* @__PURE__ */m(st,{style:{width:"100%",maxHeight:q,aspectRatio:b},position:50,onlyHandleDraggable:!0,itemOne:/* @__PURE__ */m("div",{className:"relative size-full",children:[/* @__PURE__ */m("video",{ref:_,playsInline:!0,className:"pointer-events-none size-full object-contain"}),/* @__PURE__ */m(dt,{position:"left",children:"Original"})]}),itemTwo:/* @__PURE__ */m("div",{className:"relative size-full",children:[/* @__PURE__ */m("canvas",{ref:M,className:"size-full object-contain"}),/* @__PURE__ */m(dt,{position:"right",children:"Filtered"})]})})}),/* @__PURE__ */m("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__ */m(G,{size:"sm",variant:"ghost","aria-label":I?"Unmute":"Mute",tooltip:I?"Unmute":"Mute",icon:/* @__PURE__ */m(I?it:nt,{}),onClick:()=>D(e=>!e)}),/* @__PURE__ */m(G,{size:"sm",variant:"ghost","aria-label":
|
|
27
|
+
return m("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__ */m("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"})})}var st=s(()=>import("./CKk0UYyd.js").then(e=>({default:e.ReactCompareSlider})));function lt({open:e,onClose:t,file:r,filters:i,isVideo:n,trimRange:a}){const[s,d]=c(),[u,h]=c(),[g,f]=c(!0),[v,w]=c(!1),[b,y]=c(),[S,C]=c(0),[T,F]=c(!1),[k,_]=c(null),[E,M]=c(null),[U,R]=c(!1),[I,D]=c(!0),[N,P]=c(!0),O=l(null),A=()=>{document.fullscreenElement?document.exitFullscreen():O.current?.requestFullscreen()};o(()=>{const e=()=>F(!!document.fullscreenElement);return document.addEventListener("fullscreenchange",e),()=>document.removeEventListener("fullscreenchange",e)},[]),o(()=>{R(!!k&&!!E)},[k,E]),o(()=>{k&&(k.muted=I)},[k,I]),o(()=>{if(!e||n)return;let t=!1;const o=[];return f(!0),w(!1),(async()=>{const e=await createImageBitmap(r),n=Math.min(1,1600/Math.max(e.width,e.height)),a=Math.round(e.width*n),s=Math.round(e.height*n),l=new OffscreenCanvas(a,s);l.getContext("2d").drawImage(e,0,0,a,s),e.close(),y(a/s);const c=await l.convertToBlob({type:"image/jpeg",quality:.92});if(t)return;const u=URL.createObjectURL(c);o.push(u),d(u);const p=await Ie(c,i,1600,"image/jpeg",.92);if(t)return;const m=URL.createObjectURL(p.blob);o.push(m),h(m)})().catch(()=>{t||w(!0)}).finally(()=>{t||f(!1)}),()=>{t=!0,o.forEach(e=>URL.revokeObjectURL(e))}},[e,n,r,i]),o(()=>{if(!e||!n||!U)return;const t=k,o=E;if(!t||!o)return;let s=!1,l=null,d=null;const c=URL.createObjectURL(r);f(!0),w(!1),C(0);const u=a?.startTime??0,h=u+5,p=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)}),m=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(s)return;C(15);let e=t.videoWidth||640,r=t.videoHeight||360;const n=Math.min(1,720/Math.max(e,r));e=Math.round(e*n),r=Math.round(r*n),o.width=e,o.height=r,y(e/r);const c=o.getContext("2d",{willReadFrequently:!0});if(!c)return f(!1),void w(!0);if(Math.abs(t.currentTime-u)>.05&&(await new Promise(e=>{const r=()=>{t.removeEventListener("seeked",r),e()};t.addEventListener("seeked",r,{once:!0}),t.currentTime=u}),s))return;C(40);const g=new OffscreenCanvas(e,r),v=g.getContext("2d",{willReadFrequently:!0});let b=null;t.muted=!0;try{await t.play()}catch{}if(s)return;for(let i=0;i<6&&!s;i++){if(await p(t),s)return;if(v.drawImage(t,0,0,e,r),!m(v.getImageData(0,0,e,r))){b=await g.convertToBlob({type:"image/jpeg",quality:.85});break}if(t.paused)break}if(s)return;if(!b)return f(!1),void w(!0);C(60);const x=await De(i,b,e,r);if(s)return;if(!x.appliedFilters.length)return f(!1),void w(!0);d=x.transform,C(100),f(!1);const S=a?Math.min(a.endTime,h):Math.min(t.duration||h,h),T=()=>{if(!s&&d){if(c.drawImage(t,0,0,e,r),c.putImageData(d(c.getImageData(0,0,e,r)),0,0),t.currentTime>=S||t.currentTime<u){const e=()=>{t.removeEventListener("seeked",e),s||(l=t.requestVideoFrameCallback(T))};return t.addEventListener("seeked",e,{once:!0}),void(t.currentTime=u)}l=t.requestVideoFrameCallback(T)}};l=t.requestVideoFrameCallback(T)},{once:!0}),t.src=c,t.load(),()=>{s=!0,null!==l&&t.cancelVideoFrameCallback(l),t.pause(),t.removeAttribute("src"),t.load(),URL.revokeObjectURL(c)}},[e,n,r,i,a,U]);const q=T?"100vh":"70vh";/* @__PURE__ */
|
|
28
|
+
return m(H,{open:e,onOpenChange:e=>!e&&t(),children:/* @__PURE__ */m(j,{className:x(T?"max-w-none rounded-none":"max-w-2xl sm:w-2xl"),children:/* @__PURE__ */m("div",{className:"bg-background",children:[/* @__PURE__ */m(L,{className:"flex-row items-center justify-between space-y-0",children:[/* @__PURE__ */m($,{children:"Compare original & filtered"}),/* @__PURE__ */m(G,{size:"sm",variant:"ghost","aria-label":T?"Exit fullscreen":"Fullscreen",tooltip:T?"Exit fullscreen":"Fullscreen",icon:/* @__PURE__ */m(T?ot:at,{}),onClick:A})]}),/* @__PURE__ */m("div",{ref:O,className:x("p-4 pt-0",T&&"bg-background relative flex h-screen w-screen items-center justify-center p-0"),children:[T&&/* @__PURE__ */m(G,{size:"sm",variant:"ghost","aria-label":"Exit fullscreen",tooltip:"Exit fullscreen",className:"absolute top-2 right-2 z-30",icon:/* @__PURE__ */m(ot,{}),onClick:A}),g&&/* @__PURE__ */m("div",{className:"flex h-64 flex-col items-center justify-center gap-2",children:[/* @__PURE__ */m(V,{}),n&&/* @__PURE__ */m("p",{className:"text-muted-foreground text-sm",children:["Generating preview… ",S,"%"]})]}),v&&/* @__PURE__ */m("div",{className:"text-muted-foreground flex h-64 items-center justify-center text-sm",children:"Couldn't generate preview."}),!n&&!g&&!v&&s&&u&&/* @__PURE__ */m(p,{fallback:null,children:/* @__PURE__ */m(st,{style:{width:"100%",maxHeight:q,aspectRatio:b},position:50,onlyHandleDraggable:!0,itemOne:/* @__PURE__ */m("div",{className:"relative size-full",children:[/* @__PURE__ */m("img",{alt:"Original",className:"size-full object-contain",src:s}),/* @__PURE__ */m(dt,{position:"left",children:"Original"})]}),itemTwo:/* @__PURE__ */m("div",{className:"relative size-full",children:[/* @__PURE__ */m("img",{alt:"Filtered",className:"size-full object-contain",src:u}),/* @__PURE__ */m(dt,{position:"right",children:"Filtered"})]})})}),n&&/* @__PURE__ */m("div",{className:"relative",style:{visibility:g||v?"hidden":"visible"},children:[/* @__PURE__ */m(p,{fallback:null,children:/* @__PURE__ */m(st,{style:{width:"100%",maxHeight:q,aspectRatio:b},position:50,onlyHandleDraggable:!0,itemOne:/* @__PURE__ */m("div",{className:"relative size-full",children:[/* @__PURE__ */m("video",{ref:_,playsInline:!0,className:"pointer-events-none size-full object-contain"}),/* @__PURE__ */m(dt,{position:"left",children:"Original"})]}),itemTwo:/* @__PURE__ */m("div",{className:"relative size-full",children:[/* @__PURE__ */m("canvas",{ref:M,className:"size-full object-contain"}),/* @__PURE__ */m(dt,{position:"right",children:"Filtered"})]})})}),/* @__PURE__ */m("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__ */m(G,{size:"sm",variant:"ghost","aria-label":I?"Unmute":"Mute",tooltip:I?"Unmute":"Mute",icon:/* @__PURE__ */m(I?it:nt,{}),onClick:()=>D(e=>!e)}),/* @__PURE__ */m(G,{size:"sm",variant:"ghost","aria-label":N?"Pause":"Play",tooltip:N?"Pause":"Play",icon:/* @__PURE__ */m(N?tt:rt,{}),onClick:()=>{k&&(k.paused?(k.play(),P(!0)):(k.pause(),P(!1)))}})]})]})]})]})})})}function dt({position:e,children:t}){/* @__PURE__ */
|
|
29
29
|
return m("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 ct=Object.defineProperty,ut=(e,t,r)=>((e,t,r)=>t in e?ct(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r),ht={x:0,y:0,width:0,height:0,unit:"px"},pt=(e,t,r)=>Math.min(Math.max(e,t),r),mt=(e,t)=>e===t||e.width===t.width&&e.height===t.height&&e.x===t.x&&e.y===t.y&&e.unit===t.unit;function gt(e,t,r){return"%"===e.unit?{...ht,...e,unit:"%"}:{unit:"%",x:e.x?e.x/t*100:0,y:e.y?e.y/r*100:0,width:e.width?e.width/t*100:0,height:e.height?e.height/r*100:0}}function ft(e,t,r){return e.unit?"px"===e.unit?{...ht,...e,unit:"px"}:{unit:"px",x:e.x?e.x*t/100:0,y:e.y?e.y*r/100:0,width:e.width?e.width*t/100:0,height:e.height?e.height*r/100:0}:{...ht,...e,unit:"px"}}function vt(e,t,r,i,n,o=0,a=0,s=i,l=n){const d={...e};let c=Math.min(o,i),u=Math.min(a,n),h=Math.min(s,i),p=Math.min(l,n);t&&(t>1?(c=a?a*t:c,u=c/t,h=s*t):(u=o?o/t:u,c=u*t,p=l/t)),d.y<0&&(d.height=Math.max(d.height+d.y,u),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,c),d.x=0);const m=i-(d.x+d.width);m<0&&(d.x=Math.min(d.x,i-c),d.width+=m);const g=n-(d.y+d.height);if(g<0&&(d.y=Math.min(d.y,n-u),d.height+=g),d.width<c&&(("sw"===r||"nw"==r)&&(d.x-=c-d.width),d.width=c),d.height<u&&(("nw"===r||"ne"==r)&&(d.y-=u-d.height),d.height=u),d.width>h&&(("sw"===r||"nw"==r)&&(d.x-=h-d.width),d.width=h),d.height>p&&(("nw"===r||"ne"==r)&&(d.y-=p-d.height),d.height=p),t){const e=d.width/d.height;if(e<t){const e=Math.max(d.width/t,u);("nw"===r||"ne"==r)&&(d.y-=e-d.height),d.height=e}else if(e>t){const e=Math.max(d.height*t,c);("sw"===r||"nw"==r)&&(d.x-=e-d.width),d.width=e}}return d}var wt={capture:!0,passive:!1},bt=0,yt=class e extends n{constructor(){super(...arguments),ut(this,"docMoveBound",!1),ut(this,"mouseDownOnCrop",!1),ut(this,"dragStarted",!1),ut(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),ut(this,"componentRef",r()),ut(this,"mediaRef",r()),ut(this,"resizeObserver"),ut(this,"initChangeCalled",!1),ut(this,"instanceId","rc-"+bt++),ut(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),ut(this,"onCropPointerDown",e=>{const{crop:t,disabled:r}=this.props,i=this.getBox();if(!t)return;const n=ft(t,i.width,i.height);if(r)return;e.cancelable&&e.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const o=e.target.dataset.ord,a=!!o;let s=e.clientX,l=e.clientY,d=n.x,c=n.y;if(o){const t=e.clientX-i.x,r=e.clientY-i.y;let a=0,u=0;"ne"===o||"e"==o?(a=t-(n.x+n.width),u=r-n.y,d=n.x,c=n.y+n.height):"se"===o||"s"===o?(a=t-(n.x+n.width),u=r-(n.y+n.height),d=n.x,c=n.y):"sw"===o||"w"==o?(a=t-n.x,u=r-(n.y+n.height),d=n.x+n.width,c=n.y):("nw"===o||"n"==o)&&(a=t-n.x,u=r-n.y,d=n.x+n.width,c=n.y+n.height),s=d+i.x+a,l=c+i.y+u}this.evData={startClientX:s,startClientY:l,startCropX:d,startCropY:c,clientX:e.clientX,clientY:e.clientY,isResize:a,ord:o},this.mouseDownOnCrop=!0,this.setState({cropIsActive:!0})}),ut(this,"onComponentPointerDown",e=>{const{crop:t,disabled:r,locked:i,keepSelection:n,onChange:o}=this.props,a=this.getBox();if(r||i||n&&t)return;e.cancelable&&e.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const s=e.clientX-a.x,l=e.clientY-a.y,d={unit:"px",x:s,y:l,width:0,height:0};this.evData={startClientX:e.clientX,startClientY:e.clientY,startCropX:s,startCropY:l,clientX:e.clientX,clientY:e.clientY,isResize:!0},this.mouseDownOnCrop=!0,o(ft(d,a.width,a.height),gt(d,a.width,a.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),ut(this,"onDocPointerMove",e=>{const{crop:t,disabled:r,onChange:i,onDragStart:n}=this.props,o=this.getBox();if(r||!t||!this.mouseDownOnCrop)return;e.cancelable&&e.preventDefault(),this.dragStarted||(this.dragStarted=!0,n&&n(e));const{evData:a}=this;let s;a.clientX=e.clientX,a.clientY=e.clientY,s=a.isResize?this.resizeCrop():this.dragCrop(),mt(t,s)||i(ft(s,o.width,o.height),gt(s,o.width,o.height))}),ut(this,"onComponentKeyDown",t=>{const{crop:r,disabled:i,onChange:n,onComplete:o}=this.props;if(i)return;const a=t.key;let s=!1;if(!r)return;const l=this.getBox(),d=this.makePixelCrop(l),c=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?e.nudgeStepLarge:t.shiftKey?e.nudgeStepMedium:e.nudgeStep;if("ArrowLeft"===a?(d.x-=c,s=!0):"ArrowRight"===a?(d.x+=c,s=!0):"ArrowUp"===a?(d.y-=c,s=!0):"ArrowDown"===a&&(d.y+=c,s=!0),s){t.cancelable&&t.preventDefault(),d.x=pt(d.x,0,l.width-d.width),d.y=pt(d.y,0,l.height-d.height);const e=ft(d,l.width,l.height),r=gt(d,l.width,l.height);n(e,r),o&&o(e,r)}}),ut(this,"onHandlerKeyDown",(t,r)=>{const{aspect:i=0,crop:n,disabled:o,minWidth:a=0,minHeight:s=0,maxWidth:l,maxHeight:d,onChange:c,onComplete:u}=this.props,h=this.getBox();if(o||!n)return;if("ArrowUp"!==t.key&&"ArrowDown"!==t.key&&"ArrowLeft"!==t.key&&"ArrowRight"!==t.key)return;t.stopPropagation(),t.preventDefault();const p=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?e.nudgeStepLarge:t.shiftKey?e.nudgeStepMedium:e.nudgeStep,m=vt(function(e,t,r,i){const n={...e};return"ArrowLeft"===t?"nw"===i?(n.x-=r,n.y-=r,n.width+=r,n.height+=r):"w"===i?(n.x-=r,n.width+=r):"sw"===i?(n.x-=r,n.width+=r,n.height+=r):"ne"===i?(n.y+=r,n.width-=r,n.height-=r):"e"===i?n.width-=r:"se"===i&&(n.width-=r,n.height-=r):"ArrowRight"===t&&("nw"===i?(n.x+=r,n.y+=r,n.width-=r,n.height-=r):"w"===i?(n.x+=r,n.width-=r):"sw"===i?(n.x+=r,n.width-=r,n.height-=r):"ne"===i?(n.y-=r,n.width+=r,n.height+=r):"e"===i?n.width+=r:"se"===i&&(n.width+=r,n.height+=r)),"ArrowUp"===t?"nw"===i?(n.x-=r,n.y-=r,n.width+=r,n.height+=r):"n"===i?(n.y-=r,n.height+=r):"ne"===i?(n.y-=r,n.width+=r,n.height+=r):"sw"===i?(n.x+=r,n.width-=r,n.height-=r):"s"===i?n.height-=r:"se"===i&&(n.width-=r,n.height-=r):"ArrowDown"===t&&("nw"===i?(n.x+=r,n.y+=r,n.width-=r,n.height-=r):"n"===i?(n.y+=r,n.height-=r):"ne"===i?(n.y+=r,n.width-=r,n.height-=r):"sw"===i?(n.x-=r,n.width+=r,n.height+=r):"s"===i?n.height+=r:"se"===i&&(n.width+=r,n.height+=r)),n}(ft(n,h.width,h.height),t.key,p,r),i,r,h.width,h.height,a,s,l,d);if(!mt(n,m)){const e=gt(m,h.width,h.height);c(m,e),u&&u(m,e)}}),ut(this,"onDocPointerDone",e=>{const{crop:t,disabled:r,onComplete:i,onDragEnd:n}=this.props,o=this.getBox();this.unbindDocMove(),!r&&t&&this.mouseDownOnCrop&&(this.mouseDownOnCrop=!1,this.dragStarted=!1,n&&n(e),i&&i(ft(t,o.width,o.height),gt(t,o.width,o.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),ut(this,"onDragFocus",()=>{var e;null==(e=this.componentRef.current)||e.scrollTo(0,0)})}get document(){return document}getBox(){const e=this.mediaRef.current;if(!e)return{x:0,y:0,width:0,height:0};const{x:t,y:r,width:i,height:n}=e.getBoundingClientRect();return{x:t,y:r,width:i,height:n}}componentDidUpdate(e){const{crop:t,onComplete:r}=this.props;if(r&&!e.crop&&t){const{width:e,height:i}=this.getBox();e&&i&&r(ft(t,e,i),gt(t,e,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,wt),this.document.addEventListener("pointerup",this.onDocPointerDone,wt),this.document.addEventListener("pointercancel",this.onDocPointerDone,wt),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,wt),this.document.removeEventListener("pointerup",this.onDocPointerDone,wt),this.document.removeEventListener("pointercancel",this.onDocPointerDone,wt),this.docMoveBound=!1)}getCropStyle(){const{crop:e}=this.props;if(e)return{top:`${e.y}${e.unit}`,left:`${e.x}${e.unit}`,width:`${e.width}${e.unit}`,height:`${e.height}${e.unit}`}}dragCrop(){const{evData:e}=this,t=this.getBox(),r=this.makePixelCrop(t),i=e.clientX-e.startClientX,n=e.clientY-e.startClientY;return r.x=pt(e.startCropX+i,0,t.width-r.width),r.y=pt(e.startCropY+n,0,t.height-r.height),r}getPointRegion(e,t,r,i){const{evData:n}=this,o=n.clientX-e.x,a=n.clientY-e.y;let s,l;return s=i&&t?"nw"===t||"n"===t||"ne"===t:a<n.startCropY,l=r&&t?"nw"===t||"w"===t||"sw"===t:o<n.startCropX,l?s?"nw":"sw":s?"ne":"se"}resolveMinDimensions(e,t,r=0,i=0){const n=Math.min(r,e.width),o=Math.min(i,e.height);return t&&(n||o)?t>1?n?[n,n/t]:[o*t,o]:o?[o*t,o]:[n,n/t]:[n,o]}resizeCrop(){const{evData:t}=this,{aspect:r=0,maxWidth:i,maxHeight:n}=this.props,o=this.getBox(),[a,s]=this.resolveMinDimensions(o,r,this.props.minWidth,this.props.minHeight);let l=this.makePixelCrop(o);const d=this.getPointRegion(o,t.ord,a,s),c=t.ord||d;let u=t.clientX-t.startClientX,h=t.clientY-t.startClientY;(a&&"nw"===c||"w"===c||"sw"===c)&&(u=Math.min(u,-a)),(s&&"nw"===c||"n"===c||"ne"===c)&&(h=Math.min(h,-s));const p={unit:"px",x:0,y:0,width:0,height:0};"ne"===d?(p.x=t.startCropX,p.width=u,r?(p.height=p.width/r,p.y=t.startCropY-p.height):(p.height=Math.abs(h),p.y=t.startCropY-p.height)):"se"===d?(p.x=t.startCropX,p.y=t.startCropY,p.width=u,p.height=r?p.width/r:h):"sw"===d?(p.x=t.startCropX+u,p.y=t.startCropY,p.width=Math.abs(u),p.height=r?p.width/r:h):"nw"===d&&(p.x=t.startCropX+u,p.width=Math.abs(u),r?(p.height=p.width/r,p.y=t.startCropY-p.height):(p.height=Math.abs(h),p.y=t.startCropY+h));const m=vt(p,r,d,o.width,o.height,a,s,i,n);return r||e.xyOrds.indexOf(c)>-1?l=m:e.xOrds.indexOf(c)>-1?(l.x=m.x,l.width=m.width):e.yOrds.indexOf(c)>-1&&(l.y=m.y,l.height=m.height),l.x=pt(l.x,0,o.width-l.width),l.y=pt(l.y,0,o.height-l.height),l}renderCropSelection(){const{ariaLabels:t=e.defaultProps.ariaLabels,disabled:r,locked:i,renderSelectionAddon:n,ruleOfThirds:o,crop:s}=this.props,l=this.getCropStyle();if(s)/* @__PURE__ */return a.createElement("div",{style:l,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!r&&!i&&/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-handle ord-nw","data-ord":"nw",tabIndex:0,"aria-label":t.nwDragHandle,onKeyDown:e=>this.onHandlerKeyDown(e,"nw"),role:"button"}),/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-handle ord-n","data-ord":"n",tabIndex:0,"aria-label":t.nDragHandle,onKeyDown:e=>this.onHandlerKeyDown(e,"n"),role:"button"}),/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-handle ord-ne","data-ord":"ne",tabIndex:0,"aria-label":t.neDragHandle,onKeyDown:e=>this.onHandlerKeyDown(e,"ne"),role:"button"}),/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-handle ord-e","data-ord":"e",tabIndex:0,"aria-label":t.eDragHandle,onKeyDown:e=>this.onHandlerKeyDown(e,"e"),role:"button"}),/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-handle ord-se","data-ord":"se",tabIndex:0,"aria-label":t.seDragHandle,onKeyDown:e=>this.onHandlerKeyDown(e,"se"),role:"button"}),/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-handle ord-s","data-ord":"s",tabIndex:0,"aria-label":t.sDragHandle,onKeyDown:e=>this.onHandlerKeyDown(e,"s"),role:"button"}),/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-handle ord-sw","data-ord":"sw",tabIndex:0,"aria-label":t.swDragHandle,onKeyDown:e=>this.onHandlerKeyDown(e,"sw"),role:"button"}),/* @__PURE__ */a.createElement("div",{className:"ReactCrop__drag-handle ord-w","data-ord":"w",tabIndex:0,"aria-label":t.wDragHandle,onKeyDown:e=>this.onHandlerKeyDown(e,"w"),role:"button"})),n&&/* @__PURE__ */a.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:e=>e.stopPropagation()},n(this.state)),o&&/* @__PURE__ */a.createElement(a.Fragment,null,/* @__PURE__ */a.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),/* @__PURE__ */a.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(e){return ft({...ht,...this.props.crop||{}},e.width,e.height)}render(){const{aspect:e,children:t,circularCrop:r,className:i,crop:n,disabled:o,locked:s,style:l,ruleOfThirds:d}=this.props,{cropIsActive:c,newCropIsBeingDrawn:u}=this.state,h=n?this.renderCropSelection():null,p=((...e)=>e.filter(e=>e&&"string"==typeof e).join(" "))("ReactCrop",i,c&&"ReactCrop--active",o&&"ReactCrop--disabled",s&&"ReactCrop--locked",u&&"ReactCrop--new-crop",n&&e&&"ReactCrop--fixed-aspect",n&&r&&"ReactCrop--circular-crop",n&&d&&"ReactCrop--rule-of-thirds",!this.dragStarted&&n&&!n.width&&!n.height&&"ReactCrop--invisible-crop",r&&"ReactCrop--no-animate");/* @__PURE__ */
|
|
30
30
|
return a.createElement("div",{ref:this.componentRef,className:p,style:l},/* @__PURE__ */a.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},t),n?/* @__PURE__ */a.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},/* @__PURE__ */a.createElement("defs",null,/* @__PURE__ */a.createElement("mask",{id:`hole-${this.instanceId}`},/* @__PURE__ */a.createElement("rect",{width:"100%",height:"100%",fill:"white"}),r?/* @__PURE__ */a.createElement("ellipse",{cx:`${n.x+n.width/2}${n.unit}`,cy:`${n.y+n.height/2}${n.unit}`,rx:`${n.width/2}${n.unit}`,ry:`${n.height/2}${n.unit}`,fill:"black"}):/* @__PURE__ */a.createElement("rect",{x:`${n.x}${n.unit}`,y:`${n.y}${n.unit}`,width:`${n.width}${n.unit}`,height:`${n.height}${n.unit}`,fill:"black"}))),/* @__PURE__ */a.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,h)}};ut(yt,"xOrds",["e","w"]),ut(yt,"yOrds",["n","s"]),ut(yt,"xyOrds",["nw","ne","se","sw"]),ut(yt,"nudgeStep",1),ut(yt,"nudgeStepMedium",10),ut(yt,"nudgeStepLarge",100),ut(yt,"defaultProps",{ariaLabels:{cropArea:"Use the arrow keys to move the crop selection area",nwDragHandle:"Use the arrow keys to move the north west drag handle to change the crop selection area",nDragHandle:"Use the up and down arrow keys to move the north drag handle to change the crop selection area",neDragHandle:"Use the arrow keys to move the north east drag handle to change the crop selection area",eDragHandle:"Use the up and down arrow keys to move the east drag handle to change the crop selection area",seDragHandle:"Use the arrow keys to move the south east drag handle to change the crop selection area",sDragHandle:"Use the up and down arrow keys to move the south drag handle to change the crop selection area",swDragHandle:"Use the arrow keys to move the south west drag handle to change the crop selection area",wDragHandle:"Use the up and down arrow keys to move the west drag handle to change the crop selection area"}});var xt=yt,St=({open:e,onClose:t,imageSrc:r,aspectRatio:i,onCropComplete:n,title:o})=>{const a=l(null),[s,d]=c(),[u,h]=c(),[p,f]=c(!1),v=g(()=>{d(void 0),h(void 0),t()},[t]);/* @__PURE__ */
|
|
31
31
|
return m(H,{open:e,onOpenChange:v,children:/* @__PURE__ */m(j,{className:"flex h-[90vh] min-w-xl flex-col overflow-hidden p-0",children:[
|
|
32
32
|
/* @__PURE__ */m("div",{className:"bg-background shrink-0",children:/* @__PURE__ */m(L,{children:[/* @__PURE__ */m($,{children:o||"Crop Image"}),/* @__PURE__ */m(B,{className:"sr-only",children:"Drag the handles to select the crop area."})]})}),
|
|
33
|
-
/* @__PURE__ */m("div",{className:"flex max-h-[50vh] min-h-0 flex-1 items-center justify-center overflow-hidden bg-black",children:/* @__PURE__ */m(xt,{crop:s,aspect:i,onChange:e=>d(e),onComplete:e=>h(e),keepSelection:!0,minWidth:20,minHeight:20,children:/* @__PURE__ */m("img",{ref:a,src:r,alt:"Crop preview",onLoad:()=>{const e=a.current;if(!e)return;const{width:t,height:r}=e;d(function(e,t,r){const i=ft(e,t,r);return i.x=(t-i.width)/2,i.y=(r-i.height)/2,"%"===e.unit?gt(i,t,r):i}(function(e,t,r,i){const n=ft(e,r,i);return e.width&&(n.height=n.width/t),e.height&&(n.width=n.height*t),n.y+n.height>i&&(n.height=i-n.y,n.width=n.height*t),n.x+n.width>r&&(n.width=r-n.x,n.height=n.width/t),"%"===e.unit?gt(n,r,i):n}({unit:"%",width:85},i??t/r,t,r),t,r))},
|
|
34
|
-
/* @__PURE__ */m("div",{className:"border-border bg-background shrink-0 border-t p-4",children:/* @__PURE__ */m(z,{children:[/* @__PURE__ */m(I,{variant:"outlined",onClick:v,disabled:p,children:"Cancel"}),/* @__PURE__ */m(I,{onClick:async()=>{if(!u||!a.current)return;const e=a.current,t=e.naturalWidth/e.width,r=e.naturalHeight/e.height,i={unit:"px",x:Math.round(u.x*t),y:Math.round(u.y*r),width:Math.round(u.width*t),height:Math.round(u.height*r)};try{f(!0),n(await function(e,t){const r=document.createElement("canvas");r.width=t.width,r.height=t.height;const i=r.getContext("2d");return i?(i.drawImage(e,t.x,t.y,t.width,t.height,0,0,t.width,t.height),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"))}(e,i)),v()}catch(o){console.error(o)}finally{f(!1)}},loading:p,disabled:p||!u?.width||!u?.height,children:"Crop & Save"})]})})]})})},Ct=({open:e,onClose:t,videoFile:r,onTrimComplete:i,title:n="Select 60 Second Clip"})=>{const a=l(null),s=l(null),[d,u]=c(0),[h,p]=c(0),[f,v]=c(60),[w,b]=c(0),[y,x]=c(!1),[S,C]=c(!1),[T,F]=c(null),[k,_]=c(null),[E,M]=c(0),[U,R]=c({start:0,end:0});o(()=>{if(r&&e){const e=URL.createObjectURL(r);return F(e),()=>URL.revokeObjectURL(e)}},[r,e]);const D=g(e=>{if(!s.current||0===d)return 0;const t=s.current.getBoundingClientRect();return Math.max(0,Math.min(1,(e-t.left)/t.width))*d},[d]),
|
|
33
|
+
/* @__PURE__ */m("div",{className:"flex max-h-[50vh] min-h-0 flex-1 items-center justify-center overflow-hidden bg-black",children:/* @__PURE__ */m(xt,{crop:s,aspect:i,onChange:e=>d(e),onComplete:e=>h(e),keepSelection:!0,minWidth:20,minHeight:20,children:/* @__PURE__ */m("img",{ref:a,src:r,alt:"Crop preview",onLoad:()=>{const e=a.current;if(!e)return;const{width:t,height:r}=e;d(function(e,t,r){const i=ft(e,t,r);return i.x=(t-i.width)/2,i.y=(r-i.height)/2,"%"===e.unit?gt(i,t,r):i}(function(e,t,r,i){const n=ft(e,r,i);return e.width&&(n.height=n.width/t),e.height&&(n.width=n.height*t),n.y+n.height>i&&(n.height=i-n.y,n.width=n.height*t),n.x+n.width>r&&(n.width=r-n.x,n.height=n.width/t),"%"===e.unit?gt(n,r,i):n}({unit:"%",width:85},i??t/r,t,r),t,r))},className:"block h-auto w-auto max-w-full object-contain"})})}),
|
|
34
|
+
/* @__PURE__ */m("div",{className:"border-border bg-background shrink-0 border-t p-4",children:/* @__PURE__ */m(z,{children:[/* @__PURE__ */m(I,{variant:"outlined",onClick:v,disabled:p,children:"Cancel"}),/* @__PURE__ */m(I,{onClick:async()=>{if(!u||!a.current)return;const e=a.current,t=e.naturalWidth/e.width,r=e.naturalHeight/e.height,i={unit:"px",x:Math.round(u.x*t),y:Math.round(u.y*r),width:Math.round(u.width*t),height:Math.round(u.height*r)};try{f(!0),n(await function(e,t){const r=document.createElement("canvas");r.width=t.width,r.height=t.height;const i=r.getContext("2d");return i?(i.drawImage(e,t.x,t.y,t.width,t.height,0,0,t.width,t.height),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"))}(e,i)),v()}catch(o){console.error(o)}finally{f(!1)}},loading:p,disabled:p||!u?.width||!u?.height,children:"Crop & Save"})]})})]})})},Ct=({open:e,onClose:t,videoFile:r,onTrimComplete:i,title:n="Select 60 Second Clip"})=>{const a=l(null),s=l(null),[d,u]=c(0),[h,p]=c(0),[f,v]=c(60),[w,b]=c(0),[y,x]=c(!1),[S,C]=c(!1),[T,F]=c(null),[k,_]=c(null),[E,M]=c(0),[U,R]=c({start:0,end:0});o(()=>{if(r&&e){const e=URL.createObjectURL(r);return F(e),()=>URL.revokeObjectURL(e)}},[r,e]);const D=g(e=>{if(!s.current||0===d)return 0;const t=s.current.getBoundingClientRect();return Math.max(0,Math.min(1,(e-t.left)/t.width))*d},[d]),N=g(e=>0===d?0:e/d*100,[d]),P=(e,t)=>{e.preventDefault?.(),e.stopPropagation?.(),_(t),M(e.clientX||0),R({start:h,end:f})},O=(e,t)=>{e.stopPropagation?.();const r=e.touches?.[0];_(t),M(r?.clientX||0),R({start:h,end:f})};o(()=>{if(!k||!s.current)return;const e=e=>{const t=s.current.getBoundingClientRect(),r=(e-E)/t.width*d;if("start"===k){let e=Math.max(0,U.start+r);e=Math.min(e,f-1),f-e>60&&(e=f-60),p(e),a.current&&(a.current.currentTime=e)}else if("end"===k){let e=Math.min(d,U.end+r);e=Math.max(e,h+1),e-h>60&&(e=h+60),v(e)}else if("range"===k){const e=U.end-U.start;let t=U.start+r,i=U.end+r;t<0&&(t=0,i=e),i>d&&(i=d,t=d-e),p(t),v(i),a.current&&(a.current.currentTime=t)}},t=t=>e(t.clientX),r=t=>e(t.touches[0].clientX),i=()=>_(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)}},[k,E,U,d,h,f]);const A=()=>{a.current&&(y?a.current.pause():((w<h||w>=f)&&(a.current.currentTime=h),a.current.play()),x(!y))},q=e=>`${Math.floor(e/60)}:${Math.floor(e%60).toString().padStart(2,"0")}`,W=()=>{p(0),v(60),b(0),x(!1),_(null),a.current&&a.current.pause(),t()},V=f-h;/* @__PURE__ */
|
|
35
35
|
return m(H,{open:e,onOpenChange:W,children:/* @__PURE__ */m(j,{className:"max-h-[90vh] max-w-3xl overflow-y-auto p-0",children:[
|
|
36
36
|
/* @__PURE__ */m("div",{className:"bg-background sticky top-0 z-10",children:/* @__PURE__ */m(L,{children:[/* @__PURE__ */m($,{children:n}),/* @__PURE__ */m(B,{className:"hidden",children:"Review the video preview and choose the start and end times for the clip you want to keep."})]})}),
|
|
37
37
|
/* @__PURE__ */m("div",{className:"space-y-4 p-4",children:[
|
|
@@ -40,47 +40,47 @@ return m(H,{open:e,onOpenChange:W,children:/* @__PURE__ */m(j,{className:"max-h-
|
|
|
40
40
|
/* @__PURE__ */m("div",{className:"absolute bottom-2 left-2 rounded bg-black/70 px-2 py-1 text-sm text-white",children:q(w)})]}),
|
|
41
41
|
/* @__PURE__ */m("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[/* @__PURE__ */m("div",{className:"flex items-center gap-2",children:[/* @__PURE__ */m("span",{className:"bg-primary/20 text-primary rounded-full px-3 py-1 text-sm font-medium",children:["Start: ",q(h)]}),/* @__PURE__ */m("span",{className:"bg-primary/20 text-primary rounded-full px-3 py-1 text-sm font-medium",children:["End: ",q(f)]})]}),/* @__PURE__ */m("span",{className:"rounded-full px-3 py-1 text-sm font-medium "+(V<=60?"bg-green-500/20 text-green-600":"bg-red-500/20 text-red-600"),children:[q(V)," / ",q(60)]})]}),
|
|
42
42
|
/* @__PURE__ */m("div",{className:"space-y-1",children:[
|
|
43
|
-
/* @__PURE__ */m("div",{className:"relative h-4 select-none",children:(()=>{if(0===d)return[];let e;e=d<=30?10:d<=60?15:d<=120?30:d<=300?60:120;const t=[];for(let r=0;r<=d;r+=e)t.push(r);return d-t[t.length-1]>.3*e&&t.push(Math.floor(d)),t})().map(e=>/* @__PURE__ */m("span",{className:"text-muted-foreground absolute -translate-x-1/2 text-xs",style:{left:`${
|
|
43
|
+
/* @__PURE__ */m("div",{className:"relative h-4 select-none",children:(()=>{if(0===d)return[];let e;e=d<=30?10:d<=60?15:d<=120?30:d<=300?60:120;const t=[];for(let r=0;r<=d;r+=e)t.push(r);return d-t[t.length-1]>.3*e&&t.push(Math.floor(d)),t})().map(e=>/* @__PURE__ */m("span",{className:"text-muted-foreground absolute -translate-x-1/2 text-xs",style:{left:`${N(e)}%`},children:q(e)},e))}),
|
|
44
44
|
/* @__PURE__ */m("div",{ref:s,className:"relative h-16 cursor-pointer rounded-lg bg-gray-200 select-none dark:bg-gray-800",onClick:e=>(e=>{if(k)return;const t=D(e.clientX);t>=h&&t<=f&&a.current&&(a.current.currentTime=t,b(t))})(e),children:[
|
|
45
|
-
/* @__PURE__ */m("div",{className:"absolute inset-y-0 left-0 bg-black/50",style:{width:`${
|
|
46
|
-
/* @__PURE__ */m("div",{className:"absolute inset-y-0 right-0 bg-black/50",style:{width:100-
|
|
47
|
-
/* @__PURE__ */m("div",{className:"bg-primary/30 border-primary absolute inset-y-0 cursor-grab border-y-2 active:cursor-grabbing",style:{left:`${
|
|
48
|
-
/* @__PURE__ */m("div",{className:"border-primary bg-primary absolute inset-y-0 z-10 w-3 cursor-ew-resize rounded-l-md border-2 transition-transform hover:scale-x-125",style:{left:`calc(${
|
|
49
|
-
/* @__PURE__ */m("div",{className:"border-primary bg-primary absolute inset-y-0 z-10 w-3 cursor-ew-resize rounded-r-md border-2 transition-transform hover:scale-x-125",style:{left:`calc(${
|
|
50
|
-
/* @__PURE__ */m("div",{className:"absolute inset-y-0 z-20 w-0.5 bg-white shadow-lg",style:{left:`${
|
|
45
|
+
/* @__PURE__ */m("div",{className:"absolute inset-y-0 left-0 bg-black/50",style:{width:`${N(h)}%`}}),
|
|
46
|
+
/* @__PURE__ */m("div",{className:"absolute inset-y-0 right-0 bg-black/50",style:{width:100-N(f)+"%"}}),
|
|
47
|
+
/* @__PURE__ */m("div",{className:"bg-primary/30 border-primary absolute inset-y-0 cursor-grab border-y-2 active:cursor-grabbing",style:{left:`${N(h)}%`,width:`${N(f-h)}%`},onMouseDown:e=>P(e,"range"),onTouchStart:e=>O(e,"range")}),
|
|
48
|
+
/* @__PURE__ */m("div",{className:"border-primary bg-primary absolute inset-y-0 z-10 w-3 cursor-ew-resize rounded-l-md border-2 transition-transform hover:scale-x-125",style:{left:`calc(${N(h)}% - 6px)`},onMouseDown:e=>P(e,"start"),onTouchStart:e=>O(e,"start"),children:/* @__PURE__ */m("div",{className:"absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-white/50"})}),
|
|
49
|
+
/* @__PURE__ */m("div",{className:"border-primary bg-primary absolute inset-y-0 z-10 w-3 cursor-ew-resize rounded-r-md border-2 transition-transform hover:scale-x-125",style:{left:`calc(${N(f)}% - 6px)`},onMouseDown:e=>P(e,"end"),onTouchStart:e=>O(e,"end"),children:/* @__PURE__ */m("div",{className:"absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-white/50"})}),
|
|
50
|
+
/* @__PURE__ */m("div",{className:"absolute inset-y-0 z-20 w-0.5 bg-white shadow-lg",style:{left:`${N(w)}%`},children:/* @__PURE__ */m("div",{className:"absolute -top-1 left-1/2 h-3 w-3 -translate-x-1/2 rotate-45 bg-white"})}),
|
|
51
51
|
/* @__PURE__ */m("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(d))}).map((e,t)=>/* @__PURE__ */m("div",{className:"w-px bg-gray-400/30",style:{height:t%5==0?"100%":"50%"}},t))})]}),
|
|
52
52
|
/* @__PURE__ */m("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"})]}),
|
|
53
53
|
/* @__PURE__ */m("div",{className:"flex items-center justify-center gap-2",children:[
|
|
54
54
|
/* @__PURE__ */m(I,{variant:"outlined",size:"sm",onClick:()=>{a.current&&(a.current.currentTime=h,b(h))},children:/* @__PURE__ */m("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 24 24",children:/* @__PURE__ */m("path",{fill:"currentColor",d:"M6 6h2v12H6zm3.5 6l8.5 6V6z"})})}),
|
|
55
55
|
/* @__PURE__ */m(I,{variant:"outlined",onClick:A,children:/* @__PURE__ */m("svg",y?{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6",viewBox:"0 0 24 24",children:/* @__PURE__ */m("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__ */m("path",{fill:"currentColor",d:"M8 5v14l11-7z"})})}),
|
|
56
56
|
/* @__PURE__ */m(I,{variant:"outlined",size:"sm",onClick:()=>{a.current&&(a.current.currentTime=f,b(f))},children:/* @__PURE__ */m("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 24 24",children:/* @__PURE__ */m("path",{fill:"currentColor",d:"m5 18l8.5-6L5 6zm11 0V6h2v12z"})})})]})]}),
|
|
57
|
-
/* @__PURE__ */m("div",{className:"bg-background border-border sticky bottom-0 border-t",children:/* @__PURE__ */m(z,{children:[/* @__PURE__ */m(I,{variant:"outlined",onClick:W,disabled:S,children:"Cancel"}),/* @__PURE__ */m(I,{onClick:async()=>{C(!0);try{i({startTime:h,endTime:f,duration:f-h}),W()}catch(e){console.error("Error trimming video:",e)}finally{C(!1)}},loading:S,disabled:S||V>60,children:"Confirm Selection"})]})})]})})},Tt=/* @__PURE__ */new Map;function Ft(e,t,r,i){return`${e}:${JSON.stringify(t)}:${r}x${i}`}function kt(e){const t=Tt.get(e);return t&&(Tt.delete(e),Tt.set(e,t)),t}function _t(e,t){const r=Math.min(1,360/e);return{w:Math.round(e*r),h:Math.round(t*r)}}function Et(e,t){if(Tt.delete(e),Tt.set(e,t),Tt.size>3){const e=Tt.keys().next().value;void 0!==e&&Tt.delete(e)}}var Mt={image:"25 MB",video:"250 MB"},Ut=u(function({uid:e,file:t,onRemove:r,disabled:i,adaRequired:n,onRetry:a}){const s=ze(t),d=!s&&function(e){return e.type.startsWith("image/")||Le.test(e.name)}(t),u=Ve(),h=We(t=>t.captions[e]),p=We(t=>t.oversizedUids[e]),f=We(t=>t.uploadStates[e]),v=We(t=>t.trimRanges[e]),w=We(t=>t.originalFiles[e])??t,b=We(e=>e.videoMuted),y=We(e=>e.setVideoMuted),S=We(e=>e.activeFilters),C=We(e=>e.showFilterChoice),T=We(e=>e.skipUploadFilters),F=We(t=>t.perFileFilterSkipped[e]),k=We(t=>t.filteredThumbs[e]),_=!!f,E="success"===f?.status,M="error"===f?.status,U=C&&S.length>0&&!T&&!F,[R,I]=c(!1),[D,
|
|
57
|
+
/* @__PURE__ */m("div",{className:"bg-background border-border sticky bottom-0 border-t",children:/* @__PURE__ */m(z,{children:[/* @__PURE__ */m(I,{variant:"outlined",onClick:W,disabled:S,children:"Cancel"}),/* @__PURE__ */m(I,{onClick:async()=>{C(!0);try{i({startTime:h,endTime:f,duration:f-h}),W()}catch(e){console.error("Error trimming video:",e)}finally{C(!1)}},loading:S,disabled:S||V>60,children:"Confirm Selection"})]})})]})})},Tt=/* @__PURE__ */new Map;function Ft(e,t,r,i){return`${e}:${JSON.stringify(t)}:${r}x${i}`}function kt(e){const t=Tt.get(e);return t&&(Tt.delete(e),Tt.set(e,t)),t}function _t(e,t){const r=Math.min(1,360/e);return{w:Math.round(e*r),h:Math.round(t*r)}}function Et(e,t){if(Tt.delete(e),Tt.set(e,t),Tt.size>3){const e=Tt.keys().next().value;void 0!==e&&Tt.delete(e)}}var Mt={image:"25 MB",video:"250 MB"},Ut=u(function({uid:e,file:t,onRemove:r,disabled:i,adaRequired:n,onRetry:a}){const s=ze(t),d=!s&&function(e){return e.type.startsWith("image/")||Le.test(e.name)}(t),u=Ve(),h=We(t=>t.captions[e]),p=We(t=>t.oversizedUids[e]),f=We(t=>t.uploadStates[e]),v=We(t=>t.trimRanges[e]),w=We(t=>t.originalFiles[e])??t,b=We(e=>e.videoMuted),y=We(e=>e.setVideoMuted),S=We(e=>e.activeFilters),C=We(e=>e.showFilterChoice),T=We(e=>e.skipUploadFilters),F=We(t=>t.perFileFilterSkipped[e]),k=We(t=>t.filteredThumbs[e]),_=!!f,E="success"===f?.status,M="error"===f?.status,U=C&&S.length>0&&!T&&!F,[R,I]=c(!1),[D,P]=c(!1),[O,A]=c(!1),{ref:L,inView:z}=function({rootMargin:e,triggerOnce:t}={}){const r=l(null),[i,n]=c(!1);return o(()=>{const i=r.current;if(!i)return;const o=new IntersectionObserver(e=>{for(const r of e)r.isIntersecting?(n(!0),t&&o.disconnect()):t||n(!1)},{rootMargin:e});return o.observe(i),()=>o.disconnect()},[e,t]),{ref:r,inView:i}}({rootMargin:"200px",triggerOnce:!0}),[j,$]=c();o(()=>{if(!d||!z)return;const e=URL.createObjectURL(t);return $(e),()=>URL.revokeObjectURL(e)},[t,d,z]);const[B,H]=c();o(()=>{if(!d||!R)return;const e=URL.createObjectURL(w);return H(e),()=>{URL.revokeObjectURL(e),H(void 0)}},[w,d,R]);const X=l(null),K=l(null),Q=l(null),J=l(0),Z=l(null),[ee,te]=c(!1),[re,ie]=c(!1),[ne,oe]=c(null),ae=g(()=>{const e=X.current;if(!e||Q.current)return;const r=URL.createObjectURL(t);Q.current=r,e.src=r,e.load()},[t]),se=g(()=>{const e=X.current;e&&(e.removeAttribute("src"),e.load()),Q.current&&(URL.revokeObjectURL(Q.current),Q.current=null)},[]),le=g(()=>{const e=X.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),oe(r.toDataURL("image/jpeg",.85)))},[]),ue=g(()=>{const t=X.current,r=K.current;if(!t||!r||!t.videoWidth)return!1;const{w:i,h:n}=_t(t.videoWidth,t.videoHeight),o=kt(Ft(e,S,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,S]),he=g(()=>{Z.current&&(clearTimeout(Z.current),Z.current=null)},[]),me=g(()=>{const t=X.current;t&&(J.current=t.currentTime),le(),U&&ie(ue()),te(!1),function(e){Xe===e&&(Xe=null)}(e),he(),Z.current=setTimeout(()=>{se(),Z.current=null},200)},[e,le,ue,U,se,he]),ge=g(()=>{const t=X.current;if(!t)return;if(ee)return void t.pause();!function(e){Xe&&Xe!==e&&Ge.get(Xe)?.(),Xe=e}(e),he(),ae();const r=J.current||v?.startTime||0,i=()=>{t.currentTime=r,t.play().catch(()=>{})};t.readyState>=1?i():t.addEventListener("loadedmetadata",i,{once:!0})},[ee,ae,v,e,he]);return o(()=>{if(!s)return;const t=function(e){return Ge.set(e,()=>X.current?.pause()),()=>{Ge.delete(e),Xe===e&&(Xe=null)}}(e);return()=>{t(),he(),se()}},[s,e,se,he]),o(()=>{D&&X.current?.pause()},[D]),o(()=>{_&&X.current?.pause()},[_]),o(()=>{J.current=0},[v]),o(()=>{ie(!1)},[U,S,e]),o(()=>{X.current&&(X.current.muted=b)},[b]),o(()=>{if(!s||!z)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 de(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;if(d.drawImage(i,0,0,o.width,o.height),e)return;oe(o.toDataURL("image/jpeg",.85))}catch{}finally{n()}}).catch(()=>{}),()=>{e=!0,n()}},[s,z,t]),o(()=>{if(!d||!z||!U||k)return;let r=!1;return ce(()=>async function(e,t){const r=Date.now(),i=t.filter(e=>e.enabled);let n,o;const a=await createImageBitmap(e,{resizeWidth:Ne});if(n=a.width,o=a.height,o>Ne){const e=Ne/o;n=Math.round(n*e),o=Ne}const s=new OffscreenCanvas(n,o);s.getContext("2d").drawImage(a,0,0,n,o),a.close();const l=await s.convertToBlob({type:"image/jpeg",quality:.92}),d=await Pe(l);if(!i.length)return{original:d,processed:d,appliedFilters:[],failedFilters:[],totalExecutionTime:Date.now()-r};let c=d;const u=[],h=[];try{const e=await Ie(l,i,Ne,"image/jpeg",.92);e.appliedFilters.length>0&&(c=await Pe(e.blob),u.push(...e.appliedFilters));for(const t of i)e.appliedFilters.includes(t.id)||h.push({id:t.id,error:"Filter not applied"})}catch(p){for(const e of i)h.push({id:e.id,error:p instanceof Error?p.message:"Unknown error"});pe(p instanceof Error?p:/* @__PURE__ */new Error("Filter preview failed"),{component:"client-filter-engine",tags:["uploadv2","filter-preview","webgl"],extra:{filterCount:i.length,failedFilters:h.map(e=>e.id)}})}return{original:d,processed:c,appliedFilters:u,failedFilters:h,totalExecutionTime:Date.now()-r}}(t,S)).then(t=>{!r&&t.appliedFilters.length&&u.getState().setFilteredThumb(e,t.processed)}).catch(()=>{}),()=>{r=!0}},[d,z,U,k,t,S,u,e]),o(()=>{if(!s||!ne||!U||k)return;let t=!1;return ce(async()=>{const t=await fetch(ne).then(e=>e.blob()),r=await createImageBitmap(t),{w:i,h:n}=_t(r.width,r.height),o=Ft(e,S,i,n);let a=kt(o);if(a||(a=await De(S,t,i,n),a.appliedFilters.length&&Et(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||u.getState().setFilteredThumb(e,i.result)},i.readAsDataURL(r)}).catch(()=>{}),()=>{t=!0}},[s,ne,U,k,S,u,e]),o(()=>{if(!(s&&ee&&U&&ne))return;const t=X.current,r=K.current;if(!t||!r)return;let i=!1,n=null;return(async()=>{if(!t.videoWidth)return;const{w:o,h:a}=_t(t.videoWidth,t.videoHeight);r.width=o,r.height=a;const s=r.getContext("2d");if(!s)return;const l=Ft(e,S,o,a);let d=kt(l);if(!d){const e=await fetch(ne).then(e=>e.blob());if(i)return;if(d=await De(S,e,o,a),i||!d.appliedFilters.length)return;Et(l,d)}const c=d.transform,u=v?.startTime??0,h=Number.isFinite(t.duration)?t.duration:1/0,p=Math.min(v?.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,ie(!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)}},[s,ee,U,ne,S,v,e]),/* @__PURE__ */m("div",{className:"group relative",children:[
|
|
58
58
|
/* @__PURE__ */m("div",{ref:L,className:x("bg-muted relative h-48 overflow-hidden rounded-xl sm:h-72",p&&"border-destructive border-2"),children:[d&&j&&/* @__PURE__ */m("img",{src:U&&k?k:j,alt:t.name,loading:"lazy",decoding:"async",className:"size-full object-contain"}),d&&C&&S.length>0&&!T&&/* @__PURE__ */m(Rt,{applied:U&&!!k}),s&&/* @__PURE__ */m("div",{className:"relative size-full",children:[ne&&/* @__PURE__ */m("img",{src:U&&k?k:ne,alt:"",className:x("absolute inset-0 size-full object-contain",ee&&!U||U&&re?"opacity-0":"opacity-100")}),(!ee||U)&&C&&S.length>0&&!T&&/* @__PURE__ */m(Rt,{applied:U&&!!k}),
|
|
59
59
|
/* @__PURE__ */m("video",{ref:X,muted:b,playsInline:!0,loop:!v,preload:"none",onLoadedMetadata:e=>{v&&(e.currentTarget.currentTime=v.startTime)},onTimeUpdate:e=>{if(!v)return;const t=e.currentTarget;t.currentTime>=v.endTime&&(t.currentTime=v.startTime)},onPlaying:()=>te(!0),onPause:me,className:x("size-full object-contain",ee&&!U?"opacity-100":"opacity-0")}),U&&/* @__PURE__ */m("canvas",{ref:K,className:x("pointer-events-none absolute inset-0 size-full object-contain",re?"opacity-100":"opacity-0")}),!_&&/* @__PURE__ */m("button",{type:"button","aria-label":ee?"Pause":"Play",onClick:ge,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__ */m(ee?tt:rt,{className:"text-foreground size-8"})}),!_&&/* @__PURE__ */m("button",{type:"button","aria-label":b?"Unmute videos":"Mute videos",onClick:()=>y(!b),className:"bg-background/60 absolute bottom-2 left-2 z-10 rounded-full p-2 backdrop-blur-sm",children:/* @__PURE__ */m(b?it:nt,{className:"text-foreground size-5"})}),v&&!_&&/* @__PURE__ */m("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: ",(fe=v.endTime-v.startTime,`${Math.floor(fe/60)}:${Math.floor(fe%60).toString().padStart(2,"0")}`)]})]}),!d&&!s&&/* @__PURE__ */m("div",{className:"flex h-full w-full items-center justify-center",children:/* @__PURE__ */m(et,{className:"text-muted-foreground size-12"})}),p&&/* @__PURE__ */m("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:[
|
|
60
60
|
/* @__PURE__ */m(W,{className:"size-4"}),"Exceeds ",Mt[p]," limit"]}),_&&!E&&!M&&/* @__PURE__ */m("div",{className:"bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-3 backdrop-blur-sm",children:[f.bytesTotal>0&&/* @__PURE__ */m("div",{className:"bg-primary/20 absolute bottom-0 left-0 h-full transition-all duration-300",style:{width:`${Math.round(f.bytesUploaded/f.bytesTotal*100)}%`}}),
|
|
61
61
|
/* @__PURE__ */m("div",{className:"bg-primary/10 flex size-12 items-center justify-center rounded-full",children:/* @__PURE__ */m(V,{className:"size-6"})}),
|
|
62
62
|
/* @__PURE__ */m("div",{className:"relative z-10 rounded-full bg-white/80 px-3 py-1 backdrop-blur-sm dark:bg-black/40",children:/* @__PURE__ */m("span",{className:"text-muted-foreground text-sm font-medium",children:"creating"!==f.status&&"queued"!==f.status&&f.bytesTotal>0?`Uploading ${Math.round(f.bytesUploaded/f.bytesTotal*100)}%`:"Uploading..."})})]}),E&&/* @__PURE__ */m("div",{className:"bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-2 p-4 backdrop-blur-sm",children:[/* @__PURE__ */m("div",{className:"bg-success/20 flex size-14 items-center justify-center rounded-full",children:/* @__PURE__ */m(Y,{className:"text-success size-8"})}),/* @__PURE__ */m("span",{className:"text-success text-sm font-medium",children:"Uploaded!"})]}),M&&/* @__PURE__ */m("div",{className:"bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-3 p-4 backdrop-blur-sm",children:[
|
|
63
63
|
/* @__PURE__ */m("div",{className:"bg-destructive/20 flex size-14 items-center justify-center rounded-full",children:/* @__PURE__ */m(W,{className:"text-destructive size-8"})}),
|
|
64
|
-
/* @__PURE__ */m("p",{className:"text-destructive text-center text-xs font-medium",children:f?.error??"Upload failed"}),a&&/* @__PURE__ */m("button",{type:"button",onClick:()=>a(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__ */m(q,{className:"size-3.5"}),"Retry"]})]})]}),!i&&/* @__PURE__ */m(G,{size:"sm",color:"error",variant:"default",className:"absolute top-3 right-3","aria-label":"Remove file",icon:/* @__PURE__ */m(
|
|
65
|
-
/* @__PURE__ */m(G,{size:"sm",variant:"default","aria-label":d?"Crop image":"Trim video",icon:/* @__PURE__ */m(d?Ze:Je,{}),onClick:()=>d?I(!0):
|
|
64
|
+
/* @__PURE__ */m("p",{className:"text-destructive text-center text-xs font-medium",children:f?.error??"Upload failed"}),a&&/* @__PURE__ */m("button",{type:"button",onClick:()=>a(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__ */m(q,{className:"size-3.5"}),"Retry"]})]})]}),!i&&/* @__PURE__ */m(G,{size:"sm",color:"error",variant:"default",className:"absolute top-3 right-3","aria-label":"Remove file",icon:/* @__PURE__ */m(N,{}),onClick:()=>r(e)}),!i&&(d||s)&&/* @__PURE__ */m("div",{className:"absolute top-3 left-3 flex gap-2",children:[
|
|
65
|
+
/* @__PURE__ */m(G,{size:"sm",variant:"default","aria-label":d?"Crop image":"Trim video",icon:/* @__PURE__ */m(d?Ze:Je,{}),onClick:()=>d?I(!0):P(!0)}),C&&S.length>0&&!T&&/* @__PURE__ */m(G,{size:"sm",variant:"default","aria-label":F?"Apply filter":"Skip filter",tooltip:F?"Apply filter":"Skip filter",icon:/* @__PURE__ */m(F?Ye:Ke,{}),onClick:()=>u.getState().setFileFilterSkipped(e,!F)}),C&&S.length>0&&!T&&!F&&/* @__PURE__ */m(G,{size:"sm",variant:"default","aria-label":"Compare original and filtered",tooltip:"Compare original and filtered",icon:/* @__PURE__ */m(Qe,{}),onClick:()=>{Xe&&(Ge.get(Xe)?.(),Xe=null),A(!0)}})]}),d&&B&&/* @__PURE__ */m(St,{open:R,onClose:()=>I(!1),imageSrc:B,title:"Crop Image",onCropComplete:r=>{const i=new File([r],t.name,{type:r.type});u.getState().replaceFile(e,i)}}),s&&D&&/* @__PURE__ */m(Ct,{open:D,onClose:()=>P(!1),videoFile:t,title:"Select Clip",onTrimComplete:({startTime:t,endTime:r})=>u.getState().setTrimRange(e,{startTime:t,endTime:r})}),O&&/* @__PURE__ */m(lt,{open:O,onClose:()=>A(!1),file:t,filters:S,isVideo:s,trimRange:v}),
|
|
66
66
|
/* @__PURE__ */m("div",{className:"mt-2",children:/* @__PURE__ */m(Oe,{placeholder:n?"Caption (required)":"Caption",value:h??"",onInput:t=>u.getState().setCaption(e,t.target.value),disabled:i,error:n&&!h?.trim()?" ":void 0,className:"text-xs"})})]});var fe});function Rt({applied:e}){/* @__PURE__ */
|
|
67
67
|
return m("div",{className:x("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 It({onUpload:e,onCancel:t,onRetryAll:r,uploadDisabled:i,selectedCount:n}){const o=We(e=>e.hasStarted),a=We(e=>e.uploadStates),s=We(e=>e.uploadSpeedBps),l=h(()=>{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__ */m("div",{className:"bg-background/85 fixed right-0 bottom-0 left-0 z-2002 overflow-hidden backdrop-blur-sm",children:/* @__PURE__ */m("div",{className:"relative flex items-stretch gap-3",children:[
|
|
68
|
-
/* @__PURE__ */m("div",{className:"relative min-w-0 flex-1 overflow-hidden",children:[o&&l&&/* @__PURE__ */m("div",{className:"bg-primary/40 absolute inset-y-0 t-0 text-right transition-all duration-300",style:{width:`${l.percent}%`}}),/* @__PURE__ */m("div",{className:"relative flex h-full flex-col justify-center gap-0.5 py-3 pl-3",children:/* @__PURE__ */m("span",o&&l?{className:"text-muted-foreground text-sm font-medium",children:["Uploading...",l.failed>0?` · ${l.failed} failed`:""," (",l.percent,"%)"," ",s?/* @__PURE__ */m("span",{className:"text-muted-foreground/70 text-xs",children:["• ",(c=s,c<=0?"":c<1048576?`${(c/1024).toFixed(0)} KB/s`:`${(c/1048576).toFixed(1)} MB/s`)]}):null]}:{className:"text-muted-foreground text-sm font-medium",children:[n," media selected"]})})]}),o&&d&&/* @__PURE__ */m("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__ */m(q,{className:"size-4"}),"Retry All"]}),o&&!d&&/* @__PURE__ */m("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__ */m("button",{type:"button",onClick:e,disabled:i,className:x("
|
|
69
|
-
return m("div",{role:"button",tabIndex:0,onClick:()=>!t&&a.current?.click(),onKeyDown:e=>{t||"Enter"!==e.key&&" "!==e.key||a.current?.click()},onDragOver:e=>{e.preventDefault(),t||o(!0)},onDragLeave:()=>o(!1),onDrop:g(e=>{e.preventDefault(),o(!1),t||d(e.dataTransfer?.files??null)},[t,d]),children:[/* @__PURE__ */m("input",{ref:a,type:"file",accept:s,multiple:!0,disabled:t,className:"hidden",onChange:e=>{d(e.target.files),e.target.value=""}}),i({isDragActive:n})]})}function
|
|
68
|
+
/* @__PURE__ */m("div",{className:"relative min-w-0 flex-1 overflow-hidden",children:[o&&l&&/* @__PURE__ */m("div",{className:"bg-primary/40 absolute inset-y-0 t-0 text-right transition-all duration-300",style:{width:`${l.percent}%`}}),/* @__PURE__ */m("div",{className:"relative flex h-full flex-col justify-center gap-0.5 py-3 pl-3",children:/* @__PURE__ */m("span",o&&l?{className:"text-muted-foreground text-sm font-medium",children:["Uploading...",l.failed>0?` · ${l.failed} failed`:""," (",l.percent,"%)"," ",s?/* @__PURE__ */m("span",{className:"text-muted-foreground/70 text-xs",children:["• ",(c=s,c<=0?"":c<1048576?`${(c/1024).toFixed(0)} KB/s`:`${(c/1048576).toFixed(1)} MB/s`)]}):null]}:{className:"text-muted-foreground text-sm font-medium",children:[n," media selected"]})})]}),o&&d&&/* @__PURE__ */m("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__ */m(q,{className:"size-4"}),"Retry All"]}),o&&!d&&/* @__PURE__ */m("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__ */m("button",{type:"button",onClick:e,disabled:i,className:x("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__ */m("span",{className:"flex items-center gap-2",children:[/* @__PURE__ */m(A,{className:"size-4"}),"Upload"]})})]})});var c}function Dt({enabledFileTypes:e,disabled:t,onFileSelect:r,children:i}){const[n,o]=c(!1),a=l(null),s=function(e){const t=e.filter(e=>re.includes(e)),r=e.filter(e=>ie.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),d=g(t=>{if(!t)return;const i=Array.from(t).filter(t=>function(e,t){if(e.type.startsWith("image/")||e.type.startsWith("video/"))return!0;const r=e.name.split(".").pop()?.toLowerCase();return!!r&&t.includes(r)}(t,e));i.length>0&&r(i)},[e,r]);/* @__PURE__ */
|
|
69
|
+
return m("div",{role:"button",tabIndex:0,onClick:()=>!t&&a.current?.click(),onKeyDown:e=>{t||"Enter"!==e.key&&" "!==e.key||a.current?.click()},onDragOver:e=>{e.preventDefault(),t||o(!0)},onDragLeave:()=>o(!1),onDrop:g(e=>{e.preventDefault(),o(!1),t||d(e.dataTransfer?.files??null)},[t,d]),children:[/* @__PURE__ */m("input",{ref:a,type:"file",accept:s,multiple:!0,disabled:t,className:"hidden",onChange:e=>{d(e.target.files),e.target.value=""}}),i({isDragActive:n})]})}function Nt({enabledFileTypes:e,disabled:t,onFileSelect:r,selectedCount:i,maxCount:n,enableVideo:o}){/* @__PURE__ */
|
|
70
70
|
return m("div",{className:"mb-6 flex-auto",children:/* @__PURE__ */m("div",{className:"flex w-full justify-center",children:/* @__PURE__ */m(Dt,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:()=>/* @__PURE__ */m("div",{className:x("w-full rounded border-2 border-dashed px-[6vw] sm:px-[20vw] 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:[
|
|
71
71
|
/* @__PURE__ */m("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__ */m("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"})}),
|
|
72
72
|
/* @__PURE__ */m("span",{className:x(t?"text-muted-foreground":"","mt-2 block font-medium"),children:`Select Images ${o?"or Videos (60s)":""} to upload (${i}/${n})`}),
|
|
73
|
-
/* @__PURE__ */m("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
|
+
/* @__PURE__ */m("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 Pt({enabledFileTypes:e,disabled:t,onFileSelect:r}){/* @__PURE__ */
|
|
74
74
|
return m(Dt,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:({isDragActive:e})=>/* @__PURE__ */m("div",{className:x("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__ */m("span",{className:"text-lg font-medium",children:e?"Drop to add files...":"+ Add more files"})})})}function Ot({enabledFileTypes:e,disabled:t,onFileSelect:r}){/* @__PURE__ */
|
|
75
75
|
return m(Dt,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:()=>/* @__PURE__ */m("div",{className:x("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__ */m("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:"size-4",children:/* @__PURE__ */m("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__ */m("span",{children:"Add more"})]})})}function At({uploadDisabled:e,eventName:t,isQuotaLoading:r,remainingUploads:i}){const n=r?"-":i;/* @__PURE__ */
|
|
76
|
-
return m("div",{className:"relative overflow-hidden rounded-2xl px-3 pt-6 sm:pt-0",children:[/* @__PURE__ */m("div",{className:"absolute inset-0 opacity-50"}),/* @__PURE__ */m("div",{className:"relative z-10",children:/* @__PURE__ */m("div",{className:"flex flex-col items-center justify-center gap-3",children:/* @__PURE__ */m("div",{className:"flex items-center gap-3",children:/* @__PURE__ */m("div",{className:"space-y-1 text-center",children:[t&&/* @__PURE__ */m(U,{variant:"h4",align:"center",className:"line-clamp-2",children:t}),/* @__PURE__ */m("p",{className:x("text-sm font-medium",e?"text-muted-foreground":"text-foreground"),children:["Remaining Uploads: ",/* @__PURE__ */m("span",{className:"text-primary font-bold",children:n})]})]})})})})]})}var qt=Object.defineProperty,Lt=Object.getOwnPropertyNames,zt=(e,t)=>function(){return e&&(t=(0,e[Lt(e)[0]])(e=0)),t},jt=(e,t)=>{for(var r in t)qt(e,r,{get:t[r],enumerable:!0})};function $t(e){const t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Bt(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 Ht(e,t,r){const i=$t(e),n=$t(t),o=$t(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 Wt(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[Bt(4.0767416621*d-3.3077115913*c+.2309699292*u),Bt(h),Bt(p)]}var Vt,Gt=zt({"src/color-space.ts"(){}});function Xt(e,t){return(Math.max(e,t)+.05)/(Math.min(e,t)+.05)}function Yt(e,t,r,i,n=0){return new Vt(e,t,r,i,n)}var Kt=zt({"src/color.ts"(){Gt(),Vt=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=Ht(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=Xt(e,1),r=Xt(e,0),i=this.isDark?Yt(255,255,255,0,0):Yt(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 Qt(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 Jt(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 Zt(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 er(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=Jt(e,o,i.quality,a);if(0===l.length&&(l=Jt(e,o,i.quality,{...a,ignoreWhite:!1})),0===l.length&&(l=Jt(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}=Ht(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:Wt(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})=>Yt(t,r,i,n,e>0?n/e:0))}const d=Zt(e,o,i.quality);return d?[Yt(d[0],d[1],d[2],1,1)]:null}jt({},{computeFallbackColor:()=>Zt,createPixelArray:()=>Jt,extractPalette:()=>er,validateOptions:()=>Qt});var tr,rr=zt({"src/pipeline.ts"(){Kt(),Gt()}});jt({},{BrowserPixelLoader:()=>tr});var ir,nr,or,ar,sr,lr=zt({"src/loaders/browser.ts"(){tr=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}}}}}),dr=zt({"src/worker/worker-script.ts"(){ir="\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 cr(){return"undefined"!=typeof Worker}function ur(e,t,r){return new Promise((i,n)=>{if(r?.aborted)return void n(r.reason??new DOMException("Aborted","AbortError"));const o=ar++;sr.set(o,{resolve:i,reject:n});const a=()=>{sr.delete(o),n(r.reason??new DOMException("Aborted","AbortError"))};r?.addEventListener("abort",a,{once:!0});try{(function(){if(nr)return nr;if(!cr())throw new Error("Web Workers are not supported in this environment.");return or=URL.createObjectURL(new Blob([ir],{type:"application/javascript"})),(nr=new Worker(or)).onmessage=e=>{const{id:t,palette:r,error:i}=e.data,n=sr.get(t);if(n)if(sr.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})=>Yt(e,r,i,n,t>0?n/t:0));n.resolve(i)}},nr.onerror=e=>{for(const[,t]of sr)t.reject(new Error(e.message));sr.clear()},nr})().postMessage({id:o,pixels:e,maxColors:t})}catch(s){sr.delete(o),r?.removeEventListener("abort",a),n(s)}})}function hr(){nr&&(nr.terminate(),nr=null),or&&(URL.revokeObjectURL(or),or=null);for(const[,e]of sr)e.reject(/* @__PURE__ */new Error("Worker terminated"));sr.clear()}function pr(e,t,r){return(e<<10)+(t<<5)+r}jt({},{extractInWorker:()=>ur,isWorkerSupported:()=>cr,terminateWorker:()=>hr}),zt({"src/worker/manager.ts"(){Kt(),dr(),nr=null,or=null,ar=0,sr=/* @__PURE__ */new Map}}),rr(),rr(),Kt(),Yt(255,255,255,0),Yt(0,0,0,0);var mr=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[pr(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[pr(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}},gr=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 fr(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[pr(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[pr(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[pr(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 vr(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=fr(r,o);if(!a||!a[0])return;e.push(a[0]),a[1]&&(e.push(a[1]),i++)}}lr(),rr(),new tr;var wr=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[pr(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 mr(r,i,n,o,a,s,t)}(e,n),a=new gr((e,t)=>e.count()-t.count());a.push(o),vr(a,.75*t,n);const s=new gr((e,t)=>e.count()*e.volume()-t.count()*t.volume());for(;a.size();)s.push(a.pop());vr(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 br(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=D(l.data,n,o,4,4)}catch(c){console.warn("[media-intrinsics] blurhash encode failed:",c)}try{const e=function(e,t){const r=Qt(t??{}),i=t?.quantizer??wr,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 er(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 yr(e,t){return Object.hasOwn(e,t)}Kt();var{AbortController:xr}=globalThis,{AbortSignal:Sr}=globalThis,Cr=(e="Aborted",t)=>{const r=new DOMException(e,"AbortError");return null!=t&&yr(t,"cause")&&Object.defineProperty(r,"cause",{__proto__:null,configurable:!0,writable:!0,value:t.cause}),r},Tr=class extends Error{isNetworkError;cause;constructor(e,t){super(e),this.cause=t?.cause,this.cause&&yr(this.cause,"isNetworkError")?this.isNetworkError=this.cause.isNetworkError:this.isNetworkError=!1}},Fr=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 kr(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 _r={__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 Er(e){if(e.type)return e.type;const t=e.name?kr(e.name).extension?.toLowerCase():null;return t&&t in _r?_r[t]:"application/octet-stream"}function Mr(e){let t="";return e.replace(/[^A-Z0-9]/gi,e=>(t+=`-${function(e){return e.charCodeAt(0).toString(32)}(e)}`,"/"))+t}function Ur(e,t){return!0===e?Object.keys(t):Array.isArray(e)?e:[]}function Rr(e){return e<10?`0${e}`:e.toString()}function Ir(){const e=/* @__PURE__ */new Date;return`${Rr(e.getHours())}:${Rr(e.getMinutes())}:${Rr(e.getSeconds())}`}function Dr(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 Pr=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:Dr,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=Dr,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 Nr(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 Or(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=Nr(i,new RegExp(`%\\{${n}\\}`,"g"),e)}return i}var Ar=e=>{throw new Error(`missing string: ${e}`)},qr=class{locale;constructor(e,{onMissingKey:t=Ar}={}){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 Or(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 Or(r,t)}},Lr=class extends Error{name="UserFacingApiError"},zr=/* @__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}}),jr=/* @__PURE__ */t(e=>{var t=zr();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}}}),$r=/* @__PURE__ */t((e,t)=>{t.exports=jr()}),Br=Object.prototype.toString,Hr=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 Wr=/* @__PURE__ */e($r(),1),Vr=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}},Gr=(e,t,r)=>{const i=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=i,e};async function Xr(e,t){return new Promise((r,i)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const n=Wr.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 Vr)throw s.originalError;if(s instanceof TypeError&&!function(e){if(!e||(t=e,"[object Error]"!==Br.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(")"))||Hr.has(r)}(s))throw s;if(Gr(s,o,t),await t.shouldRetry(s)||(n.stop(),i(s)),await t.onFailedAttempt(s),!n.retry(s))throw n.mainError()}catch(l){Gr(l,o,t),a(),i(l)}}})})}var Yr=class extends Error{isAuthError;constructor(){super("Authorization required"),this.name="AuthError",this.isAuthError=!0}},Kr=class extends Error{statusCode;constructor({statusCode:e,message:t}){super(t),this.name="HttpError",this.statusCode=e}},Qr=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 Fr(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 Yr;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 Lr(t.message);throw new Kr({statusCode:e.status,message:r})}(a)}catch(o){if(o.isAuthError||"UserFacingApiError"===o.name||"AbortError"===o.name)throw o;throw new Tr(`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 Xr(async()=>{const r=this.uppy.getFile(e.id)?.serverToken;if(null!=r)return this.uppy.log(`Connecting to exiting websocket ${r}`),this.#w({file:e,queue:n(),signal:i});const o=await n().wrapPromiseFunction(async(...e)=>{try{return await this.#b(...e)}catch(t){if(t.isAuthError)throw new Vr(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 Vr(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.#w({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}}#b=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#w({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()},w=(t,r)=>{t?.id===e.id&&g(r)},b=()=>g(!0),y=()=>g(!1);this.uppy.on("file-removed",f),this.uppy.on("cancel-all",v),this.uppy.on("upload-pause",w),this.uppy.on("pause-all",b),this.uppy.on("resume-all",y),i=()=>{this.uppy.off("file-removed",f),this.uppy.off("cancel-all",v),this.uppy.off("upload-pause",w),this.uppy.off("pause-all",b),this.uppy.off("resume-all",y)},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 Xr(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?.()}}},Jr=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 qr([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(){}},Zr=class{#y;#x=[];constructor(e){this.#y=e}on(e,t){return this.#x.push([e,t]),this.#y.on(e,t)}remove(){for(const[e,t]of this.#x.splice(0))this.#y.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.#y.getFile(e)&&t()})}onPauseAll(e,t){this.on("pause-all",()=>{this.#y.getFile(e)&&t()})}onCancelAll(e,t){this.on("cancel-all",(...r)=>{this.#y.getFile(e)&&t(...r)})}onResumeAll(e,t){this.on("resume-all",()=>{this.#y.getFile(e)&&t()})}},ei={debug:()=>{},warn:()=>{},error:(...e)=>console.error(`[Uppy] [${Ir()}]`,...e)},ti={debug:(...e)=>console.debug(`[Uppy] [${Ir()}]`,...e),warn:(...e)=>console.warn(`[Uppy] [${Ir()}]`,...e),error:(...e)=>console.error(`[Uppy] [${Ir()}]`,...e)},ri=/* @__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}`}}),ii=/* @__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}}),ni=/* @__PURE__ */t((e,t)=>{var r=ii(),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}}),oi=/* @__PURE__ */e(ri(),1),ai=/* @__PURE__ */e(ni(),1),si={maxFileSize:null,minFileSize:null,maxTotalFileSize:null,maxNumberOfFiles:null,minNumberOfFiles:null,allowedFileTypes:null,requiredMetaFields:[]},li=class extends Error{isUserFacing;file;constructor(e,t){super(e),this.isUserFacing=t?.isUserFacing??!0,t?.file&&(this.file=t.file)}isRestriction=!0},di=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 li(`${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 li(this.getI18n()("aggregateExceedsSize",{sizeAllowed:(0,oi.default)(r),size:(0,oi.default)(i)}))}}validateSingleFile(e){const{maxFileSize:t,minFileSize:r,allowedFileTypes:i}=this.getOpts().restrictions;if(i&&!i.some(t=>t.includes("/")?!!e.type&&(0,ai.default)(e.type.replace(/;.*?$/,""),t):!("."!==t[0]||!e.extension)&&e.extension.toLowerCase()===t.slice(1).toLowerCase())){const t=i.join(", ");throw new li(this.getI18n()("youCanOnlyUploadFileTypes",{types:t}),{file:e})}if(t&&null!=e.size&&e.size>t)throw new li(this.getI18n()("exceedsSize",{size:(0,oi.default)(t),file:e.name??this.getI18n()("unnamed")}),{file:e});if(r&&null!=e.size&&e.size<r)throw new li(this.getI18n()("inferiorSize",{size:(0,oi.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 li(this.getI18n()("youHaveToAtLeastSelectX",{smart_count:t}))}getMissingRequiredMetaFields(e){const t=new li(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}}},ci=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.#C(t,r,e)}subscribe(e){return this.#S.add(e),()=>{this.#S.delete(e)}}#C(...e){this.#S.forEach(t=>{t(...e)})}},ui=/* @__PURE__ */t((e,t)=>{t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}}),hi=/* @__PURE__ */t((e,t)=>{var r="object"==typeof global&&global&&global.Object===Object&&global;t.exports=r}),pi=/* @__PURE__ */t((e,t)=>{var r=hi(),i="object"==typeof self&&self&&self.Object===Object&&self,n=r||i||Function("return this")();t.exports=n}),mi=/* @__PURE__ */t((e,t)=>{var r=pi();t.exports=function(){return r.Date.now()}}),gi=/* @__PURE__ */t((e,t)=>{var r=/\s/;t.exports=function(e){for(var t=e.length;t--&&r.test(e.charAt(t)););return t}}),fi=/* @__PURE__ */t((e,t)=>{var r=gi(),i=/^\s+/;t.exports=function(e){return e?e.slice(0,r(e)+1).replace(i,""):e}}),vi=/* @__PURE__ */t((e,t)=>{var r=pi().Symbol;t.exports=r}),wi=/* @__PURE__ */t((e,t)=>{var r=vi(),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}}),bi=/* @__PURE__ */t((e,t)=>{var r=Object.prototype.toString;t.exports=function(e){return r.call(e)}}),yi=/* @__PURE__ */t((e,t)=>{var r=vi(),i=wi(),n=bi(),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)}}),xi=/* @__PURE__ */t((e,t)=>{t.exports=function(e){return null!=e&&"object"==typeof e}}),Si=/* @__PURE__ */t((e,t)=>{var r=yi(),i=xi();t.exports=function(e){return"symbol"==typeof e||i(e)&&"[object Symbol]"==r(e)}}),Ci=/* @__PURE__ */t((e,t)=>{var r=fi(),i=ui(),n=Si(),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}}),Ti=/* @__PURE__ */t((e,t)=>{var r=ui(),i=mi(),n=Ci(),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 w(t){var r=l,i=d;return l=d=void 0,m=t,u=e.apply(i,r)}function b(e){var r=e-p;return void 0===p||r>=t||r<0||f&&e-m>=c}function y(){var e=i();if(b(e))return x(e);h=setTimeout(y,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?w(e):(l=d=void 0,u)}function S(){var e=i(),r=b(e);if(l=arguments,d=this,p=e,r){if(void 0===h)return function(e){return m=e,h=setTimeout(y,t),g?w(e):u}(p);if(f)return clearTimeout(h),h=setTimeout(y,t),w(p)}return void 0===h&&(h=setTimeout(y,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}}),Fi=/* @__PURE__ */t((e,t)=>{var r=Ti(),i=ui();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})}}),ki=/* @__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}}),_i={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"}};function Ei(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 Mi=/* @__PURE__ */e(Fi(),1),Ui=/* @__PURE__ */e(ki(),1),Ri={totalProgress:0,allowNewUpload:!0,error:null,recoveredState:null},Ii=class e{static VERSION="5.2.0";#T=Object.create(null);#F;#k;#_=(0,Ui.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=_i;const r={id:"uppy",autoProceed:!1,allowMultipleUploadBatches:!0,debug:!1,restrictions:si,meta:{},onBeforeFileAdded:(e,t)=>!Object.hasOwn(t,e.id),onBeforeUpload:e=>e,store:new ci,logger:ei,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=ti),this.log(`Using Core v${e.VERSION}`),this.i18nInit(),this.store=this.opts.store,this.setState({...Ri,plugins:{},files:{},currentUploads:{},capabilities:{uploadProgress:Ei(),individualCancellation:!0,resumableUploads:!1},meta:{...this.opts.meta},info:[]}),this.#F=new di(()=>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 qr([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,...Ri})}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({...Ri,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}#D(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)}#P(e){let t=!0;for(const r of Object.values(e))this.#D(r)||(t=!1);return t}#N(e){const{allowNewUpload:t}=this.getState();if(!1===t){const t=new li(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=Er(t),i=function(e,t){return t.name?t.name:"image"===e.split("/")[0]?`${e.split("/")[0]}.${e.split("/")[1]}`:"noname"}(r,t),n=kr(i).extension,o=function(e,t){if(function(e){return!(!e.isRemote||!e.remote)&&new Set(["box","dropbox","drive","facebook","unsplash"]).has(e.remote.provider)}(e))return e.id;const r=Er(e);return function(e,t){let r=t||"uppy";return"string"==typeof e.name&&(r+=`-${Mr(e.name.toLowerCase())}`),void 0!==e.type&&(r+=`-${e.type}`),e.meta&&"string"==typeof e.meta.relativePath&&(r+=`-${Mr(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))}#q(e){let{files:t}=this.getState(),r={...t};const i=[],n=[];for(const a of e)try{let e=this.#O(a);this.#N(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 li(this.i18n("noDuplicates",{fileName:e.name??this.i18n("unnamed")}),{file:e});if(!1===s&&!o)throw new li("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.#q([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.#q(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")}#z(){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#j(){const e=this.#z(),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.#j();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(Ri)}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()};#W(){const e=this.#V();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,Mi.default)(()=>this.#W(),500,{leading:!0,trailing:!0});[Symbol.for("uppy test: updateTotalProgress")](){return this.#W()}#V(){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.#D(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.#T?this.#T[r.type].push(r):this.#T[r.type]=[r],r.install(),this.emit("plugin-added",r),this}getPlugin(e){for(const t of Object.values(this.#T)){const r=t.find(t=>t.id===e);if(null!=r)return r}}[Symbol.for("uppy test: getPlugins")](e){return this.#T[e]}iteratePlugins(e){Object.values(this.#T).flat(1).forEach(e)}removePlugin(e){this.log(`Removing plugin ${e.id}`),this.emit("plugin-remove",e),e.uninstall&&e.uninstall();const t=this.#T[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--;)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}})}#K(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.#K(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.#K(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.#T.uploader?.length||this.log("No uploader type plugins are used","warning");let{files:e}=this.getState();if(this.#z().length>0){const t=await this.#j();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.#P(e))throw new li(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 Di({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 Pi=new TextEncoder,Ni={name:"HMAC",hash:"SHA-256"};async function Oi(e){const{subtle:t}=globalThis.crypto;return t.digest(Ni.hash,Pi.encode(e))}function Ai(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 qi(e,t){const{subtle:r}=globalThis.crypto;return r.sign(Ni,await async function(e){const{subtle:t}=globalThis.crypto;return t.importKey("raw","string"==typeof e?Pi.encode(e):e,Ni,!1,["sign"])}(e),Pi.encode(t))}async function Li({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,Ai(await Oi(Di({CanonicalUri:u,CanonicalQueryString:f.search.slice(1),SignedHeaders:{host:c},HashedPayload:h})))].join("\n"),w=Ai(await qi(await qi(await qi(await qi(await qi(`AWS4${t}`,m),o),d),"aws4_request"),v));return f.searchParams.set("X-Amz-Signature",w),f}var zi={getChunkSize:e=>Math.ceil(e.size/1e4),onProgress(){},onPartComplete(){},onSuccess(){},onError(e){throw e}},ji=Symbol("pausing upload, not an actual error"),$i=class{options;#Q=new xr;#J=[];#Z=[];#ee;#te;#re=!1;#ie;#ne;#oe;#ae;#se=e=>e?.cause===ji?null:this.#ie(e);#le=1e4;#de=5242880;constructor(e,t){this.options={...zi,...t},this.options.getChunkSize??=zi.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.#Q.signal).then(this.#ne,this.#se),this.#re=!0}#pe(){this.options.companionComm.resumeUploadFile(this.#te,this.#J,this.#Q.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.#Q.abort(),this.options.companionComm.abortFileUpload(this.#te).catch(e=>this.options.log(e))}start(){this.#re?(this.#Q.signal.aborted||this.#Q.abort(ji),this.#Q=new xr,this.#pe()):this.#ae?(this.options.companionComm.restoreUploadFile(this.#te,{uploadId:this.options.uploadId,key:this.options.key}),this.#pe()):this.#$()}pause(){this.#Q.abort(ji),this.#Q=new xr}abort(e){e?.really?this.#me():this.pause()}[Symbol.for("uppy test: getChunkState")](){return this.#Z}};function Bi(e){if(e?.aborted)throw Cr("The operation was aborted",{cause:e.reason})}function Hi(e){const t=new URL(e);return t.search="",t.hash="",t.href}var Wi=class{#ge;#fe=/* @__PURE__ */new WeakMap;#ve;#we;#be;#ye;#xe;#Se;#Ce;#Te;#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.#we=t.wrapPromiseFunction(e.signPart)),"listParts"in e&&(this.#ye=t.wrapPromiseFunction(e.listParts)),"completeMultipartUpload"in e&&(this.#Te=t.wrapPromiseFunction(e.completeMultipartUpload,{priority:1})),"retryDelays"in e&&(this.#Ce=e.retryDelays??[]),"uploadPartBytes"in e&&(this.#ke=t.wrapPromiseFunction(e.uploadPartBytes,{priority:1/0})),"getUploadParameters"in e&&(this.#be=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.#be(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??Hi(n),bucket:o?.bucket,key:h}}async uploadFile(e,t,r){if(Bi(r),1===t.length&&!t[0].shouldUseMultipart)return this.#Me(e,t[0],r);const{uploadId:i,key:n}=await this.getUploadId(e,r);Bi(r);try{const o=await Promise.all(t.map((t,i)=>this.uploadChunk(e,i+1,t,r)));return Bi(r),await this.#Te(this.#_e(e),{key:n,uploadId:i,parts:o,signal:r},r).abortOn(r)}catch(o){throw o?.cause!==ji&&"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(Bi(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);Bi(r);const o=await this.#ye(this.#_e(e),{uploadId:i,key:n,signal:r},r).abortOn(r);Bi(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 Bi(r),this.#Te(this.#_e(e),{key:n,uploadId:i,parts:a,signal:r},r).abortOn(r)}async uploadChunk(e,t,r,i){Bi(i);const{uploadId:n,key:o}=await this.getUploadId(e,i),a=this.#Ce.values(),s=this.#Ce.values(),l=()=>{const e=a.next();return null==e||e.done?null:e.value};for(;;){Bi(i);const a=r.getData(),{onProgress:c,onComplete:u}=r;let h;try{h=await this.#we(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}Bi(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 Vi(e){if(e?.error){const t=new Error(e.message);throw Object.assign(t,e.error),t}return e}function Gi(e){const t=e.Expiration;if(t){const e=Math.floor((new Date(t)-Date.now())/1e3);if(e>9)return e}}function Xi({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 Yi={allowedMetaFields:!0,limit:6,getTemporarySecurityCredentials:!1,shouldUseMultipart:e=>(e.size||0)>104857600,retryDelays:[0,1e3,3e3,5e3]},Ki=class e extends Jr{static VERSION="5.1.0";#Ue;#Re;requests;uploaderEvents;uploaders;constructor(t,r){super(t,{...Yi,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 Pr(this.opts.limit),this.#Ue=new Wi(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 Qr(this.uppy,{pluginId:this.id,provider:"AWS",companionUrl:this.opts.endpoint,companionHeaders:this.opts.headers,companionCookiesRule:this.opts.cookiesRule}):("headers"in e&&this.#De(),"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)}#Pe(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.#Pe("createMultipartUpload"),Bi(t);const r=Ur(this.opts.allowedMetaFields,e.meta),i=Xi({meta:e.meta,allowedMetaFields:r});return this.#Re.post("s3/multipart",{filename:e.name,type:e.type,metadata:i},{signal:t}).then(Vi)}listParts(e,{key:t,uploadId:r,signal:i},n){i??=n,this.#Pe("listParts"),Bi(i);const o=encodeURIComponent(t);return this.#Re.get(`s3/multipart/${encodeURIComponent(r)}?key=${o}`,{signal:i}).then(Vi)}completeMultipartUpload(e,{key:t,uploadId:r,parts:i,signal:n},o){n??=o,this.#Pe("completeMultipartUpload"),Bi(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(Vi)}#Ne;async#Oe(e){if(Bi(e?.signal),null==this.#Ne){const{getTemporarySecurityCredentials:t}=this.opts;!0===t?(this.#Pe("getTemporarySecurityCredentials"),this.#Ne=this.#Re.get("s3/sts",e).then(Vi)):this.#Ne=t(e),this.#Ne=await this.#Ne,setTimeout(()=>{this.#Ne=null},500*(Gi(this.#Ne.credentials)||0))}return this.#Ne}async createSignedURL(e,t){const r=await this.#Oe(t),i=Gi(r.credentials)||604800,{uploadId:n,key:o,partNumber:a}=t;return{method:"PUT",expires:i,fields:{},url:`${await Li({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.#Pe("signPart"),Bi(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(Vi)}abortMultipartUpload(e,{key:t,uploadId:r,signal:i}){this.#Pe("abortMultipartUpload");const n=encodeURIComponent(t),o=encodeURIComponent(r);return this.#Re.delete(`s3/multipart/${o}?key=${n}`,void 0,{signal:i}).then(Vi)}getUploadParameters(e,t){this.#Pe("getUploadParameters");const{meta:r}=e,{type:i,name:n}=r,o=Xi({meta:r,allowedMetaFields:Ur(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(Bi(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(Cr())}),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 $i(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 Zr(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()})}#qe(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.#ze(!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.#qe(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.#ze(!0),n};#De=()=>{this.#Re?.setCompanionHeaders(this.opts.headers)};#ze=e=>{const{capabilities:t}=this.uppy.getState();this.uppy.setState({capabilities:{...t,resumableUploads:e}})};#je=()=>{this.#ze(!0)};install(){this.#ze(!0),this.uppy.addPreProcessor(this.#De),this.uppy.addUploader(this.#Le),this.uppy.on("cancel-all",this.#je)}uninstall(){this.uppy.removePreProcessor(this.#De),this.uppy.removeUploader(this.#Le),this.uppy.off("cancel-all",this.#je)}},Qi="undefined"!=typeof window&&(window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB),Ji=!!Qi,Zi="uppy-blobs",en="files",tn=864e5,rn=1048576;function nn(e){const t=Qi.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(en,{keyPath:"id"}).createIndex("store","store",{unique:!1}),t.oldVersion<3){const e=i.objectStore(en);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()+tn,t.update(r)}}(e)}i.oncomplete=()=>{e(r)}},t.onsuccess=t=>{e(t.target.result)},t.onerror=r})}function on(e){return new Promise((t,r)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=r})}var an=!1,sn=class e{#$e;opts;name;static isSupported;constructor(t){this.opts={dbName:Zi,storeName:"default",expires:tn,maxFileSize:10*rn,maxTotalSize:300*rn,...t},this.name=this.opts.storeName;const r=async()=>{const e=await nn(this.opts.dbName);return this.#$e=e,e};an?this.#$e=r():(an=!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 on((await this.#$e).transaction([en],"readonly").objectStore(en).index("store").getAll(IDBKeyRange.only(this.name)));return Object.fromEntries(e.map(e=>[e.fileID,e.data]))}async get(e){const{data:t}=await on((await this.#$e).transaction([en],"readonly").objectStore(en).get(this.key(e)));return{id:t.fileID,data:t.data}}async getSize(){const e=(await this.#$e).transaction([en],"readonly").objectStore(en).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 on((await this.#$e).transaction([en],"readwrite").objectStore(en).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 on((await this.#$e).transaction([en],"readwrite").objectStore(en).delete(this.key(e)))}static async cleanup(){const e=await nn(Zi),t=e.transaction([en],"readwrite").objectStore(en).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 ln(e){try{return JSON.parse(e)}catch{return null}}sn.isSupported=Ji;var dn="uppyState:",cn=class{opts;name;#Be;constructor(e){var t;this.opts={expires:864e5,throttleTime:500,...e},this.name=(t=e.storeName,`${dn}${t}`),this.#Be=0===this.opts.throttleTime?this.save:(0,Mi.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(dn)&&e.push(t)}const t=Date.now();e.forEach(e=>{const r=localStorage.getItem(e);if(!r)return;const i=ln(r);i?.expires&&i.expires<t&&localStorage.removeItem(e)})}();const e=localStorage.getItem(this.name);if(!e)return;const t=ln(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()}},un="undefined"!=typeof navigator&&"serviceWorker"in navigator,hn=class{#$e;name;static isSupported;constructor(e){this.#$e=new Promise((e,t)=>{un?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})}};hn.isSupported=un;var pn={expires:864e5,serviceWorker:!1},mn=class e extends Jr{static VERSION="5.2.1";#We;#Ve;#Ge;static[Symbol.for("uppy test: throttleTime")];constructor(t,r){super(t,{...pn,...r}),this.type="debugger",this.id=this.opts.id||"GoldenRetriever",this.#We=new cn({expires:this.opts.expires,storeName:t.getID(),throttleTime:e[Symbol.for("uppy test: throttleTime")]??void 0}),this.opts.serviceWorker&&(this.#Ve=new hn({storeName:t.getID()})),this.#Ge=new sn({expires:this.opts.expires,...this.opts.indexedDB||{},storeName:t.getID()})}async#Xe(){const e=this.#We.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.#Ke()]),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.#Qe(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.#We.get();this.#We.set({...r??{currentUploads:{},files:{}},...t,pluginData:{...r?.pluginData,...e}})};async#Ye(){if(!this.#Ve)return{};try{const e=await this.#Ve.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#Ke(){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#Qe(e){await Promise.all(e.map(async e=>{try{await Promise.all([this.#Ve?.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.#Qe(e)}#Ze=async e=>{const{id:t,data:r,isRemote:i}=e;i||null==r||await Promise.all([this.#Ve?.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.#Qe(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 gn(){const e=Ve(),t=S(),r=l(null),i=l(null),n=l({}),a=l(0),s=l(null),d=l({}),c=l(void 0),u=l({});o(()=>{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 h=g(()=>{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},[]),p=g(()=>{if(!r.current){const t=new Ii({autoProceed:!0}).use(mn,{id:"GoldenRetriever",expires:864e5,serviceWorker:!1}).use(Ki,{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 n=t.meta.uid;e.getState().setUploadState(n,{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=i.current;if(s){const t=(o-s.time)/1e3;if(t>=.5){const r=Math.max(0,(a-s.bytes)/t),n=s.speed>0?.7*s.speed+.3*r:r;i.current={time:o,bytes:a,speed:n},e.getState().setUploadSpeedBps(n)}}else i.current={time:o,bytes:a,speed:0}}),t.on("upload-success",r=>{if(!r)return;const o=r.meta.uid,a=r.meta.contentId,s=r.meta.key,l=r.meta.uploadStartedAt;(async()=>{try{const e=await fetch(T.UPLOAD_COMPLETE,{method:"POST",headers:h(),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(o,{status:"error",error:d instanceof Error?d.message:String(d)}),pe(d instanceof Error?d:new Error(String(d)),{component:"useUpload",tags:["upload","complete"],extra:{uid:o,contentId:a}}),void(a&&fetch(T.UPLOAD_FAIL,{method:"POST",headers:h(),body:JSON.stringify({contentId:a})}).catch(()=>{}))}e.getState().setUploadState(o,{status:"success",contentId:a}),delete n.current[o];try{t.removeFile(r.id)}catch{}Object.values(e.getState().uploadStates).every(e=>"success"===e.status||"error"===e.status)&&(i.current=null,e.getState().setUploadSpeedBps(0))})()}),t.on("upload-error",(t,r)=>{if(!t)return;const n=t.meta.uid,o=t.meta.contentId;e.getState().setUploadState(n,{status:"error",error:r instanceof Error?r.message:String(r)}),o&&fetch(T.UPLOAD_FAIL,{method:"POST",headers:h(),body:JSON.stringify({contentId:o})}).catch(()=>{}),Object.values(e.getState().uploadStates).every(e=>"success"===e.status||"error"===e.status)&&(i.current=null,e.getState().setUploadSpeedBps(0))}),t.on("restored",()=>{const{eventId:r}=e.getState(),i=[],o={},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}n.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&&(o[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,...o},uploadStates:{...e.uploadStates,...a},hasStarted:!0,showRestoreDialog:!0,restoredUids:i.map(e=>e.uid)}))}),r.current=t}return r.current},[e,h]);o(()=>{p()},[p]);const m=g(async(t,r)=>{const{eventId:i,groupId:o,captions:l,originalFiles:u,trimRanges:m,cropSelections:g,activeFilters:f,skipUploadFilters:v,perFileFilterSkipped:w}=e.getState(),b=u[t];if(!b)return!1;const y=p();try{e.getState().setUploadState(t,{status:"creating",bytesUploaded:0,bytesTotal:b.size,error:void 0});const u=ze(b)?"VIDEO":"IMAGE",p=await async function(e){const t=e.type.trim().toLowerCase(),r=e.name.toLowerCase(),i=Ae.test(r),n=Le.test(r),o=qe.test(r);if(t&&"application/octet-stream"!==t&&!(t.startsWith("image/")&&i||t.startsWith("video/")&&n||t.startsWith("image/")&&o))return t;try{const t=new Uint8Array(await e.slice(0,12).arrayBuffer());if(82===t[0]&&73===t[1]&&70===t[2]&&70===t[3]){if(87===t[8]&&69===t[9]&&66===t[10]&&80===t[11])return"image/webp";if(65===t[8]&&86===t[9]&&73===t[10]&&32===t[11])return"video/x-msvideo"}if(255===t[0]&&216===t[1]&&255===t[2])return"image/jpeg";if(137===t[0]&&80===t[1]&&78===t[2]&&71===t[3])return"image/png";if(71===t[0]&&73===t[1]&&70===t[2]&&56===t[3])return"image/gif";if(26===t[0]&&69===t[1]&&223===t[2]&&163===t[3])return r.endsWith(".webm")?"video/webm":"video/x-matroska";const n=102===t[4]&&116===t[5]&&121===t[6]&&112===t[7],o=109===t[4]&&111===t[5]&&111===t[6]&&118===t[7],a=109===t[4]&&100===t[5]&&97===t[6]&&116===t[7];if(n||o||a){if(n){const e=String.fromCharCode(t[8]??0,t[9]??0,t[10]??0,t[11]??0).trim().toLowerCase();if("heic"===e||"heix"===e||"mif1"===e)return"image/heic";if("qt "===e)return"video/quicktime"}return i&&(r.endsWith(".mov")||r.endsWith(".qt"))?"video/quicktime":"video/mp4"}}catch{}return t||"application/octet-stream"}(b);if(a.current!==r)return!1;const x=d.current[t]??=await async function(e){try{return await(t=ze(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,...br(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 createImageBitmap(e);try{return{dimension:{width:t.width,height:t.height},...br(t,t.width,t.height)}}finally{t.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}(b);if(a.current!==r)return!1;const S=m[t],C=g[t],F=f.length>0?w[t]??v:void 0,k=await fetch(T.UPLOAD_CREATE,{method:"POST",headers:h(),signal:s.current?.signal,body:JSON.stringify({eventId:i,groupId:o,uid:t,type:u,fileName:b.name,fileSize:b.size,rawContentType:p,caption:l[t],trimInfo:S?{start:S.startTime,end:S.endTime}:void 0,cropInfo:C,dimension:x.dimension,blurhash:x.blurhash,colors:x.colors,duration:x.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(a.current!==r)return fetch(T.UPLOAD_ABORT,{method:"POST",headers:h(),body:JSON.stringify({contentId:_,key:E})}).catch(()=>{}),!1;const U=n.current[t];if(U&&y.getFile(U))try{y.removeFile(U)}catch{}const R=y.addFile({name:b.name,type:p,data:b,meta:{uid:t,userId:c.current,contentId:_,key:E,uploadUrl:M,rawContentType:p,eventId:i,groupId:o,type:u,caption:l[t],uploadStartedAt:Date.now()}});return n.current[t]=R,!0}catch(x){return a.current!==r||x instanceof DOMException&&"AbortError"===x.name||(e.getState().setUploadState(t,{status:"error",error:x instanceof Error?x.message:String(x)}),pe(x instanceof Error?x:new Error(String(x)),{component:"useUpload",tags:["upload","create"],extra:{uid:t}})),!1}},[e,p,h]),f=g(async()=>{const{selectedFiles:t,oversizedUids:r}=e.getState(),i=t.filter(({uid:e})=>!r[e]);if(0===i.length)return;const n=++a.current;s.current=new AbortController;const o=p();e.getState().setHasStarted(!0);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})=>m(e,n)),a.current===n?0===o.getFiles().length?(N.error("Could not start upload. Please try again."),void e.getState().setHasStarted(!1)):void(await o.upload()):void 0},[e,p,m]),v=g(()=>{a.current++,s.current?.abort(),i.current=null,n.current={},d.current={},r.current?.cancelAll(),e.getState().resetUploader()},[e]),w=g(t=>{const r=p();i.current=null;const o=n.current[t],s=o?r.getFile(o):void 0;if(s)return e.getState().setUploadState(t,{status:"uploading",bytesUploaded:0,bytesTotal:s.size??0,error:void 0}),void r.retryUpload(o).catch(r=>{e.getState().setUploadState(t,{status:"error",error:r instanceof Error?r.message:String(r)})});m(t,a.current)},[e,p,m]),b=g(()=>{Object.entries(e.getState().uploadStates).filter(([,e])=>"error"===e.status).map(([e])=>e).forEach(e=>w(e))},[e,w]);return o(()=>()=>{a.current++,s.current?.abort(),r.current?.cancelAll(),r.current?.destroy(),r.current=null},[]),{startUpload:f,cancelUpload:v,retryUpload:w,retryAllUploads:b,resumeRestoredUpload:g(()=>{const t=p();s.current=new AbortController,e.setState({showRestoreDialog:!1,restoredUids:[]}),t.upload()},[e,p]),discardRestoredUpload:g(()=>{const t=p(),{restoredUids:r}=e.getState();r.forEach(r=>{const i=n.current[r];if(i){try{t.removeFile(i)}catch{}delete n.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,p])}}function fn({eventSlug:e,event:t}){const r=S(),i=_(),n=r.props?.organizationId,a=r.user,s=Ve(),d=We(e=>e.selectedFiles),u=We(e=>e.hasStarted),h=We(e=>e.oversizedUids),p=We(e=>e.showOversizedModal),f=We(e=>e.activeFilters),x=We(e=>e.showFilterChoice),k=We(e=>e.skipUploadFilters),E=We(e=>e.showRestoreDialog),M=We(e=>e.restoredUids),[U,R]=c(!1),[D,P]=c(!1),[O,q]=c({}),[L,z]=c(!0);o(()=>{if(!a||!n)return;let t=!1;return z(!0),b.get(T.GET_UPLOAD_COUNT,{searchParams:{eventSlug:e},headers:{"x-org-id":n,...a.token?{Authorization:`Bearer ${a.token}`}:{}}}).json().then(e=>{t||q(e?.data?.uploadCount??{})}).catch(()=>{t||N.error("Failed to fetch upload count")}).finally(()=>{t||z(!1)}),()=>{t=!0}},[a,n,e]);const j=!t.uploadLimit||t.uploadLimit<=0,$=(O[C.APPROVED]??0)+(O[C.IN_REVIEW]??0),B=j?1/0:Math.max(0,(t.uploadLimit??0)-$),H=L,W=j?"Unlimited":B,V=Math.min(B,100),G=!(t.status===F.OPEN)||u||H,Y=t.enableVideo?[...re,...ie]:re,K=!!t.ada,Q=function({effectiveFileLimit:e,eventSlug:t}){const r=Ve();return g(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:ee(),file:e})),d=Math.max(0,e-a.length),c=l.slice(0,d),u=l.length-c.length;u>0&&(N.warn(`${u} file${u>1?"s":""} not added — you've reached your upload limit.`),me("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=ze(e),r=t?w:y;return e.size>r?t?"video":"image":void 0}(t);r&&(h[e]=r)}),Object.keys(h).length>0&&(r.getState().addOversizedUids(h),me("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})=>{ze(t)&&de(()=>{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:V,eventSlug:e}),{startUpload:J,cancelUpload:Z,retryUpload:se,retryAllUploads:le,resumeRestoredUpload:ce,discardRestoredUpload:ue}=gn(),he=g(()=>{P(!1),u?Z():s.getState().resetUploader()},[u,Z,s]);!function(e){const t=Ve(),r=S(),i=r.props?.organizationId,n=r.user?.token;o(()=>{if(!e||!i)return;let r=!1;return b.get(T.GET_POST_PROCESSING_SETTINGS,{searchParams:{eventId:e},headers:{"x-org-id":i,...n?{Authorization:`Bearer ${n}`}:{}}}).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=>{pe(e instanceof Error?e:/* @__PURE__ */new Error("Failed to load upload filters"),{component:"useUploadFilters",tags:["upload","filters"]})}),()=>{r=!0}},[e,i,n,t])}(t._id?String(t._id):void 0),o(()=>{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],s.getState().removeFile(r)},3e3))})};t(s.getState());const r=s.subscribe(t);return()=>{r(),Object.values(e).forEach(clearTimeout)}},[s]),o(()=>{0===d.length&&u&&s.getState().resetUploader()},[d.length,u,s]),o(()=>{if(!u)return;const e=e=>{Object.values(s.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,s]);const ge=g(e=>s.getState().removeFile(e),[s]),fe=g(()=>{if(!K)return!0;const e=s.getState(),t=e.selectedFiles.some(({uid:t})=>!e.oversizedUids[t]&&!e.captions[t]?.trim());return t&&N.warn("This event requires a caption on every file before uploading."),!t},[K,s]),ve=g(()=>{fe()&&(Object.keys(s.getState().oversizedUids).length>0?s.getState().setShowOversizedModal(!0):J())},[s,J,fe]),we=g(()=>{!a||a.tcAccepted?ve():R(!0)},[a,ve]),be=g(()=>{s.getState().removeOversizedFiles(),fe()&&J()},[s,J,fe]),[ye,xe]=c(!1),Se=l(0),Ce=G||d.length>=V;/* @__PURE__ */
|
|
76
|
+
return m("div",{className:"relative overflow-hidden rounded-2xl px-3 pt-6 sm:pt-0",children:[/* @__PURE__ */m("div",{className:"absolute inset-0 opacity-50"}),/* @__PURE__ */m("div",{className:"relative z-10",children:/* @__PURE__ */m("div",{className:"flex flex-col items-center justify-center gap-3",children:/* @__PURE__ */m("div",{className:"flex items-center gap-3",children:/* @__PURE__ */m("div",{className:"space-y-1 text-center",children:[t&&/* @__PURE__ */m(U,{variant:"h4",align:"center",className:"line-clamp-2",children:t}),/* @__PURE__ */m("p",{className:x("text-sm font-medium",e?"text-muted-foreground":"text-foreground"),children:["Remaining Uploads: ",/* @__PURE__ */m("span",{className:"text-primary font-bold",children:n})]})]})})})})]})}var qt=Object.defineProperty,Lt=Object.getOwnPropertyNames,zt=(e,t)=>function(){return e&&(t=(0,e[Lt(e)[0]])(e=0)),t},jt=(e,t)=>{for(var r in t)qt(e,r,{get:t[r],enumerable:!0})};function $t(e){const t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Bt(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 Ht(e,t,r){const i=$t(e),n=$t(t),o=$t(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 Wt(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[Bt(4.0767416621*d-3.3077115913*c+.2309699292*u),Bt(h),Bt(p)]}var Vt,Gt=zt({"src/color-space.ts"(){}});function Xt(e,t){return(Math.max(e,t)+.05)/(Math.min(e,t)+.05)}function Yt(e,t,r,i,n=0){return new Vt(e,t,r,i,n)}var Kt=zt({"src/color.ts"(){Gt(),Vt=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=Ht(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=Xt(e,1),r=Xt(e,0),i=this.isDark?Yt(255,255,255,0,0):Yt(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 Qt(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 Jt(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 Zt(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 er(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=Jt(e,o,i.quality,a);if(0===l.length&&(l=Jt(e,o,i.quality,{...a,ignoreWhite:!1})),0===l.length&&(l=Jt(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}=Ht(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:Wt(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})=>Yt(t,r,i,n,e>0?n/e:0))}const d=Zt(e,o,i.quality);return d?[Yt(d[0],d[1],d[2],1,1)]:null}jt({},{computeFallbackColor:()=>Zt,createPixelArray:()=>Jt,extractPalette:()=>er,validateOptions:()=>Qt});var tr,rr=zt({"src/pipeline.ts"(){Kt(),Gt()}});jt({},{BrowserPixelLoader:()=>tr});var ir,nr,or,ar,sr,lr=zt({"src/loaders/browser.ts"(){tr=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}}}}}),dr=zt({"src/worker/worker-script.ts"(){ir="\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 cr(){return"undefined"!=typeof Worker}function ur(e,t,r){return new Promise((i,n)=>{if(r?.aborted)return void n(r.reason??new DOMException("Aborted","AbortError"));const o=ar++;sr.set(o,{resolve:i,reject:n});const a=()=>{sr.delete(o),n(r.reason??new DOMException("Aborted","AbortError"))};r?.addEventListener("abort",a,{once:!0});try{(function(){if(nr)return nr;if(!cr())throw new Error("Web Workers are not supported in this environment.");return or=URL.createObjectURL(new Blob([ir],{type:"application/javascript"})),(nr=new Worker(or)).onmessage=e=>{const{id:t,palette:r,error:i}=e.data,n=sr.get(t);if(n)if(sr.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})=>Yt(e,r,i,n,t>0?n/t:0));n.resolve(i)}},nr.onerror=e=>{for(const[,t]of sr)t.reject(new Error(e.message));sr.clear()},nr})().postMessage({id:o,pixels:e,maxColors:t})}catch(s){sr.delete(o),r?.removeEventListener("abort",a),n(s)}})}function hr(){nr&&(nr.terminate(),nr=null),or&&(URL.revokeObjectURL(or),or=null);for(const[,e]of sr)e.reject(/* @__PURE__ */new Error("Worker terminated"));sr.clear()}function pr(e,t,r){return(e<<10)+(t<<5)+r}jt({},{extractInWorker:()=>ur,isWorkerSupported:()=>cr,terminateWorker:()=>hr}),zt({"src/worker/manager.ts"(){Kt(),dr(),nr=null,or=null,ar=0,sr=/* @__PURE__ */new Map}}),rr(),rr(),Kt(),Yt(255,255,255,0),Yt(0,0,0,0);var mr=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[pr(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[pr(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}},gr=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 fr(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[pr(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[pr(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[pr(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 vr(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=fr(r,o);if(!a||!a[0])return;e.push(a[0]),a[1]&&(e.push(a[1]),i++)}}lr(),rr(),new tr;var wr=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[pr(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 mr(r,i,n,o,a,s,t)}(e,n),a=new gr((e,t)=>e.count()-t.count());a.push(o),vr(a,.75*t,n);const s=new gr((e,t)=>e.count()*e.volume()-t.count()*t.volume());for(;a.size();)s.push(a.pop());vr(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 br(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=D(l.data,n,o,4,4)}catch(c){console.warn("[media-intrinsics] blurhash encode failed:",c)}try{const e=function(e,t){const r=Qt(t??{}),i=t?.quantizer??wr,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 er(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 yr(e,t){return Object.hasOwn(e,t)}Kt();var{AbortController:xr}=globalThis,{AbortSignal:Sr}=globalThis,Cr=(e="Aborted",t)=>{const r=new DOMException(e,"AbortError");return null!=t&&yr(t,"cause")&&Object.defineProperty(r,"cause",{__proto__:null,configurable:!0,writable:!0,value:t.cause}),r},Tr=class extends Error{isNetworkError;cause;constructor(e,t){super(e),this.cause=t?.cause,this.cause&&yr(this.cause,"isNetworkError")?this.isNetworkError=this.cause.isNetworkError:this.isNetworkError=!1}},Fr=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 kr(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 _r={__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 Er(e){if(e.type)return e.type;const t=e.name?kr(e.name).extension?.toLowerCase():null;return t&&t in _r?_r[t]:"application/octet-stream"}function Mr(e){let t="";return e.replace(/[^A-Z0-9]/gi,e=>(t+=`-${function(e){return e.charCodeAt(0).toString(32)}(e)}`,"/"))+t}function Ur(e,t){return!0===e?Object.keys(t):Array.isArray(e)?e:[]}function Rr(e){return e<10?`0${e}`:e.toString()}function Ir(){const e=/* @__PURE__ */new Date;return`${Rr(e.getHours())}:${Rr(e.getMinutes())}:${Rr(e.getSeconds())}`}function Dr(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 Nr=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:Dr,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=Dr,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 Pr(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 Or(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=Pr(i,new RegExp(`%\\{${n}\\}`,"g"),e)}return i}var Ar=e=>{throw new Error(`missing string: ${e}`)},qr=class{locale;constructor(e,{onMissingKey:t=Ar}={}){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 Or(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 Or(r,t)}},Lr=class extends Error{name="UserFacingApiError"},zr=/* @__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}}),jr=/* @__PURE__ */t(e=>{var t=zr();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}}}),$r=/* @__PURE__ */t((e,t)=>{t.exports=jr()}),Br=Object.prototype.toString,Hr=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 Wr=/* @__PURE__ */e($r(),1),Vr=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}},Gr=(e,t,r)=>{const i=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=i,e};async function Xr(e,t){return new Promise((r,i)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const n=Wr.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 Vr)throw s.originalError;if(s instanceof TypeError&&!function(e){if(!e||(t=e,"[object Error]"!==Br.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(")"))||Hr.has(r)}(s))throw s;if(Gr(s,o,t),await t.shouldRetry(s)||(n.stop(),i(s)),await t.onFailedAttempt(s),!n.retry(s))throw n.mainError()}catch(l){Gr(l,o,t),a(),i(l)}}})})}var Yr=class extends Error{isAuthError;constructor(){super("Authorization required"),this.name="AuthError",this.isAuthError=!0}},Kr=class extends Error{statusCode;constructor({statusCode:e,message:t}){super(t),this.name="HttpError",this.statusCode=e}},Qr=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 Fr(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 Yr;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 Lr(t.message);throw new Kr({statusCode:e.status,message:r})}(a)}catch(o){if(o.isAuthError||"UserFacingApiError"===o.name||"AbortError"===o.name)throw o;throw new Tr(`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 Xr(async()=>{const r=this.uppy.getFile(e.id)?.serverToken;if(null!=r)return this.uppy.log(`Connecting to exiting websocket ${r}`),this.#w({file:e,queue:n(),signal:i});const o=await n().wrapPromiseFunction(async(...e)=>{try{return await this.#b(...e)}catch(t){if(t.isAuthError)throw new Vr(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 Vr(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.#w({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}}#b=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#w({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()},w=(t,r)=>{t?.id===e.id&&g(r)},b=()=>g(!0),y=()=>g(!1);this.uppy.on("file-removed",f),this.uppy.on("cancel-all",v),this.uppy.on("upload-pause",w),this.uppy.on("pause-all",b),this.uppy.on("resume-all",y),i=()=>{this.uppy.off("file-removed",f),this.uppy.off("cancel-all",v),this.uppy.off("upload-pause",w),this.uppy.off("pause-all",b),this.uppy.off("resume-all",y)},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 Xr(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?.()}}},Jr=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 qr([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(){}},Zr=class{#y;#x=[];constructor(e){this.#y=e}on(e,t){return this.#x.push([e,t]),this.#y.on(e,t)}remove(){for(const[e,t]of this.#x.splice(0))this.#y.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.#y.getFile(e)&&t()})}onPauseAll(e,t){this.on("pause-all",()=>{this.#y.getFile(e)&&t()})}onCancelAll(e,t){this.on("cancel-all",(...r)=>{this.#y.getFile(e)&&t(...r)})}onResumeAll(e,t){this.on("resume-all",()=>{this.#y.getFile(e)&&t()})}},ei={debug:()=>{},warn:()=>{},error:(...e)=>console.error(`[Uppy] [${Ir()}]`,...e)},ti={debug:(...e)=>console.debug(`[Uppy] [${Ir()}]`,...e),warn:(...e)=>console.warn(`[Uppy] [${Ir()}]`,...e),error:(...e)=>console.error(`[Uppy] [${Ir()}]`,...e)},ri=/* @__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}`}}),ii=/* @__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}}),ni=/* @__PURE__ */t((e,t)=>{var r=ii(),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}}),oi=/* @__PURE__ */e(ri(),1),ai=/* @__PURE__ */e(ni(),1),si={maxFileSize:null,minFileSize:null,maxTotalFileSize:null,maxNumberOfFiles:null,minNumberOfFiles:null,allowedFileTypes:null,requiredMetaFields:[]},li=class extends Error{isUserFacing;file;constructor(e,t){super(e),this.isUserFacing=t?.isUserFacing??!0,t?.file&&(this.file=t.file)}isRestriction=!0},di=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 li(`${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 li(this.getI18n()("aggregateExceedsSize",{sizeAllowed:(0,oi.default)(r),size:(0,oi.default)(i)}))}}validateSingleFile(e){const{maxFileSize:t,minFileSize:r,allowedFileTypes:i}=this.getOpts().restrictions;if(i&&!i.some(t=>t.includes("/")?!!e.type&&(0,ai.default)(e.type.replace(/;.*?$/,""),t):!("."!==t[0]||!e.extension)&&e.extension.toLowerCase()===t.slice(1).toLowerCase())){const t=i.join(", ");throw new li(this.getI18n()("youCanOnlyUploadFileTypes",{types:t}),{file:e})}if(t&&null!=e.size&&e.size>t)throw new li(this.getI18n()("exceedsSize",{size:(0,oi.default)(t),file:e.name??this.getI18n()("unnamed")}),{file:e});if(r&&null!=e.size&&e.size<r)throw new li(this.getI18n()("inferiorSize",{size:(0,oi.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 li(this.getI18n()("youHaveToAtLeastSelectX",{smart_count:t}))}getMissingRequiredMetaFields(e){const t=new li(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}}},ci=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.#C(t,r,e)}subscribe(e){return this.#S.add(e),()=>{this.#S.delete(e)}}#C(...e){this.#S.forEach(t=>{t(...e)})}},ui=/* @__PURE__ */t((e,t)=>{t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}}),hi=/* @__PURE__ */t((e,t)=>{var r="object"==typeof global&&global&&global.Object===Object&&global;t.exports=r}),pi=/* @__PURE__ */t((e,t)=>{var r=hi(),i="object"==typeof self&&self&&self.Object===Object&&self,n=r||i||Function("return this")();t.exports=n}),mi=/* @__PURE__ */t((e,t)=>{var r=pi();t.exports=function(){return r.Date.now()}}),gi=/* @__PURE__ */t((e,t)=>{var r=/\s/;t.exports=function(e){for(var t=e.length;t--&&r.test(e.charAt(t)););return t}}),fi=/* @__PURE__ */t((e,t)=>{var r=gi(),i=/^\s+/;t.exports=function(e){return e?e.slice(0,r(e)+1).replace(i,""):e}}),vi=/* @__PURE__ */t((e,t)=>{var r=pi().Symbol;t.exports=r}),wi=/* @__PURE__ */t((e,t)=>{var r=vi(),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}}),bi=/* @__PURE__ */t((e,t)=>{var r=Object.prototype.toString;t.exports=function(e){return r.call(e)}}),yi=/* @__PURE__ */t((e,t)=>{var r=vi(),i=wi(),n=bi(),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)}}),xi=/* @__PURE__ */t((e,t)=>{t.exports=function(e){return null!=e&&"object"==typeof e}}),Si=/* @__PURE__ */t((e,t)=>{var r=yi(),i=xi();t.exports=function(e){return"symbol"==typeof e||i(e)&&"[object Symbol]"==r(e)}}),Ci=/* @__PURE__ */t((e,t)=>{var r=fi(),i=ui(),n=Si(),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}}),Ti=/* @__PURE__ */t((e,t)=>{var r=ui(),i=mi(),n=Ci(),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 w(t){var r=l,i=d;return l=d=void 0,m=t,u=e.apply(i,r)}function b(e){var r=e-p;return void 0===p||r>=t||r<0||f&&e-m>=c}function y(){var e=i();if(b(e))return x(e);h=setTimeout(y,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?w(e):(l=d=void 0,u)}function S(){var e=i(),r=b(e);if(l=arguments,d=this,p=e,r){if(void 0===h)return function(e){return m=e,h=setTimeout(y,t),g?w(e):u}(p);if(f)return clearTimeout(h),h=setTimeout(y,t),w(p)}return void 0===h&&(h=setTimeout(y,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}}),Fi=/* @__PURE__ */t((e,t)=>{var r=Ti(),i=ui();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})}}),ki=/* @__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}}),_i={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"}};function Ei(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 Mi=/* @__PURE__ */e(Fi(),1),Ui=/* @__PURE__ */e(ki(),1),Ri={totalProgress:0,allowNewUpload:!0,error:null,recoveredState:null},Ii=class e{static VERSION="5.2.0";#T=Object.create(null);#F;#k;#_=(0,Ui.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=_i;const r={id:"uppy",autoProceed:!1,allowMultipleUploadBatches:!0,debug:!1,restrictions:si,meta:{},onBeforeFileAdded:(e,t)=>!Object.hasOwn(t,e.id),onBeforeUpload:e=>e,store:new ci,logger:ei,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=ti),this.log(`Using Core v${e.VERSION}`),this.i18nInit(),this.store=this.opts.store,this.setState({...Ri,plugins:{},files:{},currentUploads:{},capabilities:{uploadProgress:Ei(),individualCancellation:!0,resumableUploads:!1},meta:{...this.opts.meta},info:[]}),this.#F=new di(()=>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 qr([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,...Ri})}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({...Ri,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}#D(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.#D(r)||(t=!1);return t}#P(e){const{allowNewUpload:t}=this.getState();if(!1===t){const t=new li(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=Er(t),i=function(e,t){return t.name?t.name:"image"===e.split("/")[0]?`${e.split("/")[0]}.${e.split("/")[1]}`:"noname"}(r,t),n=kr(i).extension,o=function(e,t){if(function(e){return!(!e.isRemote||!e.remote)&&new Set(["box","dropbox","drive","facebook","unsplash"]).has(e.remote.provider)}(e))return e.id;const r=Er(e);return function(e,t){let r=t||"uppy";return"string"==typeof e.name&&(r+=`-${Mr(e.name.toLowerCase())}`),void 0!==e.type&&(r+=`-${e.type}`),e.meta&&"string"==typeof e.meta.relativePath&&(r+=`-${Mr(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))}#q(e){let{files:t}=this.getState(),r={...t};const i=[],n=[];for(const a of e)try{let e=this.#O(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 li(this.i18n("noDuplicates",{fileName:e.name??this.i18n("unnamed")}),{file:e});if(!1===s&&!o)throw new li("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.#q([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.#q(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")}#z(){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#j(){const e=this.#z(),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.#j();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(Ri)}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()};#W(){const e=this.#V();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,Mi.default)(()=>this.#W(),500,{leading:!0,trailing:!0});[Symbol.for("uppy test: updateTotalProgress")](){return this.#W()}#V(){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.#D(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.#T?this.#T[r.type].push(r):this.#T[r.type]=[r],r.install(),this.emit("plugin-added",r),this}getPlugin(e){for(const t of Object.values(this.#T)){const r=t.find(t=>t.id===e);if(null!=r)return r}}[Symbol.for("uppy test: getPlugins")](e){return this.#T[e]}iteratePlugins(e){Object.values(this.#T).flat(1).forEach(e)}removePlugin(e){this.log(`Removing plugin ${e.id}`),this.emit("plugin-remove",e),e.uninstall&&e.uninstall();const t=this.#T[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--;)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}})}#K(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.#K(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.#K(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.#T.uploader?.length||this.log("No uploader type plugins are used","warning");let{files:e}=this.getState();if(this.#z().length>0){const t=await this.#j();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 li(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 Di({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 Ni=new TextEncoder,Pi={name:"HMAC",hash:"SHA-256"};async function Oi(e){const{subtle:t}=globalThis.crypto;return t.digest(Pi.hash,Ni.encode(e))}function Ai(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 qi(e,t){const{subtle:r}=globalThis.crypto;return r.sign(Pi,await async function(e){const{subtle:t}=globalThis.crypto;return t.importKey("raw","string"==typeof e?Ni.encode(e):e,Pi,!1,["sign"])}(e),Ni.encode(t))}async function Li({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,Ai(await Oi(Di({CanonicalUri:u,CanonicalQueryString:f.search.slice(1),SignedHeaders:{host:c},HashedPayload:h})))].join("\n"),w=Ai(await qi(await qi(await qi(await qi(await qi(`AWS4${t}`,m),o),d),"aws4_request"),v));return f.searchParams.set("X-Amz-Signature",w),f}var zi={getChunkSize:e=>Math.ceil(e.size/1e4),onProgress(){},onPartComplete(){},onSuccess(){},onError(e){throw e}},ji=Symbol("pausing upload, not an actual error"),$i=class{options;#Q=new xr;#J=[];#Z=[];#ee;#te;#re=!1;#ie;#ne;#oe;#ae;#se=e=>e?.cause===ji?null:this.#ie(e);#le=1e4;#de=5242880;constructor(e,t){this.options={...zi,...t},this.options.getChunkSize??=zi.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.#Q.signal).then(this.#ne,this.#se),this.#re=!0}#pe(){this.options.companionComm.resumeUploadFile(this.#te,this.#J,this.#Q.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.#Q.abort(),this.options.companionComm.abortFileUpload(this.#te).catch(e=>this.options.log(e))}start(){this.#re?(this.#Q.signal.aborted||this.#Q.abort(ji),this.#Q=new xr,this.#pe()):this.#ae?(this.options.companionComm.restoreUploadFile(this.#te,{uploadId:this.options.uploadId,key:this.options.key}),this.#pe()):this.#$()}pause(){this.#Q.abort(ji),this.#Q=new xr}abort(e){e?.really?this.#me():this.pause()}[Symbol.for("uppy test: getChunkState")](){return this.#Z}};function Bi(e){if(e?.aborted)throw Cr("The operation was aborted",{cause:e.reason})}function Hi(e){const t=new URL(e);return t.search="",t.hash="",t.href}var Wi=class{#ge;#fe=/* @__PURE__ */new WeakMap;#ve;#we;#be;#ye;#xe;#Se;#Ce;#Te;#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.#we=t.wrapPromiseFunction(e.signPart)),"listParts"in e&&(this.#ye=t.wrapPromiseFunction(e.listParts)),"completeMultipartUpload"in e&&(this.#Te=t.wrapPromiseFunction(e.completeMultipartUpload,{priority:1})),"retryDelays"in e&&(this.#Ce=e.retryDelays??[]),"uploadPartBytes"in e&&(this.#ke=t.wrapPromiseFunction(e.uploadPartBytes,{priority:1/0})),"getUploadParameters"in e&&(this.#be=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.#be(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??Hi(n),bucket:o?.bucket,key:h}}async uploadFile(e,t,r){if(Bi(r),1===t.length&&!t[0].shouldUseMultipart)return this.#Me(e,t[0],r);const{uploadId:i,key:n}=await this.getUploadId(e,r);Bi(r);try{const o=await Promise.all(t.map((t,i)=>this.uploadChunk(e,i+1,t,r)));return Bi(r),await this.#Te(this.#_e(e),{key:n,uploadId:i,parts:o,signal:r},r).abortOn(r)}catch(o){throw o?.cause!==ji&&"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(Bi(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);Bi(r);const o=await this.#ye(this.#_e(e),{uploadId:i,key:n,signal:r},r).abortOn(r);Bi(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 Bi(r),this.#Te(this.#_e(e),{key:n,uploadId:i,parts:a,signal:r},r).abortOn(r)}async uploadChunk(e,t,r,i){Bi(i);const{uploadId:n,key:o}=await this.getUploadId(e,i),a=this.#Ce.values(),s=this.#Ce.values(),l=()=>{const e=a.next();return null==e||e.done?null:e.value};for(;;){Bi(i);const a=r.getData(),{onProgress:c,onComplete:u}=r;let h;try{h=await this.#we(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}Bi(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 Vi(e){if(e?.error){const t=new Error(e.message);throw Object.assign(t,e.error),t}return e}function Gi(e){const t=e.Expiration;if(t){const e=Math.floor((new Date(t)-Date.now())/1e3);if(e>9)return e}}function Xi({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 Yi={allowedMetaFields:!0,limit:6,getTemporarySecurityCredentials:!1,shouldUseMultipart:e=>(e.size||0)>104857600,retryDelays:[0,1e3,3e3,5e3]},Ki=class e extends Jr{static VERSION="5.1.0";#Ue;#Re;requests;uploaderEvents;uploaders;constructor(t,r){super(t,{...Yi,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 Nr(this.opts.limit),this.#Ue=new Wi(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 Qr(this.uppy,{pluginId:this.id,provider:"AWS",companionUrl:this.opts.endpoint,companionHeaders:this.opts.headers,companionCookiesRule:this.opts.cookiesRule}):("headers"in e&&this.#De(),"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"),Bi(t);const r=Ur(this.opts.allowedMetaFields,e.meta),i=Xi({meta:e.meta,allowedMetaFields:r});return this.#Re.post("s3/multipart",{filename:e.name,type:e.type,metadata:i},{signal:t}).then(Vi)}listParts(e,{key:t,uploadId:r,signal:i},n){i??=n,this.#Ne("listParts"),Bi(i);const o=encodeURIComponent(t);return this.#Re.get(`s3/multipart/${encodeURIComponent(r)}?key=${o}`,{signal:i}).then(Vi)}completeMultipartUpload(e,{key:t,uploadId:r,parts:i,signal:n},o){n??=o,this.#Ne("completeMultipartUpload"),Bi(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(Vi)}#Pe;async#Oe(e){if(Bi(e?.signal),null==this.#Pe){const{getTemporarySecurityCredentials:t}=this.opts;!0===t?(this.#Ne("getTemporarySecurityCredentials"),this.#Pe=this.#Re.get("s3/sts",e).then(Vi)):this.#Pe=t(e),this.#Pe=await this.#Pe,setTimeout(()=>{this.#Pe=null},500*(Gi(this.#Pe.credentials)||0))}return this.#Pe}async createSignedURL(e,t){const r=await this.#Oe(t),i=Gi(r.credentials)||604800,{uploadId:n,key:o,partNumber:a}=t;return{method:"PUT",expires:i,fields:{},url:`${await Li({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"),Bi(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(Vi)}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(Vi)}getUploadParameters(e,t){this.#Ne("getUploadParameters");const{meta:r}=e,{type:i,name:n}=r,o=Xi({meta:r,allowedMetaFields:Ur(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(Bi(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(Cr())}),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 $i(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 Zr(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()})}#qe(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.#ze(!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.#qe(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.#ze(!0),n};#De=()=>{this.#Re?.setCompanionHeaders(this.opts.headers)};#ze=e=>{const{capabilities:t}=this.uppy.getState();this.uppy.setState({capabilities:{...t,resumableUploads:e}})};#je=()=>{this.#ze(!0)};install(){this.#ze(!0),this.uppy.addPreProcessor(this.#De),this.uppy.addUploader(this.#Le),this.uppy.on("cancel-all",this.#je)}uninstall(){this.uppy.removePreProcessor(this.#De),this.uppy.removeUploader(this.#Le),this.uppy.off("cancel-all",this.#je)}},Qi="undefined"!=typeof window&&(window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB),Ji=!!Qi,Zi="uppy-blobs",en="files",tn=864e5,rn=1048576;function nn(e){const t=Qi.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(en,{keyPath:"id"}).createIndex("store","store",{unique:!1}),t.oldVersion<3){const e=i.objectStore(en);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()+tn,t.update(r)}}(e)}i.oncomplete=()=>{e(r)}},t.onsuccess=t=>{e(t.target.result)},t.onerror=r})}function on(e){return new Promise((t,r)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=r})}var an=!1,sn=class e{#$e;opts;name;static isSupported;constructor(t){this.opts={dbName:Zi,storeName:"default",expires:tn,maxFileSize:10*rn,maxTotalSize:300*rn,...t},this.name=this.opts.storeName;const r=async()=>{const e=await nn(this.opts.dbName);return this.#$e=e,e};an?this.#$e=r():(an=!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 on((await this.#$e).transaction([en],"readonly").objectStore(en).index("store").getAll(IDBKeyRange.only(this.name)));return Object.fromEntries(e.map(e=>[e.fileID,e.data]))}async get(e){const{data:t}=await on((await this.#$e).transaction([en],"readonly").objectStore(en).get(this.key(e)));return{id:t.fileID,data:t.data}}async getSize(){const e=(await this.#$e).transaction([en],"readonly").objectStore(en).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 on((await this.#$e).transaction([en],"readwrite").objectStore(en).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 on((await this.#$e).transaction([en],"readwrite").objectStore(en).delete(this.key(e)))}static async cleanup(){const e=await nn(Zi),t=e.transaction([en],"readwrite").objectStore(en).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 ln(e){try{return JSON.parse(e)}catch{return null}}sn.isSupported=Ji;var dn="uppyState:",cn=class{opts;name;#Be;constructor(e){var t;this.opts={expires:864e5,throttleTime:500,...e},this.name=(t=e.storeName,`${dn}${t}`),this.#Be=0===this.opts.throttleTime?this.save:(0,Mi.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(dn)&&e.push(t)}const t=Date.now();e.forEach(e=>{const r=localStorage.getItem(e);if(!r)return;const i=ln(r);i?.expires&&i.expires<t&&localStorage.removeItem(e)})}();const e=localStorage.getItem(this.name);if(!e)return;const t=ln(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()}},un="undefined"!=typeof navigator&&"serviceWorker"in navigator,hn=class{#$e;name;static isSupported;constructor(e){this.#$e=new Promise((e,t)=>{un?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})}};hn.isSupported=un;var pn={expires:864e5,serviceWorker:!1},mn=class e extends Jr{static VERSION="5.2.1";#We;#Ve;#Ge;static[Symbol.for("uppy test: throttleTime")];constructor(t,r){super(t,{...pn,...r}),this.type="debugger",this.id=this.opts.id||"GoldenRetriever",this.#We=new cn({expires:this.opts.expires,storeName:t.getID(),throttleTime:e[Symbol.for("uppy test: throttleTime")]??void 0}),this.opts.serviceWorker&&(this.#Ve=new hn({storeName:t.getID()})),this.#Ge=new sn({expires:this.opts.expires,...this.opts.indexedDB||{},storeName:t.getID()})}async#Xe(){const e=this.#We.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.#Ke()]),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.#Qe(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.#We.get();this.#We.set({...r??{currentUploads:{},files:{}},...t,pluginData:{...r?.pluginData,...e}})};async#Ye(){if(!this.#Ve)return{};try{const e=await this.#Ve.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#Ke(){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#Qe(e){await Promise.all(e.map(async e=>{try{await Promise.all([this.#Ve?.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.#Qe(e)}#Ze=async e=>{const{id:t,data:r,isRemote:i}=e;i||null==r||await Promise.all([this.#Ve?.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.#Qe(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 gn(){const e=Ve(),t=S(),r=l(null),i=l(null),n=l({}),a=l(0),s=l(null),d=l({}),c=l(void 0),u=l({});o(()=>{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 h=g(()=>{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},[]),p=g(()=>{if(!r.current){const t=new Ii({autoProceed:!0}).use(mn,{id:"GoldenRetriever",expires:864e5,serviceWorker:!1}).use(Ki,{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 n=t.meta.uid;e.getState().setUploadState(n,{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=i.current;if(s){const t=(o-s.time)/1e3;if(t>=.5){const r=Math.max(0,(a-s.bytes)/t),n=s.speed>0?.7*s.speed+.3*r:r;i.current={time:o,bytes:a,speed:n},e.getState().setUploadSpeedBps(n)}}else i.current={time:o,bytes:a,speed:0}}),t.on("upload-success",r=>{if(!r)return;const o=r.meta.uid,a=r.meta.contentId,s=r.meta.key,l=r.meta.uploadStartedAt;(async()=>{try{const e=await fetch(T.UPLOAD_COMPLETE,{method:"POST",headers:h(),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(o,{status:"error",error:d instanceof Error?d.message:String(d)}),pe(d instanceof Error?d:new Error(String(d)),{component:"useUpload",tags:["upload","complete"],extra:{uid:o,contentId:a}}),void(a&&fetch(T.UPLOAD_FAIL,{method:"POST",headers:h(),body:JSON.stringify({contentId:a})}).catch(()=>{}))}e.getState().setUploadState(o,{status:"success",contentId:a}),delete n.current[o];try{t.removeFile(r.id)}catch{}Object.values(e.getState().uploadStates).every(e=>"success"===e.status||"error"===e.status)&&(i.current=null,e.getState().setUploadSpeedBps(0))})()}),t.on("upload-error",(t,r)=>{if(!t)return;const n=t.meta.uid,o=t.meta.contentId;e.getState().setUploadState(n,{status:"error",error:r instanceof Error?r.message:String(r)}),o&&fetch(T.UPLOAD_FAIL,{method:"POST",headers:h(),body:JSON.stringify({contentId:o})}).catch(()=>{}),Object.values(e.getState().uploadStates).every(e=>"success"===e.status||"error"===e.status)&&(i.current=null,e.getState().setUploadSpeedBps(0))}),t.on("restored",()=>{const{eventId:r}=e.getState(),i=[],o={},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}n.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&&(o[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,...o},uploadStates:{...e.uploadStates,...a},hasStarted:!0,showRestoreDialog:!0,restoredUids:i.map(e=>e.uid)}))}),r.current=t}return r.current},[e,h]);o(()=>{p()},[p]);const m=g(async(t,r)=>{const{eventId:i,groupId:o,captions:l,originalFiles:u,trimRanges:m,cropSelections:g,activeFilters:f,skipUploadFilters:v,perFileFilterSkipped:w}=e.getState(),b=u[t];if(!b)return!1;const y=p();try{e.getState().setUploadState(t,{status:"creating",bytesUploaded:0,bytesTotal:b.size,error:void 0});const u=ze(b)?"VIDEO":"IMAGE",p=await async function(e){const t=e.type.trim().toLowerCase(),r=e.name.toLowerCase(),i=Ae.test(r),n=Le.test(r),o=qe.test(r);if(t&&"application/octet-stream"!==t&&!(t.startsWith("image/")&&i||t.startsWith("video/")&&n||t.startsWith("image/")&&o))return t;try{const t=new Uint8Array(await e.slice(0,12).arrayBuffer());if(82===t[0]&&73===t[1]&&70===t[2]&&70===t[3]){if(87===t[8]&&69===t[9]&&66===t[10]&&80===t[11])return"image/webp";if(65===t[8]&&86===t[9]&&73===t[10]&&32===t[11])return"video/x-msvideo"}if(255===t[0]&&216===t[1]&&255===t[2])return"image/jpeg";if(137===t[0]&&80===t[1]&&78===t[2]&&71===t[3])return"image/png";if(71===t[0]&&73===t[1]&&70===t[2]&&56===t[3])return"image/gif";if(26===t[0]&&69===t[1]&&223===t[2]&&163===t[3])return r.endsWith(".webm")?"video/webm":"video/x-matroska";const n=102===t[4]&&116===t[5]&&121===t[6]&&112===t[7],o=109===t[4]&&111===t[5]&&111===t[6]&&118===t[7],a=109===t[4]&&100===t[5]&&97===t[6]&&116===t[7];if(n||o||a){if(n){const e=String.fromCharCode(t[8]??0,t[9]??0,t[10]??0,t[11]??0).trim().toLowerCase();if("heic"===e||"heix"===e||"mif1"===e)return"image/heic";if("qt "===e)return"video/quicktime"}return i&&(r.endsWith(".mov")||r.endsWith(".qt"))?"video/quicktime":"video/mp4"}}catch{}return t||"application/octet-stream"}(b);if(a.current!==r)return!1;const x=d.current[t]??=await async function(e){try{return await(t=ze(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,...br(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 createImageBitmap(e);try{return{dimension:{width:t.width,height:t.height},...br(t,t.width,t.height)}}finally{t.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}(b);if(a.current!==r)return!1;const S=m[t],C=g[t],F=f.length>0?w[t]??v:void 0,k=await fetch(T.UPLOAD_CREATE,{method:"POST",headers:h(),signal:s.current?.signal,body:JSON.stringify({eventId:i,groupId:o,uid:t,type:u,fileName:b.name,fileSize:b.size,rawContentType:p,caption:l[t],trimInfo:S?{start:S.startTime,end:S.endTime}:void 0,cropInfo:C,dimension:x.dimension,blurhash:x.blurhash,colors:x.colors,duration:x.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(a.current!==r)return fetch(T.UPLOAD_ABORT,{method:"POST",headers:h(),body:JSON.stringify({contentId:_,key:E})}).catch(()=>{}),!1;const U=n.current[t];if(U&&y.getFile(U))try{y.removeFile(U)}catch{}const R=y.addFile({name:b.name,type:p,data:b,meta:{uid:t,userId:c.current,contentId:_,key:E,uploadUrl:M,rawContentType:p,eventId:i,groupId:o,type:u,caption:l[t],uploadStartedAt:Date.now()}});return n.current[t]=R,!0}catch(x){return a.current!==r||x instanceof DOMException&&"AbortError"===x.name||(e.getState().setUploadState(t,{status:"error",error:x instanceof Error?x.message:String(x)}),pe(x instanceof Error?x:new Error(String(x)),{component:"useUpload",tags:["upload","create"],extra:{uid:t}})),!1}},[e,p,h]),f=g(async()=>{const{selectedFiles:t,oversizedUids:r}=e.getState(),i=t.filter(({uid:e})=>!r[e]);if(0===i.length)return;const n=++a.current;s.current=new AbortController;const o=p();e.getState().setHasStarted(!0);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})=>m(e,n)),a.current===n?0===o.getFiles().length?(P.error("Could not start upload. Please try again."),void e.getState().setHasStarted(!1)):void(await o.upload()):void 0},[e,p,m]),v=g(()=>{a.current++,s.current?.abort(),i.current=null,n.current={},d.current={},r.current?.cancelAll(),e.getState().resetUploader()},[e]),w=g(t=>{const r=p();i.current=null;const o=n.current[t],s=o?r.getFile(o):void 0;if(s)return e.getState().setUploadState(t,{status:"uploading",bytesUploaded:0,bytesTotal:s.size??0,error:void 0}),void r.retryUpload(o).catch(r=>{e.getState().setUploadState(t,{status:"error",error:r instanceof Error?r.message:String(r)})});m(t,a.current)},[e,p,m]),b=g(()=>{Object.entries(e.getState().uploadStates).filter(([,e])=>"error"===e.status).map(([e])=>e).forEach(e=>w(e))},[e,w]);return o(()=>()=>{a.current++,s.current?.abort(),r.current?.cancelAll(),r.current?.destroy(),r.current=null},[]),{startUpload:f,cancelUpload:v,retryUpload:w,retryAllUploads:b,resumeRestoredUpload:g(()=>{const t=p();s.current=new AbortController,e.setState({showRestoreDialog:!1,restoredUids:[]}),t.upload()},[e,p]),discardRestoredUpload:g(()=>{const t=p(),{restoredUids:r}=e.getState();r.forEach(r=>{const i=n.current[r];if(i){try{t.removeFile(i)}catch{}delete n.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,p])}}function fn({eventSlug:e,event:t}){const r=S(),i=_(),n=r.props?.organizationId,a=r.user,s=Ve(),d=We(e=>e.selectedFiles),u=We(e=>e.hasStarted),h=We(e=>e.oversizedUids),p=We(e=>e.showOversizedModal),f=We(e=>e.activeFilters),x=We(e=>e.showFilterChoice),k=We(e=>e.skipUploadFilters),E=We(e=>e.showRestoreDialog),M=We(e=>e.restoredUids),[U,R]=c(!1),[D,N]=c(!1),[O,q]=c({}),[L,z]=c(!0);o(()=>{if(!a||!n)return;let t=!1;return z(!0),b.get(T.GET_UPLOAD_COUNT,{searchParams:{eventSlug:e},headers:{"x-org-id":n,...a.token?{Authorization:`Bearer ${a.token}`}:{}}}).json().then(e=>{t||q(e?.data?.uploadCount??{})}).catch(()=>{t||P.error("Failed to fetch upload count")}).finally(()=>{t||z(!1)}),()=>{t=!0}},[a,n,e]);const j=!t.uploadLimit||t.uploadLimit<=0,$=(O[C.APPROVED]??0)+(O[C.IN_REVIEW]??0),B=j?1/0:Math.max(0,(t.uploadLimit??0)-$),H=L,W=j?"Unlimited":B,V=Math.min(B,100),G=!(t.status===F.OPEN)||u||H,Y=t.enableVideo?[...re,...ie]:re,K=!!t.ada,Q=function({effectiveFileLimit:e,eventSlug:t}){const r=Ve();return g(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:ee(),file:e})),d=Math.max(0,e-a.length),c=l.slice(0,d),u=l.length-c.length;u>0&&(P.warn(`${u} file${u>1?"s":""} not added — you've reached your upload limit.`),me("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=ze(e),r=t?w:y;return e.size>r?t?"video":"image":void 0}(t);r&&(h[e]=r)}),Object.keys(h).length>0&&(r.getState().addOversizedUids(h),me("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})=>{ze(t)&&de(()=>{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:V,eventSlug:e}),{startUpload:J,cancelUpload:Z,retryUpload:se,retryAllUploads:le,resumeRestoredUpload:ce,discardRestoredUpload:ue}=gn(),he=g(()=>{N(!1),u?Z():s.getState().resetUploader()},[u,Z,s]);!function(e){const t=Ve(),r=S(),i=r.props?.organizationId,n=r.user?.token;o(()=>{if(!e||!i)return;let r=!1;return b.get(T.GET_POST_PROCESSING_SETTINGS,{searchParams:{eventId:e},headers:{"x-org-id":i,...n?{Authorization:`Bearer ${n}`}:{}}}).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=>{pe(e instanceof Error?e:/* @__PURE__ */new Error("Failed to load upload filters"),{component:"useUploadFilters",tags:["upload","filters"]})}),()=>{r=!0}},[e,i,n,t])}(t._id?String(t._id):void 0),o(()=>{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],s.getState().removeFile(r)},3e3))})};t(s.getState());const r=s.subscribe(t);return()=>{r(),Object.values(e).forEach(clearTimeout)}},[s]),o(()=>{0===d.length&&u&&s.getState().resetUploader()},[d.length,u,s]),o(()=>{if(!u)return;const e=e=>{Object.values(s.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,s]);const ge=g(e=>s.getState().removeFile(e),[s]),fe=g(()=>{if(!K)return!0;const e=s.getState(),t=e.selectedFiles.some(({uid:t})=>!e.oversizedUids[t]&&!e.captions[t]?.trim());return t&&P.warn("This event requires a caption on every file before uploading."),!t},[K,s]),ve=g(()=>{fe()&&(Object.keys(s.getState().oversizedUids).length>0?s.getState().setShowOversizedModal(!0):J())},[s,J,fe]),we=g(()=>{!a||a.tcAccepted?ve():R(!0)},[a,ve]),be=g(()=>{s.getState().removeOversizedFiles(),fe()&&J()},[s,J,fe]),[ye,xe]=c(!1),Se=l(0),Ce=G||d.length>=V;/* @__PURE__ */
|
|
77
77
|
return m("div",{className:"bg-background relative min-h-screen px-3 pb-9 lg:px-0",onDragEnter:e=>{e.preventDefault(),Ce||(Se.current+=1,xe(!0))},onDragOver:e=>e.preventDefault(),onDragLeave:()=>{Se.current=Math.max(0,Se.current-1),0===Se.current&&xe(!1)},onDrop:g(e=>{if(e.preventDefault(),Se.current=0,xe(!1),Ce)return;const t=e.dataTransfer?.files;t&&t.length>0&&Q(Array.from(t))},[Ce,Q]),children:[ye&&/* @__PURE__ */m("div",{className:"border-primary bg-background/90 fixed inset-0 z-2003 flex items-center justify-center border-4 border-dashed",children:/* @__PURE__ */m("p",{className:"text-primary text-2xl font-semibold",children:"Drop to add files"})}),
|
|
78
78
|
/* @__PURE__ */m("div",{className:"mx-auto max-w-4xl space-y-6",children:[
|
|
79
|
-
/* @__PURE__ */m(At,{uploadDisabled:G,eventName:t.name,isQuotaLoading:H,remainingUploads:W}),!t.enableVideo&&/* @__PURE__ */m("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===d.length&&!u&&/* @__PURE__ */m(
|
|
79
|
+
/* @__PURE__ */m(At,{uploadDisabled:G,eventName:t.name,isQuotaLoading:H,remainingUploads:W}),!t.enableVideo&&/* @__PURE__ */m("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===d.length&&!u&&/* @__PURE__ */m(Nt,{enabledFileTypes:Y,disabled:G,onFileSelect:Q,selectedCount:d.length,maxCount:V,enableVideo:t.enableVideo})]}),d.length>0&&/* @__PURE__ */m("div",{className:"mx-auto mt-8 w-full max-w-full pb-36 sm:px-0 md:pb-24",children:[x&&f.length>0&&!u&&/* @__PURE__ */m("div",{className:"border-border bg-card mb-4 flex items-center gap-3 rounded-lg border p-3",children:[/* @__PURE__ */m(te,{checked:!k,onChange:e=>{s.getState().setSkipUploadFilters(!e);const t={};e||d.forEach(({uid:e})=>{t[e]=!0}),s.setState({perFileFilterSkipped:t})},label:"Apply filters"}),/* @__PURE__ */m("span",{className:"text-muted-foreground -ml-1 text-sm",children:"— upload with filters applied"})]}),
|
|
80
80
|
/* @__PURE__ */m("div",{className:"flex items-center justify-between py-2",children:[/* @__PURE__ */m("p",{className:"text-muted-foreground text-sm font-medium",children:[d.length," selected"]}),!u&&d.length<V&&/* @__PURE__ */m(Ot,{enabledFileTypes:Y,disabled:G,onFileSelect:Q})]}),
|
|
81
|
-
/* @__PURE__ */m("div",{className:"grid grid-cols-1 gap-4 py-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:d.map(({uid:e,file:t})=>/* @__PURE__ */m(Ut,{uid:e,file:t,onRemove:ge,disabled:u,adaRequired:K,onRetry:se},e))}),!u&&d.length<V&&/* @__PURE__ */m(
|
|
82
|
-
/* @__PURE__ */m(It,{selectedCount:d.length,onUpload:we,onCancel:()=>
|
|
81
|
+
/* @__PURE__ */m("div",{className:"grid grid-cols-1 gap-4 py-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:d.map(({uid:e,file:t})=>/* @__PURE__ */m(Ut,{uid:e,file:t,onRemove:ge,disabled:u,adaRequired:K,onRetry:se},e))}),!u&&d.length<V&&/* @__PURE__ */m(Pt,{enabledFileTypes:Y,disabled:G,onFileSelect:Q}),!u&&/* @__PURE__ */m(I,{className:"mt-2 w-full gap-2",onClick:we,disabled:G||0===d.length,children:[/* @__PURE__ */m(A,{className:"size-4"}),"Upload"]}),
|
|
82
|
+
/* @__PURE__ */m(It,{selectedCount:d.length,onUpload:we,onCancel:()=>N(!0),onRetryAll:le,uploadDisabled:G||0===d.length})]}),!u&&/* @__PURE__ */m("div",{className:"mx-auto mt-12 max-w-4xl text-center",children:/* @__PURE__ */m(I,{onClick:()=>i(v.GALLERY(e)),children:"View gallery"})}),
|
|
83
83
|
/* @__PURE__ */m(ne,{open:p,oversizedUids:h,onClose:()=>s.getState().setShowOversizedModal(!1),onRemoveAndUpload:be}),
|
|
84
84
|
/* @__PURE__ */m(oe,{open:E,count:M.length,onResume:ce,onDiscard:ue}),
|
|
85
|
-
/* @__PURE__ */m(X,{open:D,onOpenChange:
|
|
85
|
+
/* @__PURE__ */m(X,{open:D,onOpenChange:N,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:()=>N(!1),onConfirm:he}),
|
|
86
86
|
/* @__PURE__ */m(ae,{open:U,onClose:()=>R(!1),onSuccess:()=>{R(!1),ve()}})]})}var vn=()=>{const{eventSlug:e}=M(),t=k(),r=_(),{loadingUser:i,user:n}=S();o(()=>{i||n||r("/auth/login",{state:{referrer:t.pathname}})},[i,n]);const{loading:a,event:s}=O({eventSlug:e}),d=l(ee());return a||s&&s.status!==F.CLOSED?/* @__PURE__ */m("div",s&&e?{className:"bg-background mx-auto min-h-screen pt-16",children:/* @__PURE__ */m(He,{eventId:String(s._id),groupId:d.current,children:/* @__PURE__ */m(fn,{eventSlug:e,event:s})})}:{className:"bg-background min-h-screen"}):/* @__PURE__ */m("div",{className:"bg-background mx-auto min-h-[80] pt-16 pb-36",children:/* @__PURE__ */m(se,{event:s,locationState:t?.state})})};export{vn as default};
|