@masters-union/union-stack 0.3.14 → 0.3.15

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.
@@ -1,4 +1,4 @@
1
- "use strict";var UnionStack=(()=>{var W=Object.defineProperty,$e=Object.defineProperties,Ue=Object.getOwnPropertyDescriptor,Ie=Object.getOwnPropertyDescriptors,Re=Object.getOwnPropertyNames,re=Object.getOwnPropertySymbols;var ne=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable;var oe=(n,e,t)=>e in n?W(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,C=(n,e)=>{for(var t in e||(e={}))ne.call(e,t)&&oe(n,t,e[t]);if(re)for(var t of re(e))Te.call(e,t)&&oe(n,t,e[t]);return n},I=(n,e)=>$e(n,Ie(e));var q=(n,e)=>()=>(n&&(e=n(n=0)),e);var se=(n,e)=>{for(var t in e)W(n,t,{get:e[t],enumerable:!0})},Pe=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Re(e))!ne.call(n,r)&&r!==t&&W(n,r,{get:()=>e[r],enumerable:!(i=Ue(e,r))||i.enumerable});return n};var Me=n=>Pe(W({},"__esModule",{value:!0}),n);function De(){if(document.getElementById(he))return;let n=(t,i)=>{let r=document.createElement("link");r.rel="preconnect",r.href=t,i&&(r.crossOrigin="anonymous"),document.head.appendChild(r)};n("https://fonts.googleapis.com"),n("https://fonts.gstatic.com",!0);let e=document.createElement("link");e.id=he,e.rel="stylesheet",e.href=ze,document.head.appendChild(e)}function me(){if(typeof document=="undefined"||(De(),document.getElementById(ue)))return;let n=document.createElement("style");n.id=ue,n.textContent=Ne,document.head.appendChild(n)}function fe(n){var i,r,o,s,a;let t=((n==null?void 0:n.mode)||"light")==="dark"?Oe:je;return{"--us-primary":(i=n==null?void 0:n.primary)!=null?i:t.primary,"--us-on-primary":t.onPrimary,"--us-bg":(r=n==null?void 0:n.background)!=null?r:t.background,"--us-fg":(o=n==null?void 0:n.foreground)!=null?o:t.foreground,"--us-muted":t.muted,"--us-border":(s=n==null?void 0:n.border)!=null?s:t.border,"--us-subtle":"color-mix(in srgb, var(--us-fg) 5%, var(--us-bg))","--us-overlay":"color-mix(in srgb, var(--us-fg) 9%, var(--us-bg))","--us-border-strong":"color-mix(in srgb, var(--us-fg) 18%, var(--us-border))","--us-elevated":t.elevated,"--us-raised":t.raised,"--us-accent":t.accent,"--us-success":t.success,"--us-danger":t.danger,"--us-radius":(a=n==null?void 0:n.radius)!=null?a:"12px"}}var ue,he,ze,je,Oe,Ne,ge=q(()=>{"use strict";ue="unionstack-picker-styles",he="unionstack-picker-fonts",ze="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap";je={primary:"#494bd6",onPrimary:"#ffffff",background:"#fdfbff",foreground:"#1b1b21",muted:"#5e5c6e",subtle:"#f3f1fa",border:"#e4e1ee",borderStrong:"#c8c5d4",elevated:"#ffffff",overlay:"#eceaf4",raised:"#ffffff",accent:"#b35a00",success:"#2c9a5b",danger:"#ba1a1a"},Oe={primary:"#f4f4f5",onPrimary:"#18181b",background:"#0a0a0c",foreground:"#f4f4f5",muted:"#8b8b93",subtle:"#161618",border:"#2a2a2e",borderStrong:"#3f3f46",elevated:"#141416",overlay:"#1d1d20",raised:"#27272a",accent:"#ffb783",success:"#7ad08e",danger:"#ffb4ab"},Ne=`
1
+ "use strict";var UnionStack=(()=>{var W=Object.defineProperty,Ie=Object.defineProperties,$e=Object.getOwnPropertyDescriptor,Ue=Object.getOwnPropertyDescriptors,Re=Object.getOwnPropertyNames,re=Object.getOwnPropertySymbols;var ne=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable;var oe=(n,e,t)=>e in n?W(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,C=(n,e)=>{for(var t in e||(e={}))ne.call(e,t)&&oe(n,t,e[t]);if(re)for(var t of re(e))Te.call(e,t)&&oe(n,t,e[t]);return n},U=(n,e)=>Ie(n,Ue(e));var q=(n,e)=>()=>(n&&(e=n(n=0)),e);var se=(n,e)=>{for(var t in e)W(n,t,{get:e[t],enumerable:!0})},Pe=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Re(e))!ne.call(n,r)&&r!==t&&W(n,r,{get:()=>e[r],enumerable:!(i=$e(e,r))||i.enumerable});return n};var Me=n=>Pe(W({},"__esModule",{value:!0}),n);function De(){if(document.getElementById(he))return;let n=(t,i)=>{let r=document.createElement("link");r.rel="preconnect",r.href=t,i&&(r.crossOrigin="anonymous"),document.head.appendChild(r)};n("https://fonts.googleapis.com"),n("https://fonts.gstatic.com",!0);let e=document.createElement("link");e.id=he,e.rel="stylesheet",e.href=He,document.head.appendChild(e)}function me(){if(typeof document=="undefined"||(De(),document.getElementById(ue)))return;let n=document.createElement("style");n.id=ue,n.textContent=Ne,document.head.appendChild(n)}function fe(n){var i,r,o,s,a;let t=((n==null?void 0:n.mode)||"light")==="dark"?Oe:je;return{"--us-primary":(i=n==null?void 0:n.primary)!=null?i:t.primary,"--us-on-primary":t.onPrimary,"--us-bg":(r=n==null?void 0:n.background)!=null?r:t.background,"--us-fg":(o=n==null?void 0:n.foreground)!=null?o:t.foreground,"--us-muted":t.muted,"--us-border":(s=n==null?void 0:n.border)!=null?s:t.border,"--us-subtle":"color-mix(in srgb, var(--us-fg) 5%, var(--us-bg))","--us-overlay":"color-mix(in srgb, var(--us-fg) 9%, var(--us-bg))","--us-border-strong":"color-mix(in srgb, var(--us-fg) 18%, var(--us-border))","--us-elevated":t.elevated,"--us-raised":t.raised,"--us-accent":t.accent,"--us-success":t.success,"--us-danger":t.danger,"--us-radius":(a=n==null?void 0:n.radius)!=null?a:"12px"}}var ue,he,He,je,Oe,Ne,ge=q(()=>{"use strict";ue="unionstack-picker-styles",he="unionstack-picker-fonts",He="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap";je={primary:"#494bd6",onPrimary:"#ffffff",background:"#fdfbff",foreground:"#1b1b21",muted:"#5e5c6e",subtle:"#f3f1fa",border:"#e4e1ee",borderStrong:"#c8c5d4",elevated:"#ffffff",overlay:"#eceaf4",raised:"#ffffff",accent:"#b35a00",success:"#2c9a5b",danger:"#ba1a1a"},Oe={primary:"#f4f4f5",onPrimary:"#18181b",background:"#0a0a0c",foreground:"#f4f4f5",muted:"#8b8b93",subtle:"#161618",border:"#2a2a2e",borderStrong:"#3f3f46",elevated:"#141416",overlay:"#1d1d20",raised:"#27272a",accent:"#ffb783",success:"#7ad08e",danger:"#ffb4ab"},Ne=`
2
2
  .us-picker-backdrop {
3
3
  --us-font: "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
4
4
  --us-mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;
@@ -540,5 +540,5 @@
540
540
 
541
541
  /* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 empty state niceties \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
542
542
  .us-file-list:empty { display: none; }
543
- `});function w(n,e,t){let i=document.createElement(n);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function V(n,e){let t=document.createElement("button");return t.type="button",t.className="us-tool",t.innerHTML=`${e} <span>${_e(n)}</span>`,t}function _e(n){return n.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function x(n,e,t){return Math.max(e,Math.min(t,n))}function ve(n){return new Promise((e,t)=>{let i=URL.createObjectURL(n),r=new Image;r.onload=()=>{URL.revokeObjectURL(i),e(r)},r.onerror=()=>{URL.revokeObjectURL(i),t(new Error("decode failed"))},r.src=i})}function be(n){return/^image\/(png|webp|gif)$/.test(n)}var L,X,ye=q(()=>{"use strict";L={back:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>',crop:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M6 2v14a2 2 0 0 0 2 2h14"/><path d="M18 22V8a2 2 0 0 0-2-2H2"/></svg>',circle:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/></svg>',rotate:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.82.93 6.58 2.46L21 8"/><path d="M21 3v5h-5"/></svg>',undo:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-15-6.7L3 13"/></svg>',check:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>'},X=class{constructor(e){this.opts=e;this.cropBox=null;this.hasAlpha=!1;this.mode="none";this.cropRect=null;this.dragKind=null;this.dragStart=null;this.onPointerMove=e=>{if(!this.dragKind||!this.dragStart||!this.cropRect)return;let t=this.canvasMetrics(),i=(e.clientX-this.dragStart.px)/(t.scaleX||1),r=(e.clientY-this.dragStart.py)/(t.scaleY||1),o=this.dragStart.rect,s=this.working.width,a=this.working.height,l=this.minCropImg();if(this.aspect&&this.dragKind!=="move"){switch(this.dragKind){case"se":this.cropRect=this.lockedRectFromDrag(o.x,o.y,o.w+i,1,1);break;case"nw":{let h=o.x+o.w,u=o.y+o.h;this.cropRect=this.lockedRectFromDrag(h,u,h-(o.x+i),-1,-1);break}case"ne":{let h=o.y+o.h;this.cropRect=this.lockedRectFromDrag(o.x,h,o.w+i,1,-1);break}case"sw":{let h=o.x+o.w;this.cropRect=this.lockedRectFromDrag(h,o.y,h-(o.x+i),-1,1);break}}this.updateCropBox();return}let{x:d,y:p,w:c,h:f}=o;switch(this.dragKind){case"move":d=x(o.x+i,0,s-o.w),p=x(o.y+r,0,a-o.h);break;case"nw":{let h=x(o.x+i,0,o.x+o.w-l),u=x(o.y+r,0,o.y+o.h-l);c=o.w+(o.x-h),f=o.h+(o.y-u),d=h,p=u;break}case"ne":{let h=x(o.w+i,l,s-o.x),u=x(o.y+r,0,o.y+o.h-l);f=o.h+(o.y-u),c=h,p=u;break}case"sw":{let h=x(o.x+i,0,o.x+o.w-l),u=x(o.h+r,l,a-o.y);c=o.w+(o.x-h),f=u,d=h;break}case"se":c=x(o.w+i,l,s-o.x),f=x(o.h+r,l,a-o.y);break}this.cropRect={x:d,y:p,w:c,h:f},this.updateCropBox()};this.onPointerUp=()=>{this.dragKind=null,this.dragStart=null,document.removeEventListener("pointermove",this.onPointerMove),document.removeEventListener("pointerup",this.onPointerUp)}}get aspect(){let e=this.opts.lockedAspect;return e&&e.width>0&&e.height>0?e.width/e.height:null}async open(){this.mount();try{await this.loadOriginalIntoWorking(),this.opts.originalFile&&this.opts.originalFile!==this.opts.file&&this.markEdited(!0),this.draw()}catch(e){this.canvasWrap.textContent=`Couldn't load image: ${e.message}`}}close(){document.removeEventListener("pointermove",this.onPointerMove),document.removeEventListener("pointerup",this.onPointerUp),this.root.remove()}mount(){this.root=w("div","us-editor");let e=w("div","us-editor-header"),t=document.createElement("button");t.type="button",t.className="us-editor-back",t.setAttribute("aria-label","Back"),t.innerHTML=L.back,t.onclick=()=>{this.opts.onCancel(),this.close()},e.appendChild(t),e.appendChild(w("div","us-editor-title",this.opts.title)),this.root.appendChild(e),this.canvasWrap=w("div","us-editor-canvas-wrap"),this.displayCanvas=document.createElement("canvas"),this.displayCanvas.className="us-editor-canvas",this.canvasWrap.appendChild(this.displayCanvas),this.root.appendChild(this.canvasWrap),this.cropDims=w("div","us-crop-dims"),this.cropDims.hidden=!0,this.widthInput=this.makeDimInput("Crop width in pixels","w"),this.heightInput=this.makeDimInput("Crop height in pixels","h"),this.cropDims.appendChild(w("span","us-crop-dims-label","Crop size")),this.cropDims.appendChild(this.widthInput),this.cropDims.appendChild(w("span","us-crop-dims-x","\xD7")),this.cropDims.appendChild(this.heightInput),this.cropDims.appendChild(w("span","us-crop-dims-unit","px")),this.root.appendChild(this.cropDims);let i=w("div","us-editor-toolbar");this.cropTool=V("Crop",L.crop),this.cropTool.onclick=()=>this.toggleCropMode(),this.circleTool=V("Circle",L.circle),this.circleTool.onclick=()=>this.applyCircle(),this.rotateTool=V("Rotate 90\xB0",L.rotate),this.rotateTool.onclick=()=>this.applyRotate(),this.revertTool=V("Revert",L.undo),this.revertTool.onclick=()=>this.revert(),this.revertTool.disabled=!0,i.appendChild(this.cropTool),i.appendChild(this.circleTool),i.appendChild(this.rotateTool),i.appendChild(w("div","us-tool-spacer")),i.appendChild(this.revertTool),this.root.appendChild(i);let r=w("div","us-editor-footer"),o=document.createElement("button");o.type="button",o.className="us-btn",o.textContent="Cancel",o.onclick=()=>{this.opts.onCancel(),this.close()},this.applyBtn=document.createElement("button"),this.applyBtn.type="button",this.applyBtn.className="us-btn us-btn-primary",this.applyBtn.innerHTML=`${L.check} <span>Apply</span>`,this.applyBtn.onclick=()=>this.applyAndClose(),r.appendChild(o),r.appendChild(this.applyBtn),this.root.appendChild(r),this.opts.host.appendChild(this.root)}async loadOriginalIntoWorking(){let e=await ve(this.opts.file),t=document.createElement("canvas");t.width=e.naturalWidth,t.height=e.naturalHeight;let i=t.getContext("2d");if(!i)throw new Error("Canvas 2D context unavailable");i.drawImage(e,0,0),this.working=t,this.hasAlpha=be(this.opts.file.type),this.markEdited(!1)}async loadTrueOriginalIntoWorking(){var o;let e=(o=this.opts.originalFile)!=null?o:this.opts.file,t=await ve(e),i=document.createElement("canvas");i.width=t.naturalWidth,i.height=t.naturalHeight;let r=i.getContext("2d");if(!r)throw new Error("Canvas 2D context unavailable");r.drawImage(t,0,0),this.working=i,this.hasAlpha=be(e.type),this.markEdited(!1)}draw(){let{width:e,height:t}=this.working,i=Math.min(1,720/Math.max(e,t)),r=Math.max(1,Math.round(e*i)),o=Math.max(1,Math.round(t*i));this.displayCanvas.width=r,this.displayCanvas.height=o;let s=this.displayCanvas.getContext("2d");s&&(s.clearRect(0,0,r,o),s.drawImage(this.working,0,0,r,o),this.updateCropBox())}toggleCropMode(){this.mode==="crop"?this.applyCrop():this.enterCropMode()}enterCropMode(){this.mode="crop",this.cropTool.dataset.active="true",this.cropTool.innerHTML=`${L.check} <span>Apply crop</span>`;let e=this.working.width,t=this.working.height;if(this.aspect){let r=this.aspect,o=this.minCropImg(),s=e,a=s/r;a>t&&(a=t,s=a*r),s=s*.9,a=s/r,s<o&&(s=o,a=s/r),a<o&&(a=o,s=a*r),s>e&&(s=e,a=s/r),a>t&&(a=t,s=a*r),this.cropRect={x:Math.round((e-s)/2),y:Math.round((t-a)/2),w:s,h:a}}else{let r=Math.round(Math.min(e,t)*.1);this.cropRect={x:r,y:r,w:e-r*2,h:t-r*2}}this.renderCropBox();let i=this.aspect!==null;this.widthInput.readOnly=i,this.heightInput.readOnly=i,this.cropDims.dataset.locked=i?"true":"false",this.cropDims.hidden=!1,this.syncCropDimsInputs()}exitCropMode(){this.mode="none",this.cropTool.removeAttribute("data-active"),this.cropTool.innerHTML=`${L.crop} <span>Crop</span>`,this.cropRect=null,this.cropBox&&(this.cropBox.remove(),this.cropBox=null),this.cropDims.hidden=!0}makeDimInput(e,t){let i=document.createElement("input");return i.type="number",i.min="1",i.inputMode="numeric",i.className="us-crop-dim-input",i.setAttribute("aria-label",e),i.addEventListener("input",()=>this.onDimInput(t)),i.addEventListener("change",()=>this.syncCropDimsInputs()),i}syncCropDimsInputs(){if(!this.cropRect||!this.widthInput||!this.heightInput)return;let e=Math.max(1,Math.round(this.cropRect.w)),t=Math.max(1,Math.round(this.cropRect.h));document.activeElement!==this.widthInput&&(this.widthInput.value=String(e)),document.activeElement!==this.heightInput&&(this.heightInput.value=String(t))}onDimInput(e){if(this.aspect!==null||!this.cropRect)return;let t=e==="w"?this.widthInput:this.heightInput,i=parseInt(t.value,10);if(!Number.isFinite(i)||i<=0)return;let r=this.minCropImg();if(e==="w"){let o=this.working.width-this.cropRect.x;this.cropRect=I(C({},this.cropRect),{w:x(i,r,o)})}else{let o=this.working.height-this.cropRect.y;this.cropRect=I(C({},this.cropRect),{h:x(i,r,o)})}this.updateCropBox()}renderCropBox(){if(!this.cropRect)return;this.cropBox&&this.cropBox.remove();let e=w("div","us-crop-box");for(let t of["nw","ne","sw","se"]){let i=w("div","us-crop-handle");i.dataset.pos=t,i.addEventListener("pointerdown",r=>this.beginDrag(r,t)),e.appendChild(i)}e.addEventListener("pointerdown",t=>{t.target.classList.contains("us-crop-handle")||this.beginDrag(t,"move")}),this.canvasWrap.appendChild(e),this.cropBox=e,this.updateCropBox()}canvasMetrics(){let e=this.displayCanvas.getBoundingClientRect(),t=this.canvasWrap.getBoundingClientRect();return{scaleX:e.width/(this.working.width||1),scaleY:e.height/(this.working.height||1),offX:e.left-t.left,offY:e.top-t.top}}minCropImg(){let{scaleX:e}=this.canvasMetrics();return e>0?24/e:24}updateCropBox(){if(!this.cropBox||!this.cropRect)return;let e=this.canvasMetrics();this.cropBox.style.left=`${e.offX+this.cropRect.x*e.scaleX}px`,this.cropBox.style.top=`${e.offY+this.cropRect.y*e.scaleY}px`,this.cropBox.style.width=`${this.cropRect.w*e.scaleX}px`,this.cropBox.style.height=`${this.cropRect.h*e.scaleY}px`,this.syncCropDimsInputs()}beginDrag(e,t){this.cropRect&&(e.preventDefault(),this.dragKind=t,this.dragStart={px:e.clientX,py:e.clientY,rect:C({},this.cropRect)},document.addEventListener("pointermove",this.onPointerMove),document.addEventListener("pointerup",this.onPointerUp))}lockedRectFromDrag(e,t,i,r,o){let s=this.aspect,a=this.working.width,l=this.working.height,d=this.minCropImg(),p=Math.max(d,i),c=p/s;c<d&&(c=d,p=c*s);let f=r>0?a-e:e,h=o>0?l-t:t;p=Math.min(p,f,h*s),c=p/s;let u=r>0?e:e-p,R=o>0?t:t-c;return{x:u,y:R,w:p,h:c}}applyCrop(){var a,l;if(!this.cropRect){this.exitCropMode();return}let e=x(Math.round(this.cropRect.x),0,this.working.width-1),t=x(Math.round(this.cropRect.y),0,this.working.height-1),i=x(Math.round(this.cropRect.w),1,this.working.width-e),r=x(Math.round(this.cropRect.h),1,this.working.height-t),o=document.createElement("canvas");o.width=i,o.height=r;let s=o.getContext("2d");s&&(s.drawImage(this.working,e,t,i,r,0,0,i,r),this.working=o,this.exitCropMode(),this.markEdited(!0),(l=(a=this.opts).onCropApplied)==null||l.call(a),this.draw())}applyRotate(){var o,s;let{width:e,height:t}=this.working,i=document.createElement("canvas");i.width=t,i.height=e;let r=i.getContext("2d");r&&(r.translate(t,0),r.rotate(Math.PI/2),r.drawImage(this.working,0,0),this.working=i,this.exitCropMode(),this.markEdited(!0),(s=(o=this.opts).onAspectReset)==null||s.call(o),this.draw())}applyCircle(){var l,d;let{width:e,height:t}=this.working,i=Math.min(e,t),r=Math.round((e-i)/2),o=Math.round((t-i)/2),s=document.createElement("canvas");s.width=i,s.height=i;let a=s.getContext("2d");a&&(a.save(),a.beginPath(),a.arc(i/2,i/2,i/2,0,Math.PI*2),a.closePath(),a.clip(),a.drawImage(this.working,r,o,i,i,0,0,i,i),a.restore(),this.working=s,this.hasAlpha=!0,this.exitCropMode(),this.markEdited(!0),(d=(l=this.opts).onAspectReset)==null||d.call(l),this.draw())}async revert(){var e,t;await this.loadTrueOriginalIntoWorking(),this.exitCropMode(),(t=(e=this.opts).onAspectReset)==null||t.call(e),this.draw()}markEdited(e){this.revertTool.disabled=!e}async applyAndClose(){this.applyBtn.disabled=!0,this.mode==="crop"&&this.applyCrop();try{let e=await this.exportFile();this.opts.onApply(e),this.close()}catch(e){this.applyBtn.disabled=!1,console.error("[union-stack] image export failed",e)}}exportFile(){return new Promise((e,t)=>{let i=this.hasAlpha?"image/png":"image/jpeg",r=i==="image/jpeg"?.92:void 0;this.working.toBlob(o=>{if(!o)return t(new Error("toBlob returned null"));let s=this.opts.file.name.replace(/\.[^.]+$/,""),a=i==="image/png"?"png":"jpg";e(new File([o],`${s}-edited.${a}`,{type:i}))},i,r)})}}});function We(n,e){var a,l,d,p,c,f,h,u,R,F,M,S,k,E,$,g,T,y,O,_,A,B,H,U,P,N,Q,te;let t=C({},e),i=e.branding||{};t.branding={logoUrl:(l=(a=i.logoUrl)!=null?a:n.branding.logoUrl)!=null?l:void 0,title:(p=(d=i.title)!=null?d:n.branding.title)!=null?p:void 0,hideFooter:(c=i.hideFooter)!=null?c:n.branding.hideFooter};let r=e.theme||{};if(t.theme={primary:(h=(f=r.primary)!=null?f:n.theme.primary)!=null?h:void 0,background:(R=(u=r.background)!=null?u:n.theme.background)!=null?R:void 0,foreground:(M=(F=r.foreground)!=null?F:n.theme.foreground)!=null?M:void 0,border:(k=(S=r.border)!=null?S:n.theme.border)!=null?k:void 0,radius:($=(E=r.radius)!=null?E:n.theme.radius)!=null?$:void 0,mode:(T=(g=r.mode)!=null?g:n.theme.mode)!=null?T:void 0},t.maxFileSize=(y=e.maxFileSize)!=null?y:n.constraints.maxFileSizeBytes,t.maxFiles=(O=e.maxFiles)!=null?O:n.constraints.maxFilesPerUpload,!e.accept&&((_=n.constraints.allowedMimeTypes)!=null&&_.length)){let ie=n.constraints.allowedMimeTypes.filter(Ee=>Ee!=="*/*");ie.length>0&&(t.accept=ie.join(","))}let o=(A=n.image)!=null?A:null,s=(B=e.cropAspectRatio)!=null?B:o&&o.cropRatioW&&o.cropRatioH?{width:o.cropRatioW,height:o.cropRatioH}:void 0;return t.cropAspectRatio=s,t.forceCrop=((U=(H=e.forceCrop)!=null?H:o==null?void 0:o.forceCrop)!=null?U:!1)&&!!s&&e.imageEditing!==!1,t.minImageWidth=(N=(P=e.minImageWidth)!=null?P:o==null?void 0:o.minWidth)!=null?N:void 0,t.minImageHeight=(te=(Q=e.minImageHeight)!=null?Q:o==null?void 0:o.minHeight)!=null?te:void 0,t}function Y(n){return n?n.startsWith("image/")?b.image:n.startsWith("video/")?b.video:n.startsWith("audio/")?b.audio:n==="application/pdf"?b.pdf:n.startsWith("application/zip")||n.includes("compressed")||n==="application/x-tar"||n==="application/gzip"?b.archive:b.file:b.file}function m(n,e,t){let i=document.createElement(n);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function Ye(n){var i,r,o;let e=n.trim().toLowerCase();if(!e)return"";if(e.endsWith("/*")||!e.includes("/")){let s=e.replace("/*","");return(i=Xe[s])!=null?i:s.charAt(0).toUpperCase()+s.slice(1)}if(xe[e])return xe[e];if(e.startsWith("."))return e.slice(1).toUpperCase();let t=(r=e.split("/")[1])!=null?r:e;return((o=t.split("+")[0].split(".").pop())!=null?o:t).toUpperCase()}function j(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:n<1024*1024*1024?`${(n/1024/1024).toFixed(1)} MB`:`${(n/1024/1024/1024).toFixed(2)} GB`}function Z(){return typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36)}async function Ge(n){var e;if(typeof createImageBitmap=="function")try{let t=await createImageBitmap(n),i=t.width,r=t.height;return(e=t.close)==null||e.call(t),{w:i,h:r}}catch(t){}return new Promise((t,i)=>{if(typeof URL=="undefined"||!URL.createObjectURL){i(new Error("no object URL support"));return}let r=URL.createObjectURL(n),o=new Image;o.onload=()=>{URL.revokeObjectURL(r),t({w:o.naturalWidth,h:o.naturalHeight})},o.onerror=()=>{URL.revokeObjectURL(r),i(new Error("decode failed"))},o.src=r})}async function Je(n){let e;try{e=await fetch(n,{mode:"cors",credentials:"omit"})}catch(o){throw new Error(`Could not reach ${Qe(n)} \u2014 check the URL or CORS.`)}if(!e.ok)throw new Error(`Server returned ${e.status} \u2014 file unavailable.`);let t=await e.blob(),i=Ze(n)||"download",r=t.type||et(i);return new File([t],i,{type:r})}function Qe(n){try{return new URL(n).host}catch(e){return"that host"}}function Ze(n){try{let t=new URL(n).pathname.split("/").filter(Boolean).pop();return t?decodeURIComponent(t):""}catch(e){return""}}function et(n){let e=n.toLowerCase().split(".").pop()||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",mp4:"video/mp4",mov:"video/quicktime",mp3:"audio/mpeg",wav:"audio/wav",zip:"application/zip",json:"application/json",txt:"text/plain",csv:"text/csv"}[e]||"application/octet-stream"}function G(n,e){let t=new z(n,e);return{open:()=>t.open(),close:()=>t.close(),cancel:()=>t.cancel()}}var qe,Ke,b,Ve,z,xe,Xe,ke=q(()=>{"use strict";ge();ye();qe="Upload files",Ke="https://unionstack.link",b={upload:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>',fileUp:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><path d="M12 18v-6"/><path d="m9 15 3-3 3 3"/></svg>',close:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',check:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',alert:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',spinner:'<svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="9" stroke="currentColor" opacity="0.2"/><path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor"/></svg>',clock:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><polyline points="12 7.5 12 12 15 13.5"/></svg>',image:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>',video:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>',audio:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>',pdf:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="9" y1="13" x2="15" y2="13"/><line x1="9" y1="17" x2="13" y2="17"/></svg>',archive:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="5" rx="2"/><path d="M4 9v9a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9"/><line x1="10" y1="13" x2="14" y2="13"/></svg>',file:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>',zap:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>',device:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>',link:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.72"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.72-1.72"/></svg>',pencil:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>'};Ve='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',z=class{constructor(e,t){this.client=e;this.opts=t;this.$backdrop=null;this.$panel=null;this.$list=null;this.$confirm=null;this.$cancel=null;this.$closeBtn=null;this.$input=null;this.$deviceSource=null;this.$urlSource=null;this.$urlInput=null;this.$urlHint=null;this.$urlAddBtn=null;this.items=[];this.editor=null;this.abortCtrl=new AbortController;this.uploadStarted=!1;this.validateSeqCounter=0;this.resolved=!1;this.previouslyFocused=null;this.noticeTimer=null;this.$summary=null;this.donePromise=new Promise(i=>{this.resolvePromise=i})}async open(){var e,t;if(typeof document=="undefined")throw new Error("[union-stack] Picker requires a browser environment.");try{let i=await this.client.pickerConfigPromise;i&&(this.opts=We(i,this.opts))}catch(i){}return me(),this.mount(),(t=(e=this.opts).onOpen)==null||t.call(e),this.donePromise}close(){this.unmount(),this.resolved||this.resolveResult()}cancel(){var e,t;this.abortCtrl.abort(),(t=(e=this.opts).onCancel)==null||t.call(e),this.close()}get acceptStr(){let e=this.opts.accept;return Array.isArray(e)?e.join(","):e!=null?e:""}mount(){var h,u,R,F,M,S,k,E,$;this.previouslyFocused=(h=document.activeElement)!=null?h:null;let e=document.createElement("div");e.className="us-picker-backdrop",Object.entries(fe(this.opts.theme)).forEach(([g,T])=>{e.style.setProperty(g,T)}),e.style.colorScheme=((u=this.opts.theme)==null?void 0:u.mode)==="dark"?"dark":"light",e.addEventListener("click",g=>{g.target===e&&!this.uploadStarted&&this.cancel()});let t=m("div","us-picker");this.$panel=t;let i=`us-picker-title-${Z()}`;t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-labelledby",i),t.tabIndex=-1,t.addEventListener("keydown",g=>{g.key==="Escape"&&!this.uploadStarted?(g.preventDefault(),this.cancel()):g.key==="Tab"&&this.trapFocus(g)});let r=m("div","us-picker-header"),o=m("div","us-picker-header-logo");if((R=this.opts.branding)!=null&&R.logoUrl){let g=document.createElement("img");g.src=this.opts.branding.logoUrl,g.alt="",o.appendChild(g)}else o.innerHTML=b.zap;r.appendChild(o);let s=m("div","us-picker-title",(M=(F=this.opts.branding)==null?void 0:F.title)!=null?M:qe);s.id=i,r.appendChild(s),this.$closeBtn=document.createElement("button"),this.$closeBtn.type="button",this.$closeBtn.className="us-picker-close",this.$closeBtn.setAttribute("aria-label","Close"),this.$closeBtn.innerHTML=b.close,this.$closeBtn.onclick=()=>this.cancel(),r.appendChild(this.$closeBtn),t.appendChild(r);let a=m("div","us-picker-body"),l=this.resolvedSources();l.length>1&&a.appendChild(this.renderSourceTabs(l)),l.includes("device")&&(this.$deviceSource=this.renderDropzone(),a.appendChild(this.$deviceSource)),l.includes("url")&&(this.$urlSource=this.renderUrlSource(),a.appendChild(this.$urlSource)),this.$list=m("div","us-file-list"),a.appendChild(this.$list),t.appendChild(a),this.activateSource((S=l[0])!=null?S:"device");let d=this.opts.autoUpload===!0,p=m("div","us-actions");this.$summary=m("div","us-actions-summary",""),this.$summary.setAttribute("role","status"),this.$summary.setAttribute("aria-live","polite"),p.appendChild(this.$summary);let c=m("div","us-actions-buttons");if(this.$cancel=document.createElement("button"),this.$cancel.type="button",this.$cancel.className="us-btn",this.$cancel.textContent="Cancel",this.$cancel.onclick=()=>this.cancel(),c.appendChild(this.$cancel),d||(this.$confirm=document.createElement("button"),this.$confirm.type="button",this.$confirm.className="us-btn us-btn-primary",this.$confirm.innerHTML=`${b.upload} <span>Upload</span>`,this.$confirm.disabled=!0,this.$confirm.onclick=()=>this.startUpload(),c.appendChild(this.$confirm)),p.appendChild(c),t.appendChild(p),!((k=this.opts.branding)!=null&&k.hideFooter)){let g=m("div","us-footer");g.innerHTML=`${b.zap} <span>Powered by <a href="${Ke}" target="_blank" rel="noopener">UnionStack</a></span>`,t.appendChild(g)}e.appendChild(t),((E=this.opts.container)!=null?E:document.body).appendChild(e),this.$backdrop=e,(($=t.querySelector('.us-source-tab[data-active="true"]'))!=null?$:t).focus()}trapFocus(e){if(!this.$panel)return;let t=Array.from(this.$panel.querySelectorAll(Ve)).filter(s=>!s.hasAttribute("disabled")&&s.offsetParent!==null);if(t.length===0)return;let i=t[0],r=t[t.length-1],o=document.activeElement;e.shiftKey&&o===i?(e.preventDefault(),r.focus()):!e.shiftKey&&o===r&&(e.preventDefault(),i.focus())}resolvedSources(){let e=this.opts.fromSources;return!e||e.length===0?["device","url"]:e}renderSourceTabs(e){let t=m("div","us-source-tabs");return t.setAttribute("role","tablist"),t.setAttribute("aria-label","Upload source"),e.forEach((i,r)=>{let o=document.createElement("button");o.type="button",o.className="us-source-tab",o.setAttribute("role","tab"),o.setAttribute("aria-selected","false"),o.tabIndex=-1,o.dataset.source=i,o.innerHTML=i==="device"?`${b.device} <span>My Device</span>`:`${b.link} <span>Link</span>`,o.onclick=()=>this.activateSource(i),o.onkeydown=s=>this.onTabKeydown(s,e,r),t.appendChild(o)}),t}onTabKeydown(e,t,i){var o,s;let r=i;if(e.key==="ArrowRight"||e.key==="ArrowDown")r=(i+1)%t.length;else if(e.key==="ArrowLeft"||e.key==="ArrowUp")r=(i-1+t.length)%t.length;else if(e.key==="Home")r=0;else if(e.key==="End")r=t.length-1;else return;e.preventDefault(),this.activateSource(t[r]),(s=(o=this.$panel)==null?void 0:o.querySelector(`.us-source-tab[data-source="${t[r]}"]`))==null||s.focus()}activateSource(e){var i;if(this.$deviceSource){let r=e==="device";this.$deviceSource.style.display=r?"":"none"}this.$urlSource&&(this.$urlSource.dataset.active=e==="url"?"true":"false");let t=(i=this.$panel)==null?void 0:i.querySelectorAll(".us-source-tab");t==null||t.forEach(r=>{let o=r.dataset.source===e;r.dataset.active=o?"true":"false",r.setAttribute("aria-selected",o?"true":"false"),r.tabIndex=o?0:-1})}renderUrlSource(){let e=m("div","us-url-source"),t=m("div","us-url-form"),i=document.createElement("input");i.type="url",i.className="us-url-input",i.placeholder="https://example.com/photo.jpg",i.setAttribute("aria-label","File URL"),i.onkeydown=s=>{s.key==="Enter"&&(s.preventDefault(),this.handleUrlAdd())},this.$urlInput=i;let r=document.createElement("button");r.type="button",r.className="us-btn us-btn-primary",r.textContent="Add file",r.onclick=()=>this.handleUrlAdd(),this.$urlAddBtn=r,t.appendChild(i),t.appendChild(r),e.appendChild(t);let o=m("div","us-url-hint","Paste a direct file URL. The host must allow CORS so we can fetch it from the browser.");return this.$urlHint=o,e.appendChild(o),e}async handleUrlAdd(){if(!this.$urlInput||!this.$urlAddBtn||!this.$urlHint)return;let e=this.$urlInput.value.trim();if(!e){this.setUrlHint("Enter a URL first.",!0);return}if(!/^https?:\/\//i.test(e)){this.setUrlHint("URL must start with http:// or https://",!0);return}this.$urlAddBtn.disabled=!0;let t=this.$urlAddBtn.textContent;this.$urlAddBtn.textContent="Fetching\u2026",this.setUrlHint("Downloading\u2026",!1);try{let i=await Je(e);this.addFiles([i]),this.$urlInput.value="",this.setUrlHint("Paste a direct file URL. The host must allow CORS so we can fetch it from the browser.",!1)}catch(i){let r=i.message||"Failed to fetch URL";this.setUrlHint(r,!0)}finally{this.$urlAddBtn.disabled=!1,this.$urlAddBtn.textContent=t||"Add file"}}setUrlHint(e,t){this.$urlHint&&(this.$urlHint.textContent=e,this.$urlHint.dataset.error=t?"true":"false")}renderDropzone(){var s;let e=m("div","us-dropzone");e.setAttribute("role","button"),e.setAttribute("tabindex","0"),e.setAttribute("aria-label","Drop files here or click to browse");let t=m("div","us-dropzone-icon");t.innerHTML=b.fileUp,e.appendChild(t),e.appendChild(m("div","us-dropzone-title","Drop files to upload")),e.appendChild(m("div","us-dropzone-hint","or click to browse from your device"));let i=[];if(this.opts.maxFileSize&&i.push(`max ${j(this.opts.maxFileSize)}`),this.acceptStr){let a=[],l=new Set;for(let d of this.acceptStr.split(",")){let p=d.trim();if(!p||p==="*/*")continue;let c=Ye(p);c&&!l.has(c)&&(l.add(c),a.push(c))}a.length>0&&i.push(a.length>5?`${a.slice(0,5).join(", ")} +${a.length-5}`:a.join(", "))}i.length>0&&e.appendChild(m("div","us-dropzone-constraints",i.join(" \xB7 ")));let r=document.createElement("input");r.type="file",r.multiple=((s=this.opts.maxFiles)!=null?s:10)>1,this.acceptStr&&(r.accept=this.acceptStr),r.style.display="none",r.onchange=()=>{r.files&&this.addFiles(Array.from(r.files)),r.value=""},this.$input=r,e.appendChild(r),e.onclick=()=>r.click(),e.onkeydown=a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r.click())};let o=0;return e.addEventListener("dragenter",a=>{a.preventDefault(),o++,e.setAttribute("data-drag","over")}),e.addEventListener("dragover",a=>a.preventDefault()),e.addEventListener("dragleave",()=>{o=Math.max(0,o-1),o===0&&e.removeAttribute("data-drag")}),e.addEventListener("drop",a=>{var d;a.preventDefault(),o=0,e.removeAttribute("data-drag");let l=(d=a.dataTransfer)==null?void 0:d.files;l&&this.addFiles(Array.from(l))}),e}unmount(){var e,t,i,r,o;this.editor&&(this.editor.close(),this.editor=null),this.noticeTimer&&(clearTimeout(this.noticeTimer),this.noticeTimer=null),(e=this.$backdrop)!=null&&e.parentNode&&this.$backdrop.parentNode.removeChild(this.$backdrop),this.$backdrop=null,this.$panel=null;for(let s of this.items)s.objectUrl&&URL.revokeObjectURL(s.objectUrl);(i=(t=this.previouslyFocused)==null?void 0:t.focus)==null||i.call(t),this.previouslyFocused=null,(o=(r=this.opts).onClose)==null||o.call(r)}fileMatchesAccept(e){let t=this.acceptStr.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean);if(t.length===0||t.includes("*/*"))return!0;let i=(e.type||"").toLowerCase(),r=e.name.toLowerCase();return t.some(o=>o.startsWith(".")?r.endsWith(o):o.endsWith("/*")?i.startsWith(o.slice(0,-1)):i===o)}addFiles(e){var d;let t=(d=this.opts.maxFiles)!=null?d:1/0,i=0,r=e.filter(p=>this.fileMatchesAccept(p)?!0:(i++,!1)),o=t-this.items.length,s=o>0?r.slice(0,o):[],a=r.length-s.length,l=[];i>0&&l.push(`${i} file${i>1?"s":""} skipped \u2014 unsupported type`),a>0&&l.push(`${a} file${a>1?"s":""} skipped \u2014 max ${t} allowed`),l.length&&this.flashNotice(l.join(" \xB7 "));for(let p of s){if(this.opts.maxFileSize&&p.size>this.opts.maxFileSize){let f={uploadId:Z(),file:p,originalFile:p,edited:!1,state:"failed",progress:0,error:`File exceeds ${j(this.opts.maxFileSize)} limit`};this.items.push(f),this.renderItem(f);continue}let c={uploadId:Z(),file:p,originalFile:p,edited:!1,state:"queued",progress:0};this.items.push(c),this.renderItem(c),this.shouldCheckDimensions(p)&&(c.validating=!0,this.validateDimensions(c))}this.refreshConfirm(),this.maybeAutoUpload()}renderItem(e){if(!this.$list)return;let t=m("div","us-file");t.dataset.state=e.state,t.dataset.uploadId=e.uploadId;let i=Math.min(this.items.length-1,8);t.style.animationDelay=`${i*35}ms`;let r=m("div","us-file-thumb");if(e.file.type.startsWith("image/")&&typeof URL!="undefined"&&URL.createObjectURL)try{let u=URL.createObjectURL(e.file);e.objectUrl=u,r.style.backgroundImage=`url("${u}")`,r.dataset.image="true"}catch(u){r.innerHTML=Y(e.file.type)}else r.innerHTML=Y(e.file.type);t.appendChild(r);let o=m("div","us-file-main"),s=m("div","us-file-row1");s.appendChild(m("div","us-file-name",e.file.name));let a=m("div","us-file-meta",j(e.file.size));s.appendChild(a),o.appendChild(s);let l=m("div","us-file-progress"),d=m("div","us-file-progress-bar");l.appendChild(d),o.appendChild(l);let p=m("div","us-file-error");e.error&&(p.textContent=e.error),o.appendChild(p),t.appendChild(o);let c=e.file.type.startsWith("image/"),f=this.opts.imageEditing!==!1;if(c&&f&&e.state==="queued"){let u=document.createElement("button");u.type="button",u.className="us-file-action",u.setAttribute("aria-label","Edit image"),u.title="Edit image",u.innerHTML=b.pencil,u.dataset.edited=e.edited?"true":"false",u.onclick=()=>this.openEditor(e),t.appendChild(u),e.$edit=u}let h=m("div","us-file-status");h.setAttribute("aria-label",this.statusLabel(e)),h.innerHTML=this.statusIcon(e.state),t.appendChild(h),e.$row=t,e.$bar=d,e.$status=h,e.$meta=a,e.$error=p,e.$thumb=r,this.$list.appendChild(t),this.updateSummary(),this.updateItemBadge(e)}replaceItemFile(e,t,i){if(e.file=t,e.edited=i,e.objectUrl&&URL.revokeObjectURL(e.objectUrl),e.objectUrl=void 0,e.$thumb)if(e.$thumb.style.backgroundImage="",e.$thumb.removeAttribute("data-image"),t.type.startsWith("image/")&&typeof URL!="undefined"&&URL.createObjectURL)try{let r=URL.createObjectURL(t);e.objectUrl=r,e.$thumb.style.backgroundImage=`url("${r}")`,e.$thumb.dataset.image="true",e.$thumb.innerHTML=""}catch(r){e.$thumb.innerHTML=Y(t.type)}else e.$thumb.innerHTML=Y(t.type);if(e.$meta&&(e.$meta.textContent=j(t.size)),e.$row){let r=e.$row.querySelector(".us-file-name");r&&(r.textContent=t.name)}e.$edit&&(e.$edit.dataset.edited=i?"true":"false")}openEditor(e){if(!this.$panel||this.editor||e.state!=="queued")return;let t=!1;this.editor=new X({host:this.$panel,file:e.file,originalFile:e.originalFile,title:e.originalFile.name,lockedAspect:this.opts.cropAspectRatio,onCropApplied:()=>{t=!0},onAspectReset:()=>{t=!1},onApply:i=>{let r=i!==e.originalFile;this.replaceItemFile(e,i,r),t&&(e.ratioCropped=!0),this.editor=null,this.shouldCheckDimensions(e.file)&&(e.validating=!0,this.validateDimensions(e)),this.updateItemBadge(e),this.refreshConfirm()},onCancel:()=>{this.editor=null}}),this.editor.open()}statusIcon(e){switch(e){case"uploading":return b.spinner;case"done":return b.check;case"failed":return b.alert;case"cancelled":return b.alert;default:return b.clock}}statusLabel(e){switch(e.state){case"queued":return"Waiting to upload";case"uploading":return`Uploading ${Math.round(e.progress)} percent`;case"done":return"Upload complete";case"failed":return e.error?`Failed: ${e.error}`:"Upload failed";case"cancelled":return"Cancelled"}}setItemState(e,t,i){if(e.state=t,i!==void 0&&(e.progress=i),e.$row&&(e.$row.dataset.state=t),e.$bar&&(e.$bar.style.width=`${e.progress}%`),e.$status&&(e.$status.innerHTML=this.statusIcon(t),e.$status.setAttribute("aria-label",this.statusLabel(e))),e.$meta){let r=j(e.file.size);t==="uploading"?e.$meta.textContent=`${r} \xB7 ${Math.round(e.progress)}%`:e.$meta.textContent=r}e.$error&&(e.$error.textContent=t==="failed"?e.error||"Upload failed":""),this.updateSummary()}updateSummary(){if(!this.$summary)return;let e=this.items.length;if(e===0){this.$summary.textContent="";return}let t=this.items.filter(o=>o.state==="done").length,i=this.items.filter(o=>o.state==="failed").length,r=this.items.filter(o=>o.state==="uploading"||o.state==="queued").length;if(!this.uploadStarted&&r>0){let o=this.items.filter(s=>s.state==="queued").length;this.$summary.textContent=`${o} file${o===1?"":"s"} ready`}else r>0?this.$summary.textContent=`Uploading ${t+1} of ${e}`:i>0?this.$summary.textContent=`${t} of ${e} uploaded \xB7 ${i} failed`:t===e?this.$summary.textContent=`${e} file${e===1?"":"s"} uploaded`:this.$summary.textContent=`${e} file${e===1?"":"s"} ready`}needsCrop(e){return this.opts.forceCrop===!0&&!!this.opts.cropAspectRatio&&e.state==="queued"&&e.file.type.startsWith("image/")&&e.file.type!=="image/svg+xml"&&!e.ratioCropped}hasUncroppedImages(){return this.items.some(e=>this.needsCrop(e))}anyValidating(){return this.items.some(e=>e.validating===!0)}shouldCheckDimensions(e){return!!(this.opts.minImageWidth||this.opts.minImageHeight)&&e.type.startsWith("image/")&&e.type!=="image/svg+xml"}updateItemBadge(e){e.$row&&(this.needsCrop(e)?(e.$row.dataset.cropRequired="true",e.$meta&&(e.$meta.textContent="Crop to ratio required")):(delete e.$row.dataset.cropRequired,e.state==="queued"&&e.$meta&&!e.validating&&(e.$meta.textContent=j(e.file.size))))}async validateDimensions(e){var a,l;let t=++this.validateSeqCounter;e.validateSeq=t;let i=(a=this.opts.minImageWidth)!=null?a:0,r=(l=this.opts.minImageHeight)!=null?l:0,o=e.file,s=null;try{s=await Ge(o)}catch(d){s=null}if(e.validateSeq===t){if(e.validating=!1,e.state==="queued")if(s&&s.w>0&&s.h>0&&(s.w<i||s.h<r)){let d=`${i||"?"}\xD7${r||"?"}`;e.error=`Image too small \u2014 needs at least ${d}px (got ${s.w}\xD7${s.h})`,this.setItemState(e,"failed")}else this.updateItemBadge(e);this.refreshConfirm(),this.maybeAutoUpload()}}maybeAutoUpload(){this.opts.autoUpload!==!0||this.uploadStarted||this.anyValidating()||this.hasUncroppedImages()||this.items.some(e=>e.state==="queued")&&requestAnimationFrame(()=>{this.uploadStarted||this.startUpload()})}refreshConfirm(){if(!this.$confirm)return;let e=this.items.filter(t=>t.state==="queued").length;this.$confirm.disabled=e===0||this.uploadStarted||this.hasUncroppedImages()||this.anyValidating()}flashNotice(e){this.$summary&&(this.$summary.textContent=e,this.$summary.dataset.tone="warn",this.noticeTimer&&clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{this.$summary&&(this.$summary.textContent="",delete this.$summary.dataset.tone),this.noticeTimer=null},4e3))}async startUpload(){if(this.uploadStarted)return;if(this.anyValidating()){this.flashNotice("Checking image dimensions\u2026");return}if(this.hasUncroppedImages()){this.items.forEach(r=>this.updateItemBadge(r)),this.flashNotice("Crop required \u2014 crop every image to the set ratio before uploading.");return}let e=this.items.filter(r=>r.state==="queued");if(e.length===0)return;this.uploadStarted=!0,this.$confirm&&(this.$confirm.disabled=!0,this.$confirm.textContent="Uploading\u2026"),this.$cancel&&(this.$cancel.textContent="Stop"),this.$closeBtn&&(this.$closeBtn.disabled=!0),this.$input&&(this.$input.disabled=!0);let t=new Map,i=e.map(r=>r.file);try{await this.client.uploadMany(i,I(C({},this.opts),{signal:this.abortCtrl.signal,onUploadStarted:r=>{var o,s;r.forEach((a,l)=>{let d=e[l];d&&(d.uploadId=a.uploadId,d.$row&&(d.$row.dataset.uploadId=a.uploadId),t.set(a.uploadId,d))}),(s=(o=this.opts).onUploadStarted)==null||s.call(o,r)},onFileUploadStarted:r=>{var s,a;let o=t.get(r.uploadId);o&&this.setItemState(o,"uploading",0),(a=(s=this.opts).onFileUploadStarted)==null||a.call(s,r)},onFileUploadProgress:(r,o)=>{var a,l;let s=t.get(r.uploadId);s&&this.setItemState(s,"uploading",o.totalPercent),(l=(a=this.opts).onFileUploadProgress)==null||l.call(a,r,o)},onFileUploadFinished:r=>{var s,a;let o=t.get(r.uploadId);o&&(o.uploaded=r,this.setItemState(o,"done",100)),(a=(s=this.opts).onFileUploadFinished)==null||a.call(s,r)},onFileUploadFailed:(r,o)=>{var a,l;let s=t.get(r.uploadId);s&&(s.error=o.message,this.setItemState(s,"failed")),(l=(a=this.opts).onFileUploadFailed)==null||l.call(a,r,o)},onUploadDone:r=>{var o,s;(s=(o=this.opts).onUploadDone)==null||s.call(o,r),this.resolveResult(r),this.unmount()},onError:r=>{var o,s;(s=(o=this.opts).onError)==null||s.call(o,r),this.resolveResult(),this.unmount()}}))}catch(r){this.resolved||(this.resolveResult(),this.unmount())}}resolveResult(e){if(this.resolved)return;this.resolved=!0;let t=e!=null?e:{filesUploaded:this.items.filter(i=>i.uploaded).map(i=>i.uploaded),filesFailed:this.items.filter(i=>i.state==="failed").map(i=>({file:{uploadId:i.uploadId,filename:i.file.name,mimetype:i.file.type||"application/octet-stream",size:i.file.size,source:"local"},error:{code:"VALIDATION",message:i.error||"failed",retryable:!1}}))};this.resolvePromise(t)}};xe={"application/pdf":"PDF","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/vnd.ms-powerpoint":"PPT","application/vnd.openxmlformats-officedocument.presentationml.presentation":"PPTX","application/zip":"ZIP","application/json":"JSON","application/rtf":"RTF","text/plain":"TXT","text/csv":"CSV","text/html":"HTML","text/markdown":"MD","image/jpeg":"JPG","image/png":"PNG","image/gif":"GIF","image/webp":"WEBP","image/svg+xml":"SVG","image/heic":"HEIC","video/mp4":"MP4","audio/mpeg":"MP3"},Xe={image:"Images",video:"Video",audio:"Audio",text:"Text",font:"Fonts"}});var we={};se(we,{Picker:()=>z,openPicker:()=>G});var ee=q(()=>{"use strict";ke()});var ot={};se(ot,{Picker:()=>z,UnionStackClient:()=>D,init:()=>rt,openPicker:()=>G});function v(n,e,t={}){var i;return{code:n,message:e,status:t.status,retryable:(i=t.retryable)!=null?i:Se(n,t.status),cause:t.cause}}function Se(n,e){return!!(n==="NETWORK"||n==="PART_FAILED"||n==="SERVER"&&e&&e>=500)}function ae(n,e){let t=e==null?void 0:e.error,i=(t==null?void 0:t.message)||`Request failed with status ${n}`,r=((t==null?void 0:t.code)||"").toUpperCase();if(n===401)return v("AUTH",i,{status:n,retryable:!1});if(n===403)return v("AUTH",i,{status:n,retryable:!1});if(n===413)return v("VALIDATION",i,{status:n,retryable:!1});if(n===415)return v("VALIDATION",i,{status:n,retryable:!1});if(n===426)return v("CONFIG",i,{status:n,retryable:!1});if(n===429){let o=r==="QUOTA_EXCEEDED";return v(o?"QUOTA":"NETWORK",i,{status:n,retryable:!o})}return n>=500?v("SERVER",i,{status:n,retryable:!0}):v("SERVER",i,{status:n,retryable:!1})}var le="0.3.14",de=`js/${le}`,at=`node/${le}`;var Le=3,Fe=3,pe=[400,1200,3600],K=class{constructor(e){this.cfg=e}describe(e,t={}){let i=typeof File!="undefined"&&e instanceof File,r=t.filename||(i?e.name:"untitled"),o=t.mimeType||e.type||"application/octet-stream";return{uploadId:Ae(),filename:r,mimetype:o,size:e.size,source:"local"}}async upload(e,t={}){var r,o,s;let i=this.describe(e,{filename:t.filename,mimeType:t.mimeType});(r=t.onFileUploadStarted)==null||r.call(t,i);try{let a=await this.initUpload(i,t),l=await this.uploadAllParts(e,a,i,t),d=await this.completeUpload(a.sessionId,l,t),p=I(C({},i),{handle:d.handle,fileId:d.fileId,url:d.url,size:d.size,mimetype:d.mimetype,filename:d.filename,key:d.key,container:d.container,status:"Stored",etag:d.etag,metadata:d.metadata});return(o=t.onFileUploadFinished)==null||o.call(t,p),p}catch(a){let l=ce(a);throw(s=t.onFileUploadFailed)==null||s.call(t,i,l),a!=null&&a.sessionId&&this.abortSilently(a.sessionId).catch(()=>{}),l}}async abort(e){await this.api("POST","/sdk/v1/uploads/abort",{sessionId:e})}async fetchPickerConfig(){return this.api("GET","/sdk/v1/picker-config")}async initUpload(e,t){return this.api("POST","/sdk/v1/uploads/init",{filename:e.filename,mimeType:e.mimetype,size:e.size,metadata:t.metadata},t.signal)}async uploadAllParts(e,t,i,r){var M,S;let o=t.totalParts,s=t.chunkSize,a=Math.max(1,(M=r.concurrency)!=null?M:Le),l=(S=r.maxRetriesPerPart)!=null?S:Fe,d=new Map(t.partUrls.map(k=>[k.partNumber,k.url])),p=new Array(o),c=new Array(o).fill(0),f=1,h=e.size,u=()=>{var g;let k=c.reduce((T,y)=>T+y,0),E=h>0?Math.min(100,Math.round(k/h*100)):100,$={totalBytes:h,loaded:k,totalPercent:E};(g=r.onFileUploadProgress)==null||g.call(r,i,$)},R=async()=>{var k,E,$,g,T;for(;;){if((k=r.signal)!=null&&k.aborted)throw v("ABORTED","Upload aborted by caller.",{retryable:!1});let y=f++;if(y>o)return;let O=(y-1)*s,_=Math.min(O+s,e.size),A=e.slice(O,_),B=0,H;for(;B<=l;){if((E=r.signal)!=null&&E.aborted)throw v("ABORTED","Upload aborted by caller.",{retryable:!1});try{let U=d.get(y);U||(U=(await this.api("POST","/sdk/v1/uploads/sign-part",{sessionId:t.sessionId,partNumber:y},r.signal)).url,d.set(y,U));let P=(T=await((g=($=this.cfg).fetch)==null?void 0:g.call($,U,{method:"PUT",body:A,signal:r.signal})))!=null?T:await fetch(U,{method:"PUT",body:A,signal:r.signal});if(!P.ok)throw(P.status===403||P.status===401)&&d.delete(y),v("PART_FAILED",`Part ${y} PUT failed (HTTP ${P.status})`,{status:P.status});let N=P.headers.get("etag");if(!N)throw v("PART_FAILED",`Part ${y}: R2 did not return an ETag.`);p[y-1]={partNumber:y,etag:N,size:A.size},c[y-1]=A.size,u();break}catch(U){if(H=U,B++,B>l)break;await Be(pe[Math.min(B-1,pe.length-1)])}}if(!p[y-1])throw He(ce(H!=null?H:v("PART_FAILED",`Part ${y} failed after ${l} retries.`)),t.sessionId)}},F=Array.from({length:Math.min(a,o)},R);return await Promise.all(F),p}async completeUpload(e,t,i){return this.api("POST","/sdk/v1/uploads/complete",{sessionId:e,parts:t.map(r=>({partNumber:r.partNumber,etag:r.etag}))},i.signal)}async abortSilently(e){try{await this.abort(e)}catch(t){}}async api(e,t,i,r){var d,p;let o=(d=this.cfg.fetch)!=null?d:fetch,s=`${this.cfg.apiBase}${t}`,a;try{a=await o(s,{method:e,headers:{Authorization:`Bearer ${this.cfg.apiKey}`,"Content-Type":"application/json","X-UnionStack-SDK":(p=this.cfg.sdkHeader)!=null?p:de},body:i===void 0?void 0:JSON.stringify(i),signal:r})}catch(c){throw(c==null?void 0:c.name)==="AbortError"?v("ABORTED","Request aborted.",{retryable:!1,cause:c}):v("NETWORK","Network request failed.",{retryable:!0,cause:c})}let l=null;try{l=await a.json()}catch(c){}if(!a.ok)throw ae(a.status,l);return l}};function Ae(){return typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36)}function Be(n){return new Promise(e=>setTimeout(e,n))}function ce(n){if(n&&typeof n=="object"&&"code"in n&&"message"in n&&"retryable"in n)return n;let e=(n==null?void 0:n.message)||"Upload failed.";return v("NETWORK",e,{cause:n})}function He(n,e){return n&&typeof n=="object"&&(n.sessionId=e),n}var tt="https://api.unionstack.link/v1",Ce="unionstack-preloader-styles";function it(){if(typeof document=="undefined")return()=>{};if(!document.getElementById(Ce)){let i=document.createElement("style");i.id=Ce,i.textContent="@keyframes us-preload-spin{to{transform:rotate(360deg)}}@keyframes us-preload-fade{from{opacity:0}to{opacity:1}}",document.head.appendChild(i)}let n=document.createElement("div");n.setAttribute("role","status"),n.setAttribute("aria-label","Loading file picker"),n.style.cssText="position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;background:rgba(2,6,23,0.4);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);animation:us-preload-fade 140ms ease-out;";let e=document.createElement("div");e.style.cssText="width:36px;height:36px;border-radius:50%;border:3px solid rgba(220,225,251,0.25);border-top-color:#c0c1ff;animation:us-preload-spin 0.8s linear infinite;",n.appendChild(e),document.body.appendChild(n);let t=!1;return()=>{t||(t=!0,n.remove())}}var D=class{constructor(e){e.apiKey||console.error("[UnionStack] apiKey is not set. Uploads and the picker are disabled until a valid apiKey is provided."),this.resolvedCfg=I(C({},e),{apiBase:tt}),this.uploader=new K(this.resolvedCfg),this.pickerConfigPromise=!e.apiKey||this.resolvedCfg.skipConfigPrefetch?Promise.resolve(null):this.uploader.fetchPickerConfig().then(t=>(t!=null&&t.sdkWarning&&console.warn(`[UnionStack] ${t.sdkWarning}`),t)).catch(()=>null)}missingKeyError(){return this.resolvedCfg.apiKey?null:v("CONFIG","apiKey is required.",{retryable:!1})}upload(e,t={}){let i=this.missingKeyError();return i?Promise.reject(i):this.uploader.upload(e,t)}async uploadMany(e,t={}){var l,d,p,c;let i=this.missingKeyError();if(i)throw(l=t.onError)==null||l.call(t,i),i;if(!Array.isArray(e)||e.length===0){let f=v("VALIDATION","uploadMany requires a non-empty array of files.",{retryable:!1});throw(d=t.onError)==null||d.call(t,f),f}let r=e.map(f=>this.uploader.describe(f,{filename:t.filename,mimeType:t.mimeType}));(p=t.onUploadStarted)==null||p.call(t,r);let o=[],s=[];await Promise.all(e.map(async(f,h)=>{try{let u=await this.uploader.upload(f,t);u.uploadId=r[h].uploadId,o.push(u)}catch(u){s.push({file:r[h],error:u})}}));let a={filesUploaded:o,filesFailed:s};return(c=t.onUploadDone)==null||c.call(t,a),a}picker(e={}){let t=null,i=!1,r,o,s=new Promise((a,l)=>{r=a,o=l});return{open:async()=>{if(i)return s;let a=this.missingKeyError();if(a)throw o(a),a;i=!0;let l=it();try{t=(await Promise.resolve().then(()=>(ee(),we))).openPicker(this,I(C({},e),{onOpen:()=>{var c;l(),(c=e.onOpen)==null||c.call(e)}}));let p=await t.open();return l(),r(p),p}catch(d){l();let p=d!=null&&d.code?d:v("CONFIG","Failed to load picker.",{retryable:!1,cause:d});throw o(p),p}},close:()=>{t==null||t.close()},cancel:()=>{t==null||t.cancel()}}}get config(){return this.resolvedCfg}};var J={init(n){return new D(n)}};ee();var rt=J.init.bind(J);(function(){if(typeof document=="undefined")return;let e=document.currentScript;if(!e)return;let t=e.getAttribute("data-unionstack-key");if(t)try{let i=J.init({apiKey:t});queueMicrotask(()=>{window.UnionStack&&(window.UnionStack.client=i)})}catch(i){console.error("[UnionStack] auto-init failed:",i)}})();return Me(ot);})();
543
+ `});function w(n,e,t){let i=document.createElement(n);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function V(n,e){let t=document.createElement("button");return t.type="button",t.className="us-tool",t.innerHTML=`${e} <span>${_e(n)}</span>`,t}function _e(n){return n.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function x(n,e,t){return Math.max(e,Math.min(t,n))}function ve(n){return new Promise((e,t)=>{let i=URL.createObjectURL(n),r=new Image;r.onload=()=>{URL.revokeObjectURL(i),e(r)},r.onerror=()=>{URL.revokeObjectURL(i),t(new Error("decode failed"))},r.src=i})}function be(n){return/^image\/(png|webp|gif)$/.test(n)}var L,X,ye=q(()=>{"use strict";L={back:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>',crop:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M6 2v14a2 2 0 0 0 2 2h14"/><path d="M18 22V8a2 2 0 0 0-2-2H2"/></svg>',circle:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/></svg>',rotate:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.82.93 6.58 2.46L21 8"/><path d="M21 3v5h-5"/></svg>',undo:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-15-6.7L3 13"/></svg>',check:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>'},X=class{constructor(e){this.opts=e;this.cropBox=null;this.hasAlpha=!1;this.mode="none";this.cropRect=null;this.dragKind=null;this.dragStart=null;this.onPointerMove=e=>{if(!this.dragKind||!this.dragStart||!this.cropRect)return;let t=this.canvasMetrics(),i=(e.clientX-this.dragStart.px)/(t.scaleX||1),r=(e.clientY-this.dragStart.py)/(t.scaleY||1),o=this.dragStart.rect,s=this.working.width,a=this.working.height,l=this.minCropImg();if(this.aspect&&this.dragKind!=="move"){switch(this.dragKind){case"se":this.cropRect=this.lockedRectFromDrag(o.x,o.y,o.w+i,1,1);break;case"nw":{let h=o.x+o.w,u=o.y+o.h;this.cropRect=this.lockedRectFromDrag(h,u,h-(o.x+i),-1,-1);break}case"ne":{let h=o.y+o.h;this.cropRect=this.lockedRectFromDrag(o.x,h,o.w+i,1,-1);break}case"sw":{let h=o.x+o.w;this.cropRect=this.lockedRectFromDrag(h,o.y,h-(o.x+i),-1,1);break}}this.updateCropBox();return}let{x:p,y:d,w:c,h:f}=o;switch(this.dragKind){case"move":p=x(o.x+i,0,s-o.w),d=x(o.y+r,0,a-o.h);break;case"nw":{let h=x(o.x+i,0,o.x+o.w-l),u=x(o.y+r,0,o.y+o.h-l);c=o.w+(o.x-h),f=o.h+(o.y-u),p=h,d=u;break}case"ne":{let h=x(o.w+i,l,s-o.x),u=x(o.y+r,0,o.y+o.h-l);f=o.h+(o.y-u),c=h,d=u;break}case"sw":{let h=x(o.x+i,0,o.x+o.w-l),u=x(o.h+r,l,a-o.y);c=o.w+(o.x-h),f=u,p=h;break}case"se":c=x(o.w+i,l,s-o.x),f=x(o.h+r,l,a-o.y);break}this.cropRect={x:p,y:d,w:c,h:f},this.updateCropBox()};this.onPointerUp=()=>{this.dragKind=null,this.dragStart=null,document.removeEventListener("pointermove",this.onPointerMove),document.removeEventListener("pointerup",this.onPointerUp)}}get aspect(){let e=this.opts.lockedAspect;return e&&e.width>0&&e.height>0?e.width/e.height:null}async open(){this.mount();try{await this.loadOriginalIntoWorking(),this.opts.originalFile&&this.opts.originalFile!==this.opts.file&&this.markEdited(!0),this.draw()}catch(e){this.canvasWrap.textContent=`Couldn't load image: ${e.message}`}}close(){document.removeEventListener("pointermove",this.onPointerMove),document.removeEventListener("pointerup",this.onPointerUp),this.root.remove()}mount(){this.root=w("div","us-editor");let e=w("div","us-editor-header"),t=document.createElement("button");t.type="button",t.className="us-editor-back",t.setAttribute("aria-label","Back"),t.innerHTML=L.back,t.onclick=()=>{this.opts.onCancel(),this.close()},e.appendChild(t),e.appendChild(w("div","us-editor-title",this.opts.title)),this.root.appendChild(e),this.canvasWrap=w("div","us-editor-canvas-wrap"),this.displayCanvas=document.createElement("canvas"),this.displayCanvas.className="us-editor-canvas",this.canvasWrap.appendChild(this.displayCanvas),this.root.appendChild(this.canvasWrap),this.cropDims=w("div","us-crop-dims"),this.cropDims.hidden=!0,this.widthInput=this.makeDimInput("Crop width in pixels","w"),this.heightInput=this.makeDimInput("Crop height in pixels","h"),this.cropDims.appendChild(w("span","us-crop-dims-label","Crop size")),this.cropDims.appendChild(this.widthInput),this.cropDims.appendChild(w("span","us-crop-dims-x","\xD7")),this.cropDims.appendChild(this.heightInput),this.cropDims.appendChild(w("span","us-crop-dims-unit","px")),this.root.appendChild(this.cropDims);let i=w("div","us-editor-toolbar");this.cropTool=V("Crop",L.crop),this.cropTool.onclick=()=>this.toggleCropMode(),this.circleTool=V("Circle",L.circle),this.circleTool.onclick=()=>this.applyCircle(),this.rotateTool=V("Rotate 90\xB0",L.rotate),this.rotateTool.onclick=()=>this.applyRotate(),this.revertTool=V("Revert",L.undo),this.revertTool.onclick=()=>this.revert(),this.revertTool.disabled=!0,i.appendChild(this.cropTool),i.appendChild(this.circleTool),i.appendChild(this.rotateTool),i.appendChild(w("div","us-tool-spacer")),i.appendChild(this.revertTool),this.root.appendChild(i);let r=w("div","us-editor-footer"),o=document.createElement("button");o.type="button",o.className="us-btn",o.textContent="Cancel",o.onclick=()=>{this.opts.onCancel(),this.close()},this.applyBtn=document.createElement("button"),this.applyBtn.type="button",this.applyBtn.className="us-btn us-btn-primary",this.applyBtn.innerHTML=`${L.check} <span>Apply</span>`,this.applyBtn.onclick=()=>this.applyAndClose(),r.appendChild(o),r.appendChild(this.applyBtn),this.root.appendChild(r),this.opts.host.appendChild(this.root)}async loadOriginalIntoWorking(){let e=await ve(this.opts.file),t=document.createElement("canvas");t.width=e.naturalWidth,t.height=e.naturalHeight;let i=t.getContext("2d");if(!i)throw new Error("Canvas 2D context unavailable");i.drawImage(e,0,0),this.working=t,this.hasAlpha=be(this.opts.file.type),this.markEdited(!1)}async loadTrueOriginalIntoWorking(){var o;let e=(o=this.opts.originalFile)!=null?o:this.opts.file,t=await ve(e),i=document.createElement("canvas");i.width=t.naturalWidth,i.height=t.naturalHeight;let r=i.getContext("2d");if(!r)throw new Error("Canvas 2D context unavailable");r.drawImage(t,0,0),this.working=i,this.hasAlpha=be(e.type),this.markEdited(!1)}draw(){let{width:e,height:t}=this.working,i=Math.min(1,720/Math.max(e,t)),r=Math.max(1,Math.round(e*i)),o=Math.max(1,Math.round(t*i));this.displayCanvas.width=r,this.displayCanvas.height=o;let s=this.displayCanvas.getContext("2d");s&&(s.clearRect(0,0,r,o),s.drawImage(this.working,0,0,r,o),this.updateCropBox())}toggleCropMode(){this.mode==="crop"?this.applyCrop():this.enterCropMode()}enterCropMode(){this.mode="crop",this.cropTool.dataset.active="true",this.cropTool.innerHTML=`${L.check} <span>Apply crop</span>`;let e=this.working.width,t=this.working.height;if(this.aspect){let r=this.aspect,o=this.minCropImg(),s=e,a=s/r;a>t&&(a=t,s=a*r),s=s*.9,a=s/r,s<o&&(s=o,a=s/r),a<o&&(a=o,s=a*r),s>e&&(s=e,a=s/r),a>t&&(a=t,s=a*r),this.cropRect={x:Math.round((e-s)/2),y:Math.round((t-a)/2),w:s,h:a}}else{let r=Math.round(Math.min(e,t)*.1);this.cropRect={x:r,y:r,w:e-r*2,h:t-r*2}}this.renderCropBox();let i=this.aspect!==null;this.widthInput.readOnly=i,this.heightInput.readOnly=i,this.cropDims.dataset.locked=i?"true":"false",this.cropDims.hidden=!1,this.syncCropDimsInputs()}exitCropMode(){this.mode="none",this.cropTool.removeAttribute("data-active"),this.cropTool.innerHTML=`${L.crop} <span>Crop</span>`,this.cropRect=null,this.cropBox&&(this.cropBox.remove(),this.cropBox=null),this.cropDims.hidden=!0}makeDimInput(e,t){let i=document.createElement("input");return i.type="number",i.min="1",i.inputMode="numeric",i.className="us-crop-dim-input",i.setAttribute("aria-label",e),i.addEventListener("input",()=>this.onDimInput(t)),i.addEventListener("change",()=>this.syncCropDimsInputs()),i}syncCropDimsInputs(){if(!this.cropRect||!this.widthInput||!this.heightInput)return;let e=Math.max(1,Math.round(this.cropRect.w)),t=Math.max(1,Math.round(this.cropRect.h));document.activeElement!==this.widthInput&&(this.widthInput.value=String(e)),document.activeElement!==this.heightInput&&(this.heightInput.value=String(t))}onDimInput(e){if(this.aspect!==null||!this.cropRect)return;let t=e==="w"?this.widthInput:this.heightInput,i=parseInt(t.value,10);if(!Number.isFinite(i)||i<=0)return;let r=this.minCropImg();if(e==="w"){let o=this.working.width-this.cropRect.x;this.cropRect=U(C({},this.cropRect),{w:x(i,r,o)})}else{let o=this.working.height-this.cropRect.y;this.cropRect=U(C({},this.cropRect),{h:x(i,r,o)})}this.updateCropBox()}renderCropBox(){if(!this.cropRect)return;this.cropBox&&this.cropBox.remove();let e=w("div","us-crop-box");for(let t of["nw","ne","sw","se"]){let i=w("div","us-crop-handle");i.dataset.pos=t,i.addEventListener("pointerdown",r=>this.beginDrag(r,t)),e.appendChild(i)}e.addEventListener("pointerdown",t=>{t.target.classList.contains("us-crop-handle")||this.beginDrag(t,"move")}),this.canvasWrap.appendChild(e),this.cropBox=e,this.updateCropBox()}canvasMetrics(){let e=this.displayCanvas.getBoundingClientRect(),t=this.canvasWrap.getBoundingClientRect();return{scaleX:e.width/(this.working.width||1),scaleY:e.height/(this.working.height||1),offX:e.left-t.left,offY:e.top-t.top}}minCropImg(){let{scaleX:e}=this.canvasMetrics();return e>0?24/e:24}updateCropBox(){if(!this.cropBox||!this.cropRect)return;let e=this.canvasMetrics();this.cropBox.style.left=`${e.offX+this.cropRect.x*e.scaleX}px`,this.cropBox.style.top=`${e.offY+this.cropRect.y*e.scaleY}px`,this.cropBox.style.width=`${this.cropRect.w*e.scaleX}px`,this.cropBox.style.height=`${this.cropRect.h*e.scaleY}px`,this.syncCropDimsInputs()}beginDrag(e,t){this.cropRect&&(e.preventDefault(),this.dragKind=t,this.dragStart={px:e.clientX,py:e.clientY,rect:C({},this.cropRect)},document.addEventListener("pointermove",this.onPointerMove),document.addEventListener("pointerup",this.onPointerUp))}lockedRectFromDrag(e,t,i,r,o){let s=this.aspect,a=this.working.width,l=this.working.height,p=this.minCropImg(),d=Math.max(p,i),c=d/s;c<p&&(c=p,d=c*s);let f=r>0?a-e:e,h=o>0?l-t:t;d=Math.min(d,f,h*s),c=d/s;let u=r>0?e:e-d,R=o>0?t:t-c;return{x:u,y:R,w:d,h:c}}applyCrop(){var a,l;if(!this.cropRect){this.exitCropMode();return}let e=x(Math.round(this.cropRect.x),0,this.working.width-1),t=x(Math.round(this.cropRect.y),0,this.working.height-1),i=x(Math.round(this.cropRect.w),1,this.working.width-e),r=x(Math.round(this.cropRect.h),1,this.working.height-t),o=document.createElement("canvas");o.width=i,o.height=r;let s=o.getContext("2d");s&&(s.drawImage(this.working,e,t,i,r,0,0,i,r),this.working=o,this.exitCropMode(),this.markEdited(!0),(l=(a=this.opts).onCropApplied)==null||l.call(a),this.draw())}applyRotate(){var o,s;let{width:e,height:t}=this.working,i=document.createElement("canvas");i.width=t,i.height=e;let r=i.getContext("2d");r&&(r.translate(t,0),r.rotate(Math.PI/2),r.drawImage(this.working,0,0),this.working=i,this.exitCropMode(),this.markEdited(!0),(s=(o=this.opts).onAspectReset)==null||s.call(o),this.draw())}applyCircle(){var l,p;let{width:e,height:t}=this.working,i=Math.min(e,t),r=Math.round((e-i)/2),o=Math.round((t-i)/2),s=document.createElement("canvas");s.width=i,s.height=i;let a=s.getContext("2d");a&&(a.save(),a.beginPath(),a.arc(i/2,i/2,i/2,0,Math.PI*2),a.closePath(),a.clip(),a.drawImage(this.working,r,o,i,i,0,0,i,i),a.restore(),this.working=s,this.hasAlpha=!0,this.exitCropMode(),this.markEdited(!0),(p=(l=this.opts).onAspectReset)==null||p.call(l),this.draw())}async revert(){var e,t;await this.loadTrueOriginalIntoWorking(),this.exitCropMode(),(t=(e=this.opts).onAspectReset)==null||t.call(e),this.draw()}markEdited(e){this.revertTool.disabled=!e}async applyAndClose(){this.applyBtn.disabled=!0,this.mode==="crop"&&this.applyCrop();try{let e=await this.exportFile();this.opts.onApply(e),this.close()}catch(e){this.applyBtn.disabled=!1,console.error("[union-stack] image export failed",e)}}exportFile(){return new Promise((e,t)=>{let i=this.hasAlpha?"image/png":"image/jpeg",r=i==="image/jpeg"?.92:void 0;this.working.toBlob(o=>{if(!o)return t(new Error("toBlob returned null"));let s=this.opts.file.name.replace(/\.[^.]+$/,""),a=i==="image/png"?"png":"jpg";e(new File([o],`${s}-edited.${a}`,{type:i}))},i,r)})}}});function We(n,e){var a,l,p,d,c,f,h,u,R,F,M,S,k,E,I,g,T,y,O,_,A,B,z,$,P,N,Z,te;let t=C({},e),i=e.branding||{};t.branding={logoUrl:(l=(a=i.logoUrl)!=null?a:n.branding.logoUrl)!=null?l:void 0,title:(d=(p=i.title)!=null?p:n.branding.title)!=null?d:void 0,hideFooter:(c=i.hideFooter)!=null?c:n.branding.hideFooter};let r=e.theme||{};if(t.theme={primary:(h=(f=r.primary)!=null?f:n.theme.primary)!=null?h:void 0,background:(R=(u=r.background)!=null?u:n.theme.background)!=null?R:void 0,foreground:(M=(F=r.foreground)!=null?F:n.theme.foreground)!=null?M:void 0,border:(k=(S=r.border)!=null?S:n.theme.border)!=null?k:void 0,radius:(I=(E=r.radius)!=null?E:n.theme.radius)!=null?I:void 0,mode:(T=(g=r.mode)!=null?g:n.theme.mode)!=null?T:void 0},t.maxFileSize=(y=e.maxFileSize)!=null?y:n.constraints.maxFileSizeBytes,t.maxFiles=(O=e.maxFiles)!=null?O:n.constraints.maxFilesPerUpload,!e.accept&&((_=n.constraints.allowedMimeTypes)!=null&&_.length)){let ie=n.constraints.allowedMimeTypes.filter(Ee=>Ee!=="*/*");ie.length>0&&(t.accept=ie.join(","))}let o=(A=n.image)!=null?A:null,s=(B=e.cropAspectRatio)!=null?B:o&&o.cropRatioW&&o.cropRatioH?{width:o.cropRatioW,height:o.cropRatioH}:void 0;return t.cropAspectRatio=s,t.forceCrop=(($=(z=e.forceCrop)!=null?z:o==null?void 0:o.forceCrop)!=null?$:!1)&&!!s&&e.imageEditing!==!1,t.minImageWidth=(N=(P=e.minImageWidth)!=null?P:o==null?void 0:o.minWidth)!=null?N:void 0,t.minImageHeight=(te=(Z=e.minImageHeight)!=null?Z:o==null?void 0:o.minHeight)!=null?te:void 0,t}function Y(n){return n?n.startsWith("image/")?b.image:n.startsWith("video/")?b.video:n.startsWith("audio/")?b.audio:n==="application/pdf"?b.pdf:n.startsWith("application/zip")||n.includes("compressed")||n==="application/x-tar"||n==="application/gzip"?b.archive:b.file:b.file}function m(n,e,t){let i=document.createElement(n);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function Ye(n){var i,r,o;let e=n.trim().toLowerCase();if(!e)return"";if(e.endsWith("/*")||!e.includes("/")){let s=e.replace("/*","");return(i=Xe[s])!=null?i:s.charAt(0).toUpperCase()+s.slice(1)}if(xe[e])return xe[e];if(e.startsWith("."))return e.slice(1).toUpperCase();let t=(r=e.split("/")[1])!=null?r:e;return((o=t.split("+")[0].split(".").pop())!=null?o:t).toUpperCase()}function j(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:n<1024*1024*1024?`${(n/1024/1024).toFixed(1)} MB`:`${(n/1024/1024/1024).toFixed(2)} GB`}function G(){return typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36)}async function Ge(n){var e;if(typeof createImageBitmap=="function")try{let t=await createImageBitmap(n),i=t.width,r=t.height;return(e=t.close)==null||e.call(t),{w:i,h:r}}catch(t){}return new Promise((t,i)=>{if(typeof URL=="undefined"||!URL.createObjectURL){i(new Error("no object URL support"));return}let r=URL.createObjectURL(n),o=new Image;o.onload=()=>{URL.revokeObjectURL(r),t({w:o.naturalWidth,h:o.naturalHeight})},o.onerror=()=>{URL.revokeObjectURL(r),i(new Error("decode failed"))},o.src=r})}async function Je(n){let e;try{e=await fetch(n,{mode:"cors",credentials:"omit"})}catch(o){throw new Error(`Could not reach ${Qe(n)} \u2014 check the URL or CORS.`)}if(!e.ok)throw new Error(`Server returned ${e.status} \u2014 file unavailable.`);let t=await e.blob(),i=Ze(n)||"download",r=t.type||et(i);return new File([t],i,{type:r})}function Qe(n){try{return new URL(n).host}catch(e){return"that host"}}function Ze(n){try{let t=new URL(n).pathname.split("/").filter(Boolean).pop();return t?decodeURIComponent(t):""}catch(e){return""}}function et(n){let e=n.toLowerCase().split(".").pop()||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",mp4:"video/mp4",mov:"video/quicktime",mp3:"audio/mpeg",wav:"audio/wav",zip:"application/zip",json:"application/json",txt:"text/plain",csv:"text/csv"}[e]||"application/octet-stream"}function J(n,e){let t=new H(n,e);return{open:()=>t.open(),close:()=>t.close(),cancel:()=>t.cancel()}}var qe,Ke,b,Ve,H,xe,Xe,ke=q(()=>{"use strict";ge();ye();qe="Upload files",Ke="https://unionstack.link",b={upload:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>',fileUp:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><path d="M12 18v-6"/><path d="m9 15 3-3 3 3"/></svg>',close:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',check:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',alert:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',spinner:'<svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="9" stroke="currentColor" opacity="0.2"/><path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor"/></svg>',clock:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><polyline points="12 7.5 12 12 15 13.5"/></svg>',image:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>',video:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>',audio:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>',pdf:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="9" y1="13" x2="15" y2="13"/><line x1="9" y1="17" x2="13" y2="17"/></svg>',archive:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="5" rx="2"/><path d="M4 9v9a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9"/><line x1="10" y1="13" x2="14" y2="13"/></svg>',file:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>',zap:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>',device:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>',link:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.72"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.72-1.72"/></svg>',pencil:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>'};Ve='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',H=class{constructor(e,t){this.client=e;this.opts=t;this.$backdrop=null;this.$panel=null;this.$list=null;this.$confirm=null;this.$cancel=null;this.$closeBtn=null;this.$input=null;this.$deviceSource=null;this.$urlSource=null;this.$urlInput=null;this.$urlHint=null;this.$urlAddBtn=null;this.items=[];this.editor=null;this.abortCtrl=new AbortController;this.uploadStarted=!1;this.validateSeqCounter=0;this.resolved=!1;this.previouslyFocused=null;this.noticeTimer=null;this.$summary=null;this.donePromise=new Promise(i=>{this.resolvePromise=i})}async open(){var e,t;if(typeof document=="undefined")throw new Error("[union-stack] Picker requires a browser environment.");try{let i=await this.client.pickerConfigPromise;i&&(this.opts=We(i,this.opts))}catch(i){}return me(),this.mount(),(t=(e=this.opts).onOpen)==null||t.call(e),this.donePromise}close(){this.unmount(),this.resolved||this.resolveResult()}cancel(){var e,t;this.abortCtrl.abort(),(t=(e=this.opts).onCancel)==null||t.call(e),this.close()}get acceptStr(){let e=this.opts.accept;return Array.isArray(e)?e.join(","):e!=null?e:""}mount(){var h,u,R,F,M,S,k,E,I;this.previouslyFocused=(h=document.activeElement)!=null?h:null;let e=document.createElement("div");e.className="us-picker-backdrop",Object.entries(fe(this.opts.theme)).forEach(([g,T])=>{e.style.setProperty(g,T)}),e.style.colorScheme=((u=this.opts.theme)==null?void 0:u.mode)==="dark"?"dark":"light",e.addEventListener("click",g=>{g.target===e&&!this.uploadStarted&&this.cancel()});let t=m("div","us-picker");this.$panel=t;let i=`us-picker-title-${G()}`;t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-labelledby",i),t.tabIndex=-1,t.addEventListener("keydown",g=>{g.key==="Escape"&&!this.uploadStarted?(g.preventDefault(),this.cancel()):g.key==="Tab"&&this.trapFocus(g)});let r=m("div","us-picker-header"),o=m("div","us-picker-header-logo");if((R=this.opts.branding)!=null&&R.logoUrl){let g=document.createElement("img");g.src=this.opts.branding.logoUrl,g.alt="",o.appendChild(g)}else o.innerHTML=b.zap;r.appendChild(o);let s=m("div","us-picker-title",(M=(F=this.opts.branding)==null?void 0:F.title)!=null?M:qe);s.id=i,r.appendChild(s),this.$closeBtn=document.createElement("button"),this.$closeBtn.type="button",this.$closeBtn.className="us-picker-close",this.$closeBtn.setAttribute("aria-label","Close"),this.$closeBtn.innerHTML=b.close,this.$closeBtn.onclick=()=>this.cancel(),r.appendChild(this.$closeBtn),t.appendChild(r);let a=m("div","us-picker-body"),l=this.resolvedSources();l.length>1&&a.appendChild(this.renderSourceTabs(l)),l.includes("device")&&(this.$deviceSource=this.renderDropzone(),a.appendChild(this.$deviceSource)),l.includes("url")&&(this.$urlSource=this.renderUrlSource(),a.appendChild(this.$urlSource)),this.$list=m("div","us-file-list"),a.appendChild(this.$list),t.appendChild(a),this.activateSource((S=l[0])!=null?S:"device");let p=this.opts.autoUpload===!0,d=m("div","us-actions");this.$summary=m("div","us-actions-summary",""),this.$summary.setAttribute("role","status"),this.$summary.setAttribute("aria-live","polite"),d.appendChild(this.$summary);let c=m("div","us-actions-buttons");if(this.$cancel=document.createElement("button"),this.$cancel.type="button",this.$cancel.className="us-btn",this.$cancel.textContent="Cancel",this.$cancel.onclick=()=>this.cancel(),c.appendChild(this.$cancel),p||(this.$confirm=document.createElement("button"),this.$confirm.type="button",this.$confirm.className="us-btn us-btn-primary",this.$confirm.innerHTML=`${b.upload} <span>Upload</span>`,this.$confirm.disabled=!0,this.$confirm.onclick=()=>this.startUpload(),c.appendChild(this.$confirm)),d.appendChild(c),t.appendChild(d),!((k=this.opts.branding)!=null&&k.hideFooter)){let g=m("div","us-footer");g.innerHTML=`${b.zap} <span>Powered by <a href="${Ke}" target="_blank" rel="noopener">UnionStack</a></span>`,t.appendChild(g)}e.appendChild(t),((E=this.opts.container)!=null?E:document.body).appendChild(e),this.$backdrop=e,((I=t.querySelector('.us-source-tab[data-active="true"]'))!=null?I:t).focus()}trapFocus(e){if(!this.$panel)return;let t=Array.from(this.$panel.querySelectorAll(Ve)).filter(s=>!s.hasAttribute("disabled")&&s.offsetParent!==null);if(t.length===0)return;let i=t[0],r=t[t.length-1],o=document.activeElement;e.shiftKey&&o===i?(e.preventDefault(),r.focus()):!e.shiftKey&&o===r&&(e.preventDefault(),i.focus())}resolvedSources(){let e=this.opts.fromSources;return!e||e.length===0?["device","url"]:e}renderSourceTabs(e){let t=m("div","us-source-tabs");return t.setAttribute("role","tablist"),t.setAttribute("aria-label","Upload source"),e.forEach((i,r)=>{let o=document.createElement("button");o.type="button",o.className="us-source-tab",o.setAttribute("role","tab"),o.setAttribute("aria-selected","false"),o.tabIndex=-1,o.dataset.source=i,o.innerHTML=i==="device"?`${b.device} <span>My Device</span>`:`${b.link} <span>Link</span>`,o.onclick=()=>this.activateSource(i),o.onkeydown=s=>this.onTabKeydown(s,e,r),t.appendChild(o)}),t}onTabKeydown(e,t,i){var o,s;let r=i;if(e.key==="ArrowRight"||e.key==="ArrowDown")r=(i+1)%t.length;else if(e.key==="ArrowLeft"||e.key==="ArrowUp")r=(i-1+t.length)%t.length;else if(e.key==="Home")r=0;else if(e.key==="End")r=t.length-1;else return;e.preventDefault(),this.activateSource(t[r]),(s=(o=this.$panel)==null?void 0:o.querySelector(`.us-source-tab[data-source="${t[r]}"]`))==null||s.focus()}activateSource(e){var i;if(this.$deviceSource){let r=e==="device";this.$deviceSource.style.display=r?"":"none"}this.$urlSource&&(this.$urlSource.dataset.active=e==="url"?"true":"false");let t=(i=this.$panel)==null?void 0:i.querySelectorAll(".us-source-tab");t==null||t.forEach(r=>{let o=r.dataset.source===e;r.dataset.active=o?"true":"false",r.setAttribute("aria-selected",o?"true":"false"),r.tabIndex=o?0:-1})}renderUrlSource(){let e=m("div","us-url-source"),t=m("div","us-url-form"),i=document.createElement("input");i.type="url",i.className="us-url-input",i.placeholder="https://example.com/photo.jpg",i.setAttribute("aria-label","File URL"),i.onkeydown=s=>{s.key==="Enter"&&(s.preventDefault(),this.handleUrlAdd())},this.$urlInput=i;let r=document.createElement("button");r.type="button",r.className="us-btn us-btn-primary",r.textContent="Add file",r.onclick=()=>this.handleUrlAdd(),this.$urlAddBtn=r,t.appendChild(i),t.appendChild(r),e.appendChild(t);let o=m("div","us-url-hint","Paste a direct file URL. The host must allow CORS so we can fetch it from the browser.");return this.$urlHint=o,e.appendChild(o),e}async handleUrlAdd(){if(!this.$urlInput||!this.$urlAddBtn||!this.$urlHint)return;let e=this.$urlInput.value.trim();if(!e){this.setUrlHint("Enter a URL first.",!0);return}if(!/^https?:\/\//i.test(e)){this.setUrlHint("URL must start with http:// or https://",!0);return}this.$urlAddBtn.disabled=!0;let t=this.$urlAddBtn.textContent;this.$urlAddBtn.textContent="Fetching\u2026",this.setUrlHint("Downloading\u2026",!1);try{let i=await Je(e);this.addFiles([i]),this.$urlInput.value="",this.setUrlHint("Paste a direct file URL. The host must allow CORS so we can fetch it from the browser.",!1)}catch(i){let r=i.message||"Failed to fetch URL";this.setUrlHint(r,!0)}finally{this.$urlAddBtn.disabled=!1,this.$urlAddBtn.textContent=t||"Add file"}}setUrlHint(e,t){this.$urlHint&&(this.$urlHint.textContent=e,this.$urlHint.dataset.error=t?"true":"false")}renderDropzone(){var s;let e=m("div","us-dropzone");e.setAttribute("role","button"),e.setAttribute("tabindex","0"),e.setAttribute("aria-label","Drop files here or click to browse");let t=m("div","us-dropzone-icon");t.innerHTML=b.fileUp,e.appendChild(t),e.appendChild(m("div","us-dropzone-title","Drop files to upload")),e.appendChild(m("div","us-dropzone-hint","or click to browse from your device"));let i=[];if(this.opts.maxFileSize&&i.push(`max ${j(this.opts.maxFileSize)}`),this.acceptStr){let a=[],l=new Set;for(let p of this.acceptStr.split(",")){let d=p.trim();if(!d||d==="*/*")continue;let c=Ye(d);c&&!l.has(c)&&(l.add(c),a.push(c))}a.length>0&&i.push(a.length>5?`${a.slice(0,5).join(", ")} +${a.length-5}`:a.join(", "))}i.length>0&&e.appendChild(m("div","us-dropzone-constraints",i.join(" \xB7 ")));let r=document.createElement("input");r.type="file",r.multiple=((s=this.opts.maxFiles)!=null?s:10)>1,this.acceptStr&&(r.accept=this.acceptStr),r.style.display="none",r.onchange=()=>{r.files&&this.addFiles(Array.from(r.files)),r.value=""},this.$input=r,e.appendChild(r),e.onclick=()=>r.click(),e.onkeydown=a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r.click())};let o=0;return e.addEventListener("dragenter",a=>{a.preventDefault(),o++,e.setAttribute("data-drag","over")}),e.addEventListener("dragover",a=>a.preventDefault()),e.addEventListener("dragleave",()=>{o=Math.max(0,o-1),o===0&&e.removeAttribute("data-drag")}),e.addEventListener("drop",a=>{var p;a.preventDefault(),o=0,e.removeAttribute("data-drag");let l=(p=a.dataTransfer)==null?void 0:p.files;l&&this.addFiles(Array.from(l))}),e}unmount(){var e,t,i,r,o;this.editor&&(this.editor.close(),this.editor=null),this.noticeTimer&&(clearTimeout(this.noticeTimer),this.noticeTimer=null),(e=this.$backdrop)!=null&&e.parentNode&&this.$backdrop.parentNode.removeChild(this.$backdrop),this.$backdrop=null,this.$panel=null;for(let s of this.items)s.objectUrl&&URL.revokeObjectURL(s.objectUrl);(i=(t=this.previouslyFocused)==null?void 0:t.focus)==null||i.call(t),this.previouslyFocused=null,(o=(r=this.opts).onClose)==null||o.call(r)}fileMatchesAccept(e){let t=this.acceptStr.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean);if(t.length===0||t.includes("*/*"))return!0;let i=(e.type||"").toLowerCase(),r=e.name.toLowerCase();return t.some(o=>o.startsWith(".")?r.endsWith(o):o.endsWith("/*")?i.startsWith(o.slice(0,-1)):i===o)}addFiles(e){var p;let t=(p=this.opts.maxFiles)!=null?p:1/0,i=0,r=e.filter(d=>this.fileMatchesAccept(d)?!0:(i++,!1)),o=t-this.items.length,s=o>0?r.slice(0,o):[],a=r.length-s.length,l=[];i>0&&l.push(`${i} file${i>1?"s":""} skipped \u2014 unsupported type`),a>0&&l.push(`${a} file${a>1?"s":""} skipped \u2014 max ${t} allowed`),l.length&&this.flashNotice(l.join(" \xB7 "));for(let d of s){if(d.size===0){let f={uploadId:G(),file:d,originalFile:d,edited:!1,state:"failed",progress:0,error:"File is empty (0 bytes) \u2014 if it lives in iCloud/Drive, open it once to download it, then re-add"};this.items.push(f),this.renderItem(f);continue}if(this.opts.maxFileSize&&d.size>this.opts.maxFileSize){let f={uploadId:G(),file:d,originalFile:d,edited:!1,state:"failed",progress:0,error:`File exceeds ${j(this.opts.maxFileSize)} limit`};this.items.push(f),this.renderItem(f);continue}let c={uploadId:G(),file:d,originalFile:d,edited:!1,state:"queued",progress:0};this.items.push(c),this.renderItem(c),this.shouldCheckDimensions(d)&&(c.validating=!0,this.validateDimensions(c))}this.refreshConfirm(),this.maybeAutoUpload()}renderItem(e){if(!this.$list)return;let t=m("div","us-file");t.dataset.state=e.state,t.dataset.uploadId=e.uploadId;let i=Math.min(this.items.length-1,8);t.style.animationDelay=`${i*35}ms`;let r=m("div","us-file-thumb");if(e.file.type.startsWith("image/")&&typeof URL!="undefined"&&URL.createObjectURL)try{let u=URL.createObjectURL(e.file);e.objectUrl=u,r.style.backgroundImage=`url("${u}")`,r.dataset.image="true"}catch(u){r.innerHTML=Y(e.file.type)}else r.innerHTML=Y(e.file.type);t.appendChild(r);let o=m("div","us-file-main"),s=m("div","us-file-row1");s.appendChild(m("div","us-file-name",e.file.name));let a=m("div","us-file-meta",j(e.file.size));s.appendChild(a),o.appendChild(s);let l=m("div","us-file-progress"),p=m("div","us-file-progress-bar");l.appendChild(p),o.appendChild(l);let d=m("div","us-file-error");e.error&&(d.textContent=e.error),o.appendChild(d),t.appendChild(o);let c=e.file.type.startsWith("image/"),f=this.opts.imageEditing!==!1;if(c&&f&&e.state==="queued"){let u=document.createElement("button");u.type="button",u.className="us-file-action",u.setAttribute("aria-label","Edit image"),u.title="Edit image",u.innerHTML=b.pencil,u.dataset.edited=e.edited?"true":"false",u.onclick=()=>this.openEditor(e),t.appendChild(u),e.$edit=u}let h=m("div","us-file-status");h.setAttribute("aria-label",this.statusLabel(e)),h.innerHTML=this.statusIcon(e.state),t.appendChild(h),e.$row=t,e.$bar=p,e.$status=h,e.$meta=a,e.$error=d,e.$thumb=r,this.$list.appendChild(t),this.updateSummary(),this.updateItemBadge(e)}replaceItemFile(e,t,i){if(e.file=t,e.edited=i,e.objectUrl&&URL.revokeObjectURL(e.objectUrl),e.objectUrl=void 0,e.$thumb)if(e.$thumb.style.backgroundImage="",e.$thumb.removeAttribute("data-image"),t.type.startsWith("image/")&&typeof URL!="undefined"&&URL.createObjectURL)try{let r=URL.createObjectURL(t);e.objectUrl=r,e.$thumb.style.backgroundImage=`url("${r}")`,e.$thumb.dataset.image="true",e.$thumb.innerHTML=""}catch(r){e.$thumb.innerHTML=Y(t.type)}else e.$thumb.innerHTML=Y(t.type);if(e.$meta&&(e.$meta.textContent=j(t.size)),e.$row){let r=e.$row.querySelector(".us-file-name");r&&(r.textContent=t.name)}e.$edit&&(e.$edit.dataset.edited=i?"true":"false")}openEditor(e){if(!this.$panel||this.editor||e.state!=="queued")return;let t=!1;this.editor=new X({host:this.$panel,file:e.file,originalFile:e.originalFile,title:e.originalFile.name,lockedAspect:this.opts.cropAspectRatio,onCropApplied:()=>{t=!0},onAspectReset:()=>{t=!1},onApply:i=>{let r=i!==e.originalFile;this.replaceItemFile(e,i,r),t&&(e.ratioCropped=!0),this.editor=null,this.shouldCheckDimensions(e.file)&&(e.validating=!0,this.validateDimensions(e)),this.updateItemBadge(e),this.refreshConfirm()},onCancel:()=>{this.editor=null}}),this.editor.open()}statusIcon(e){switch(e){case"uploading":return b.spinner;case"done":return b.check;case"failed":return b.alert;case"cancelled":return b.alert;default:return b.clock}}statusLabel(e){switch(e.state){case"queued":return"Waiting to upload";case"uploading":return`Uploading ${Math.round(e.progress)} percent`;case"done":return"Upload complete";case"failed":return e.error?`Failed: ${e.error}`:"Upload failed";case"cancelled":return"Cancelled"}}setItemState(e,t,i){if(e.state=t,i!==void 0&&(e.progress=i),e.$row&&(e.$row.dataset.state=t),e.$bar&&(e.$bar.style.width=`${e.progress}%`),e.$status&&(e.$status.innerHTML=this.statusIcon(t),e.$status.setAttribute("aria-label",this.statusLabel(e))),e.$meta){let r=j(e.file.size);t==="uploading"?e.$meta.textContent=`${r} \xB7 ${Math.round(e.progress)}%`:e.$meta.textContent=r}e.$error&&(e.$error.textContent=t==="failed"?e.error||"Upload failed":""),this.updateSummary()}updateSummary(){if(!this.$summary)return;let e=this.items.length;if(e===0){this.$summary.textContent="";return}let t=this.items.filter(o=>o.state==="done").length,i=this.items.filter(o=>o.state==="failed").length,r=this.items.filter(o=>o.state==="uploading"||o.state==="queued").length;if(!this.uploadStarted&&r>0){let o=this.items.filter(s=>s.state==="queued").length;this.$summary.textContent=`${o} file${o===1?"":"s"} ready`}else r>0?this.$summary.textContent=`Uploading ${t+1} of ${e}`:i>0?this.$summary.textContent=`${t} of ${e} uploaded \xB7 ${i} failed`:t===e?this.$summary.textContent=`${e} file${e===1?"":"s"} uploaded`:this.$summary.textContent=`${e} file${e===1?"":"s"} ready`}needsCrop(e){return this.opts.forceCrop===!0&&!!this.opts.cropAspectRatio&&e.state==="queued"&&e.file.type.startsWith("image/")&&e.file.type!=="image/svg+xml"&&!e.ratioCropped}hasUncroppedImages(){return this.items.some(e=>this.needsCrop(e))}anyValidating(){return this.items.some(e=>e.validating===!0)}shouldCheckDimensions(e){return!!(this.opts.minImageWidth||this.opts.minImageHeight)&&e.type.startsWith("image/")&&e.type!=="image/svg+xml"}updateItemBadge(e){e.$row&&(this.needsCrop(e)?(e.$row.dataset.cropRequired="true",e.$meta&&(e.$meta.textContent="Crop to ratio required")):(delete e.$row.dataset.cropRequired,e.state==="queued"&&e.$meta&&!e.validating&&(e.$meta.textContent=j(e.file.size))))}async validateDimensions(e){var a,l;let t=++this.validateSeqCounter;e.validateSeq=t;let i=(a=this.opts.minImageWidth)!=null?a:0,r=(l=this.opts.minImageHeight)!=null?l:0,o=e.file,s=null;try{s=await Ge(o)}catch(p){s=null}if(e.validateSeq===t){if(e.validating=!1,e.state==="queued")if(s&&s.w>0&&s.h>0&&(s.w<i||s.h<r)){let p=`${i||"?"}\xD7${r||"?"}`;e.error=`Image too small \u2014 needs at least ${p}px (got ${s.w}\xD7${s.h})`,this.setItemState(e,"failed")}else this.updateItemBadge(e);this.refreshConfirm(),this.maybeAutoUpload()}}maybeAutoUpload(){this.opts.autoUpload!==!0||this.uploadStarted||this.anyValidating()||this.hasUncroppedImages()||this.items.some(e=>e.state==="queued")&&requestAnimationFrame(()=>{this.uploadStarted||this.startUpload()})}refreshConfirm(){if(!this.$confirm)return;let e=this.items.filter(t=>t.state==="queued").length;this.$confirm.disabled=e===0||this.uploadStarted||this.hasUncroppedImages()||this.anyValidating()}flashNotice(e){this.$summary&&(this.$summary.textContent=e,this.$summary.dataset.tone="warn",this.noticeTimer&&clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{this.$summary&&(this.$summary.textContent="",delete this.$summary.dataset.tone),this.noticeTimer=null},4e3))}async startUpload(){if(this.uploadStarted)return;if(this.anyValidating()){this.flashNotice("Checking image dimensions\u2026");return}if(this.hasUncroppedImages()){this.items.forEach(r=>this.updateItemBadge(r)),this.flashNotice("Crop required \u2014 crop every image to the set ratio before uploading.");return}let e=this.items.filter(r=>r.state==="queued");if(e.length===0)return;this.uploadStarted=!0,this.$confirm&&(this.$confirm.disabled=!0,this.$confirm.textContent="Uploading\u2026"),this.$cancel&&(this.$cancel.textContent="Stop"),this.$closeBtn&&(this.$closeBtn.disabled=!0),this.$input&&(this.$input.disabled=!0);let t=new Map,i=e.map(r=>r.file);try{await this.client.uploadMany(i,U(C({},this.opts),{signal:this.abortCtrl.signal,onUploadStarted:r=>{var o,s;r.forEach((a,l)=>{let p=e[l];p&&(p.uploadId=a.uploadId,p.$row&&(p.$row.dataset.uploadId=a.uploadId),t.set(a.uploadId,p))}),(s=(o=this.opts).onUploadStarted)==null||s.call(o,r)},onFileUploadStarted:r=>{var s,a;let o=t.get(r.uploadId);o&&this.setItemState(o,"uploading",0),(a=(s=this.opts).onFileUploadStarted)==null||a.call(s,r)},onFileUploadProgress:(r,o)=>{var a,l;let s=t.get(r.uploadId);s&&this.setItemState(s,"uploading",o.totalPercent),(l=(a=this.opts).onFileUploadProgress)==null||l.call(a,r,o)},onFileUploadFinished:r=>{var s,a;let o=t.get(r.uploadId);o&&(o.uploaded=r,this.setItemState(o,"done",100)),(a=(s=this.opts).onFileUploadFinished)==null||a.call(s,r)},onFileUploadFailed:(r,o)=>{var a,l;let s=t.get(r.uploadId);s&&(s.error=o.message,this.setItemState(s,"failed")),(l=(a=this.opts).onFileUploadFailed)==null||l.call(a,r,o)},onUploadDone:r=>{var o,s;(s=(o=this.opts).onUploadDone)==null||s.call(o,r),this.resolveResult(r),this.unmount()},onError:r=>{var o,s;(s=(o=this.opts).onError)==null||s.call(o,r),this.resolveResult(),this.unmount()}}))}catch(r){this.resolved||(this.resolveResult(),this.unmount())}}resolveResult(e){if(this.resolved)return;this.resolved=!0;let t=e!=null?e:{filesUploaded:this.items.filter(i=>i.uploaded).map(i=>i.uploaded),filesFailed:this.items.filter(i=>i.state==="failed").map(i=>({file:{uploadId:i.uploadId,filename:i.file.name,mimetype:i.file.type||"application/octet-stream",size:i.file.size,source:"local"},error:{code:"VALIDATION",message:i.error||"failed",retryable:!1}}))};this.resolvePromise(t)}};xe={"application/pdf":"PDF","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/vnd.ms-powerpoint":"PPT","application/vnd.openxmlformats-officedocument.presentationml.presentation":"PPTX","application/zip":"ZIP","application/json":"JSON","application/rtf":"RTF","text/plain":"TXT","text/csv":"CSV","text/html":"HTML","text/markdown":"MD","image/jpeg":"JPG","image/png":"PNG","image/gif":"GIF","image/webp":"WEBP","image/svg+xml":"SVG","image/heic":"HEIC","video/mp4":"MP4","audio/mpeg":"MP3"},Xe={image:"Images",video:"Video",audio:"Audio",text:"Text",font:"Fonts"}});var we={};se(we,{Picker:()=>H,openPicker:()=>J});var ee=q(()=>{"use strict";ke()});var ot={};se(ot,{Picker:()=>H,UnionStackClient:()=>D,init:()=>rt,openPicker:()=>J});function v(n,e,t={}){var i;return{code:n,message:e,status:t.status,retryable:(i=t.retryable)!=null?i:Se(n,t.status),cause:t.cause}}function Se(n,e){return!!(n==="NETWORK"||n==="PART_FAILED"||n==="SERVER"&&e&&e>=500)}function ae(n,e){let t=e==null?void 0:e.error,i=(t==null?void 0:t.message)||`Request failed with status ${n}`,r=((t==null?void 0:t.code)||"").toUpperCase();if(n===401)return v("AUTH",i,{status:n,retryable:!1});if(n===403)return v("AUTH",i,{status:n,retryable:!1});if(n===413)return v("VALIDATION",i,{status:n,retryable:!1});if(n===415)return v("VALIDATION",i,{status:n,retryable:!1});if(n===422)return v("VALIDATION",i,{status:n,retryable:!1});if(n===426)return v("CONFIG",i,{status:n,retryable:!1});if(n===429){let o=r==="QUOTA_EXCEEDED";return v(o?"QUOTA":"NETWORK",i,{status:n,retryable:!o})}return n>=500?v("SERVER",i,{status:n,retryable:!0}):v("SERVER",i,{status:n,retryable:!1})}var le="0.3.15",de=`js/${le}`,at=`node/${le}`;var Le=3,Fe=3,pe=[400,1200,3600],K=class{constructor(e){this.cfg=e}describe(e,t={}){let i=typeof File!="undefined"&&e instanceof File,r=t.filename||(i?e.name:"untitled"),o=t.mimeType||e.type||"application/octet-stream";return{uploadId:Ae(),filename:r,mimetype:o,size:e.size,source:"local"}}async upload(e,t={}){var r,o,s,a;let i=this.describe(e,{filename:t.filename,mimeType:t.mimeType});if((r=t.onFileUploadStarted)==null||r.call(t,i),e.size===0){let l=v("VALIDATION","File is empty (0 bytes). If it is stored in iCloud, OneDrive, or Google Drive, open it once to download it locally, then try again.",{retryable:!1});throw(o=t.onFileUploadFailed)==null||o.call(t,i,l),l}try{let l=await this.initUpload(i,t),p=await this.uploadAllParts(e,l,i,t),d=await this.completeUpload(l.sessionId,p,t),c=U(C({},i),{handle:d.handle,fileId:d.fileId,url:d.url,size:d.size,mimetype:d.mimetype,filename:d.filename,key:d.key,container:d.container,status:"Stored",etag:d.etag,metadata:d.metadata});return(s=t.onFileUploadFinished)==null||s.call(t,c),c}catch(l){let p=ce(l);throw(a=t.onFileUploadFailed)==null||a.call(t,i,p),l!=null&&l.sessionId&&this.abortSilently(l.sessionId).catch(()=>{}),p}}async abort(e){await this.api("POST","/sdk/v1/uploads/abort",{sessionId:e})}async fetchPickerConfig(){return this.api("GET","/sdk/v1/picker-config")}async initUpload(e,t){return this.api("POST","/sdk/v1/uploads/init",{filename:e.filename,mimeType:e.mimetype,size:e.size,metadata:t.metadata},t.signal)}async uploadAllParts(e,t,i,r){var M,S;let o=t.totalParts,s=t.chunkSize,a=Math.max(1,(M=r.concurrency)!=null?M:Le),l=(S=r.maxRetriesPerPart)!=null?S:Fe,p=new Map(t.partUrls.map(k=>[k.partNumber,k.url])),d=new Array(o),c=new Array(o).fill(0),f=1,h=e.size,u=()=>{var g;let k=c.reduce((T,y)=>T+y,0),E=h>0?Math.min(100,Math.round(k/h*100)):100,I={totalBytes:h,loaded:k,totalPercent:E};(g=r.onFileUploadProgress)==null||g.call(r,i,I)},R=async()=>{var k,E,I,g,T;for(;;){if((k=r.signal)!=null&&k.aborted)throw v("ABORTED","Upload aborted by caller.",{retryable:!1});let y=f++;if(y>o)return;let O=(y-1)*s,_=Math.min(O+s,e.size),A=e.slice(O,_),B=0,z;for(;B<=l;){if((E=r.signal)!=null&&E.aborted)throw v("ABORTED","Upload aborted by caller.",{retryable:!1});try{let $=p.get(y);$||($=(await this.api("POST","/sdk/v1/uploads/sign-part",{sessionId:t.sessionId,partNumber:y},r.signal)).url,p.set(y,$));let P=(T=await((g=(I=this.cfg).fetch)==null?void 0:g.call(I,$,{method:"PUT",body:A,signal:r.signal})))!=null?T:await fetch($,{method:"PUT",body:A,signal:r.signal});if(!P.ok)throw(P.status===403||P.status===401)&&p.delete(y),v("PART_FAILED",`Part ${y} PUT failed (HTTP ${P.status})`,{status:P.status});let N=P.headers.get("etag");if(!N)throw v("PART_FAILED",`Part ${y}: R2 did not return an ETag.`);d[y-1]={partNumber:y,etag:N,size:A.size},c[y-1]=A.size,u();break}catch($){if(z=$,B++,B>l)break;await Be(pe[Math.min(B-1,pe.length-1)])}}if(!d[y-1])throw ze(ce(z!=null?z:v("PART_FAILED",`Part ${y} failed after ${l} retries.`)),t.sessionId)}},F=Array.from({length:Math.min(a,o)},R);return await Promise.all(F),d}async completeUpload(e,t,i){return this.api("POST","/sdk/v1/uploads/complete",{sessionId:e,parts:t.map(r=>({partNumber:r.partNumber,etag:r.etag}))},i.signal)}async abortSilently(e){try{await this.abort(e)}catch(t){}}async api(e,t,i,r){var p,d;let o=(p=this.cfg.fetch)!=null?p:fetch,s=`${this.cfg.apiBase}${t}`,a;try{a=await o(s,{method:e,headers:{Authorization:`Bearer ${this.cfg.apiKey}`,"Content-Type":"application/json","X-UnionStack-SDK":(d=this.cfg.sdkHeader)!=null?d:de},body:i===void 0?void 0:JSON.stringify(i),signal:r})}catch(c){throw(c==null?void 0:c.name)==="AbortError"?v("ABORTED","Request aborted.",{retryable:!1,cause:c}):v("NETWORK","Network request failed.",{retryable:!0,cause:c})}let l=null;try{l=await a.json()}catch(c){}if(!a.ok)throw ae(a.status,l);return l}};function Ae(){return typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36)}function Be(n){return new Promise(e=>setTimeout(e,n))}function ce(n){if(n&&typeof n=="object"&&"code"in n&&"message"in n&&"retryable"in n)return n;let e=(n==null?void 0:n.message)||"Upload failed.";return v("NETWORK",e,{cause:n})}function ze(n,e){return n&&typeof n=="object"&&(n.sessionId=e),n}var tt="https://api.unionstack.link/v1",Ce="unionstack-preloader-styles";function it(){if(typeof document=="undefined")return()=>{};if(!document.getElementById(Ce)){let i=document.createElement("style");i.id=Ce,i.textContent="@keyframes us-preload-spin{to{transform:rotate(360deg)}}@keyframes us-preload-fade{from{opacity:0}to{opacity:1}}",document.head.appendChild(i)}let n=document.createElement("div");n.setAttribute("role","status"),n.setAttribute("aria-label","Loading file picker"),n.style.cssText="position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;background:rgba(2,6,23,0.4);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);animation:us-preload-fade 140ms ease-out;";let e=document.createElement("div");e.style.cssText="width:36px;height:36px;border-radius:50%;border:3px solid rgba(220,225,251,0.25);border-top-color:#c0c1ff;animation:us-preload-spin 0.8s linear infinite;",n.appendChild(e),document.body.appendChild(n);let t=!1;return()=>{t||(t=!0,n.remove())}}var D=class{constructor(e){e.apiKey||console.error("[UnionStack] apiKey is not set. Uploads and the picker are disabled until a valid apiKey is provided."),this.resolvedCfg=U(C({},e),{apiBase:tt}),this.uploader=new K(this.resolvedCfg),this.pickerConfigPromise=!e.apiKey||this.resolvedCfg.skipConfigPrefetch?Promise.resolve(null):this.uploader.fetchPickerConfig().then(t=>(t!=null&&t.sdkWarning&&console.warn(`[UnionStack] ${t.sdkWarning}`),t)).catch(()=>null)}missingKeyError(){return this.resolvedCfg.apiKey?null:v("CONFIG","apiKey is required.",{retryable:!1})}upload(e,t={}){let i=this.missingKeyError();return i?Promise.reject(i):this.uploader.upload(e,t)}async uploadMany(e,t={}){var l,p,d,c;let i=this.missingKeyError();if(i)throw(l=t.onError)==null||l.call(t,i),i;if(!Array.isArray(e)||e.length===0){let f=v("VALIDATION","uploadMany requires a non-empty array of files.",{retryable:!1});throw(p=t.onError)==null||p.call(t,f),f}let r=e.map(f=>this.uploader.describe(f,{filename:t.filename,mimeType:t.mimeType}));(d=t.onUploadStarted)==null||d.call(t,r);let o=[],s=[];await Promise.all(e.map(async(f,h)=>{try{let u=await this.uploader.upload(f,t);u.uploadId=r[h].uploadId,o.push(u)}catch(u){s.push({file:r[h],error:u})}}));let a={filesUploaded:o,filesFailed:s};return(c=t.onUploadDone)==null||c.call(t,a),a}picker(e={}){let t=null,i=!1,r,o,s=new Promise((a,l)=>{r=a,o=l});return{open:async()=>{if(i)return s;let a=this.missingKeyError();if(a)throw o(a),a;i=!0;let l=it();try{t=(await Promise.resolve().then(()=>(ee(),we))).openPicker(this,U(C({},e),{onOpen:()=>{var c;l(),(c=e.onOpen)==null||c.call(e)}}));let d=await t.open();return l(),r(d),d}catch(p){l();let d=p!=null&&p.code?p:v("CONFIG","Failed to load picker.",{retryable:!1,cause:p});throw o(d),d}},close:()=>{t==null||t.close()},cancel:()=>{t==null||t.cancel()}}}get config(){return this.resolvedCfg}};var Q={init(n){return new D(n)}};ee();var rt=Q.init.bind(Q);(function(){if(typeof document=="undefined")return;let e=document.currentScript;if(!e)return;let t=e.getAttribute("data-unionstack-key");if(t)try{let i=Q.init({apiKey:t});queueMicrotask(()=>{window.UnionStack&&(window.UnionStack.client=i)})}catch(i){console.error("[UnionStack] auto-init failed:",i)}})();return Me(ot);})();
544
544
  //# sourceMappingURL=loader.v1.global.js.map