@masters-union/union-stack 0.1.9 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var UnionStack=(()=>{var N=Object.defineProperty,be=Object.defineProperties,xe=Object.getOwnPropertyDescriptor,ye=Object.getOwnPropertyDescriptors,ke=Object.getOwnPropertyNames,Z=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,we=Object.prototype.propertyIsEnumerable;var ee=(o,e,t)=>e in o?N(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,y=(o,e)=>{for(var t in e||(e={}))te.call(e,t)&&ee(o,t,e[t]);if(Z)for(var t of Z(e))we.call(e,t)&&ee(o,t,e[t]);return o},S=(o,e)=>be(o,ye(e));var W=(o,e)=>()=>(o&&(e=o(o=0)),e);var re=(o,e)=>{for(var t in e)N(o,t,{get:e[t],enumerable:!0})},Ce=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ke(e))!te.call(o,r)&&r!==t&&N(o,r,{get:()=>e[r],enumerable:!(i=xe(e,r))||i.enumerable});return o};var Ee=o=>Ce(N({},"__esModule",{value:!0}),o);function Le(){if(document.getElementById(ae))return;let o=(t,i)=>{let r=document.createElement("link");r.rel="preconnect",r.href=t,i&&(r.crossOrigin="anonymous"),document.head.appendChild(r)};o("https://fonts.googleapis.com"),o("https://fonts.gstatic.com",!0);let e=document.createElement("link");e.id=ae,e.rel="stylesheet",e.href=Ie,document.head.appendChild(e)}function le(){if(typeof document=="undefined"||(Le(),document.getElementById(se)))return;let o=document.createElement("style");o.id=se,o.textContent=Be,document.head.appendChild(o)}function de(o){var i,r,n,a,s;let t=((o==null?void 0:o.mode)||"light")==="dark"?Fe:Se;return{"--us-primary":(i=o==null?void 0:o.primary)!=null?i:t.primary,"--us-on-primary":t.onPrimary,"--us-bg":(r=o==null?void 0:o.background)!=null?r:t.background,"--us-fg":(n=o==null?void 0:o.foreground)!=null?n:t.foreground,"--us-muted":t.muted,"--us-subtle":t.subtle,"--us-border":(a=o==null?void 0:o.border)!=null?a:t.border,"--us-border-strong":t.borderStrong,"--us-elevated":t.elevated,"--us-overlay":t.overlay,"--us-raised":t.raised,"--us-accent":t.accent,"--us-success":t.success,"--us-danger":t.danger,"--us-radius":(s=o==null?void 0:o.radius)!=null?s:"12px"}}var se,ae,Ie,Se,Fe,Be,pe=W(()=>{"use strict";se="unionstack-picker-styles",ae="unionstack-picker-fonts",Ie="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap";Se={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"},Fe={primary:"#c0c1ff",onPrimary:"#1000a9",background:"#0c1324",foreground:"#dce1fb",muted:"#908fa0",subtle:"#191f31",border:"#2e3447",borderStrong:"#464554",elevated:"#151b2d",overlay:"#23293c",raised:"#2e3447",accent:"#ffb783",success:"#7ad08e",danger:"#ffb4ab"},Be=`
1
+ "use strict";var UnionStack=(()=>{var N=Object.defineProperty,xe=Object.defineProperties,ye=Object.getOwnPropertyDescriptor,ke=Object.getOwnPropertyDescriptors,we=Object.getOwnPropertyNames,Z=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,Ce=Object.prototype.propertyIsEnumerable;var ee=(o,e,t)=>e in o?N(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,y=(o,e)=>{for(var t in e||(e={}))te.call(e,t)&&ee(o,t,e[t]);if(Z)for(var t of Z(e))Ce.call(e,t)&&ee(o,t,e[t]);return o},L=(o,e)=>xe(o,ke(e));var _=(o,e)=>()=>(o&&(e=o(o=0)),e);var re=(o,e)=>{for(var t in e)N(o,t,{get:e[t],enumerable:!0})},Ee=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of we(e))!te.call(o,r)&&r!==t&&N(o,r,{get:()=>e[r],enumerable:!(i=ye(e,r))||i.enumerable});return o};var Ue=o=>Ee(N({},"__esModule",{value:!0}),o);function Fe(){if(document.getElementById(le))return;let o=(t,i)=>{let r=document.createElement("link");r.rel="preconnect",r.href=t,i&&(r.crossOrigin="anonymous"),document.head.appendChild(r)};o("https://fonts.googleapis.com"),o("https://fonts.gstatic.com",!0);let e=document.createElement("link");e.id=le,e.rel="stylesheet",e.href=Le,document.head.appendChild(e)}function de(){if(typeof document=="undefined"||(Fe(),document.getElementById(ae)))return;let o=document.createElement("style");o.id=ae,o.textContent=Ae,document.head.appendChild(o)}function pe(o){var i,r,n,a,s;let t=((o==null?void 0:o.mode)||"light")==="dark"?ze:Be;return{"--us-primary":(i=o==null?void 0:o.primary)!=null?i:t.primary,"--us-on-primary":t.onPrimary,"--us-bg":(r=o==null?void 0:o.background)!=null?r:t.background,"--us-fg":(n=o==null?void 0:o.foreground)!=null?n:t.foreground,"--us-muted":t.muted,"--us-subtle":t.subtle,"--us-border":(a=o==null?void 0:o.border)!=null?a:t.border,"--us-border-strong":t.borderStrong,"--us-elevated":t.elevated,"--us-overlay":t.overlay,"--us-raised":t.raised,"--us-accent":t.accent,"--us-success":t.success,"--us-danger":t.danger,"--us-radius":(s=o==null?void 0:o.radius)!=null?s:"12px"}}var ae,le,Le,Be,ze,Ae,ce=_(()=>{"use strict";ae="unionstack-picker-styles",le="unionstack-picker-fonts",Le="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap";Be={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"},ze={primary:"#c0c1ff",onPrimary:"#1000a9",background:"#0c1324",foreground:"#dce1fb",muted:"#908fa0",subtle:"#191f31",border:"#2e3447",borderStrong:"#464554",elevated:"#151b2d",overlay:"#23293c",raised:"#2e3447",accent:"#ffb783",success:"#7ad08e",danger:"#ffb4ab"},Ae=`
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;
@@ -503,5 +503,5 @@
503
503
 
504
504
  /* \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 */
505
505
  .us-file-list:empty { display: none; }
506
- `});function w(o,e,t){let i=document.createElement(o);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function _(o,e){let t=document.createElement("button");return t.type="button",t.className="us-tool",t.innerHTML=`${e} <span>${ze(o)}</span>`,t}function ze(o){return o.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function k(o,e,t){return Math.max(e,Math.min(t,o))}function ce(o){return new Promise((e,t)=>{let i=URL.createObjectURL(o),r=new Image;r.onload=()=>{URL.revokeObjectURL(i),e(r)},r.onerror=()=>{URL.revokeObjectURL(i),t(new Error("decode failed"))},r.src=i})}function ue(o){return/^image\/(png|webp|gif)$/.test(o)}var E,K,he=W(()=>{"use strict";E={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>'},K=class{constructor(e){this.opts=e;this.cropBox=null;this.displayScale=1;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=e.clientX-this.dragStart.px,i=e.clientY-this.dragStart.py,r=this.dragStart.rect,n=this.displayCanvas.width,a=this.displayCanvas.height,s=24,{x:l,y:d,w:p,h:g}=r;switch(this.dragKind){case"move":l=k(r.x+t,0,n-r.w),d=k(r.y+i,0,a-r.h);break;case"nw":{let h=k(r.x+t,0,r.x+r.w-s),c=k(r.y+i,0,r.y+r.h-s);p=r.w+(r.x-h),g=r.h+(r.y-c),l=h,d=c;break}case"ne":{let h=k(r.w+t,s,n-r.x),c=k(r.y+i,0,r.y+r.h-s);g=r.h+(r.y-c),p=h,d=c;break}case"sw":{let h=k(r.x+t,0,r.x+r.w-s),c=k(r.h+i,s,a-r.y);p=r.w+(r.x-h),g=c,l=h;break}case"se":p=k(r.w+t,s,n-r.x),g=k(r.h+i,s,a-r.y);break}this.cropRect={x:l,y:d,w:p,h:g},this.updateCropBox()};this.onPointerUp=()=>{this.dragKind=null,this.dragStart=null,document.removeEventListener("pointermove",this.onPointerMove),document.removeEventListener("pointerup",this.onPointerUp)}}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=E.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);let i=w("div","us-editor-toolbar");this.cropTool=_("Crop",E.crop),this.cropTool.onclick=()=>this.toggleCropMode(),this.circleTool=_("Circle",E.circle),this.circleTool.onclick=()=>this.applyCircle(),this.rotateTool=_("Rotate 90\xB0",E.rotate),this.rotateTool.onclick=()=>this.applyRotate(),this.revertTool=_("Revert",E.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"),n=document.createElement("button");n.type="button",n.className="us-btn",n.textContent="Cancel",n.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=`${E.check} <span>Apply</span>`,this.applyBtn.onclick=()=>this.applyAndClose(),r.appendChild(n),r.appendChild(this.applyBtn),this.root.appendChild(r),this.opts.host.appendChild(this.root)}async loadOriginalIntoWorking(){let e=await ce(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=ue(this.opts.file.type),this.markEdited(!1)}async loadTrueOriginalIntoWorking(){var n;let e=(n=this.opts.originalFile)!=null?n:this.opts.file,t=await ce(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=ue(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)),n=Math.max(1,Math.round(t*i));this.displayCanvas.width=r,this.displayCanvas.height=n,this.displayScale=i;let a=this.displayCanvas.getContext("2d");a&&(a.clearRect(0,0,r,n),a.drawImage(this.working,0,0,r,n),this.updateCropBox())}toggleCropMode(){this.mode==="crop"?this.applyCrop():this.enterCropMode()}enterCropMode(){this.mode="crop",this.cropTool.dataset.active="true",this.cropTool.innerHTML=`${E.check} <span>Apply crop</span>`;let e=this.displayCanvas.width,t=this.displayCanvas.height,i=Math.round(Math.min(e,t)*.1);this.cropRect={x:i,y:i,w:e-i*2,h:t-i*2},this.renderCropBox()}exitCropMode(){this.mode="none",this.cropTool.removeAttribute("data-active"),this.cropTool.innerHTML=`${E.crop} <span>Crop</span>`,this.cropRect=null,this.cropBox&&(this.cropBox.remove(),this.cropBox=null)}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()}updateCropBox(){if(!this.cropBox||!this.cropRect)return;let e=this.displayCanvas.getBoundingClientRect(),t=this.canvasWrap.getBoundingClientRect(),i=e.left-t.left+this.cropRect.x,r=e.top-t.top+this.cropRect.y;this.cropBox.style.left=`${i}px`,this.cropBox.style.top=`${r}px`,this.cropBox.style.width=`${this.cropRect.w}px`,this.cropBox.style.height=`${this.cropRect.h}px`}beginDrag(e,t){this.cropRect&&(e.preventDefault(),this.dragKind=t,this.dragStart={px:e.clientX,py:e.clientY,rect:y({},this.cropRect)},document.addEventListener("pointermove",this.onPointerMove),document.addEventListener("pointerup",this.onPointerUp))}applyCrop(){if(!this.cropRect){this.exitCropMode();return}let e=this.displayScale,t=Math.round(this.cropRect.x/e),i=Math.round(this.cropRect.y/e),r=Math.round(this.cropRect.w/e),n=Math.round(this.cropRect.h/e),a=document.createElement("canvas");a.width=r,a.height=n;let s=a.getContext("2d");s&&(s.drawImage(this.working,t,i,r,n,0,0,r,n),this.working=a,this.exitCropMode(),this.markEdited(!0),this.draw())}applyRotate(){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),this.draw())}applyCircle(){let{width:e,height:t}=this.working,i=Math.min(e,t),r=Math.round((e-i)/2),n=Math.round((t-i)/2),a=document.createElement("canvas");a.width=i,a.height=i;let s=a.getContext("2d");s&&(s.save(),s.beginPath(),s.arc(i/2,i/2,i/2,0,Math.PI*2),s.closePath(),s.clip(),s.drawImage(this.working,r,n,i,i,0,0,i,i),s.restore(),this.working=a,this.hasAlpha=!0,this.exitCropMode(),this.markEdited(!0),this.draw())}async revert(){await this.loadTrueOriginalIntoWorking(),this.exitCropMode(),this.draw()}markEdited(e){this.revertTool.disabled=!e}async applyAndClose(){this.applyBtn.disabled=!0;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(n=>{if(!n)return t(new Error("toBlob returned null"));let a=this.opts.file.name.replace(/\.[^.]+$/,""),s=i==="image/png"?"png":"jpg";e(new File([n],`${a}-edited.${s}`,{type:i}))},i,r)})}}});function Ae(o,e){var n,a,s,l,d,p,g,h,c,U,$,P,b,T,x,R,M,C,I,v;let t=y({},e),i=e.branding||{};t.branding={logoUrl:(a=(n=i.logoUrl)!=null?n:o.branding.logoUrl)!=null?a:void 0,title:(l=(s=i.title)!=null?s:o.branding.title)!=null?l:void 0,hideFooter:(d=i.hideFooter)!=null?d:o.branding.hideFooter};let r=e.theme||{};if(t.theme={primary:(g=(p=r.primary)!=null?p:o.theme.primary)!=null?g:void 0,background:(c=(h=r.background)!=null?h:o.theme.background)!=null?c:void 0,foreground:($=(U=r.foreground)!=null?U:o.theme.foreground)!=null?$:void 0,border:(b=(P=r.border)!=null?P:o.theme.border)!=null?b:void 0,radius:(x=(T=r.radius)!=null?T:o.theme.radius)!=null?x:void 0,mode:(M=(R=r.mode)!=null?R:o.theme.mode)!=null?M:void 0},t.maxFileSize=(C=e.maxFileSize)!=null?C:o.constraints.maxFileSizeBytes,t.maxFiles=(I=e.maxFiles)!=null?I:o.constraints.maxFilesPerUpload,!e.accept&&((v=o.constraints.allowedMimeTypes)!=null&&v.length)){let A=o.constraints.allowedMimeTypes.filter(G=>G!=="*/*");A.length>0&&(t.accept=A.join(","))}return t}function V(o){return o?o.startsWith("image/")?m.image:o.startsWith("video/")?m.video:o.startsWith("audio/")?m.audio:o==="application/pdf"?m.pdf:o.startsWith("application/zip")||o.includes("compressed")||o==="application/x-tar"||o==="application/gzip"?m.archive:m.file:m.file}function u(o,e,t){let i=document.createElement(o);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function H(o){return o<1024?`${o} B`:o<1024*1024?`${(o/1024).toFixed(1)} KB`:o<1024*1024*1024?`${(o/1024/1024).toFixed(1)} MB`:`${(o/1024/1024/1024).toFixed(2)} GB`}function fe(){return typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36)}async function Oe(o){let e;try{e=await fetch(o,{mode:"cors",credentials:"omit"})}catch(n){throw new Error(`Could not reach ${De(o)} \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=Ne(o)||"download",r=t.type||We(i);return new File([t],i,{type:r})}function De(o){try{return new URL(o).host}catch(e){return"that host"}}function Ne(o){try{let t=new URL(o).pathname.split("/").filter(Boolean).pop();return t?decodeURIComponent(t):""}catch(e){return""}}function We(o){let e=o.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 Y(o,e){let t=new F(o,e);return{open:()=>t.open(),close:()=>t.close(),cancel:()=>t.cancel()}}var He,je,m,F,me=W(()=>{"use strict";pe();he();He="Upload files",je="https://unionstack.link",m={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>',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>'};F=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.resolved=!1;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=Ae(i,this.opts))}catch(i){}return le(),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()}mount(){var g,h,c,U,$,P;let e=document.createElement("div");e.className="us-picker-backdrop",Object.entries(de(this.opts.theme)).forEach(([b,T])=>{e.style.setProperty(b,T)}),e.addEventListener("click",b=>{b.target===e&&!this.uploadStarted&&this.cancel()});let t=u("div","us-picker"),i=u("div","us-picker-header"),r=u("div","us-picker-header-logo");if((g=this.opts.branding)!=null&&g.logoUrl){let b=document.createElement("img");b.src=this.opts.branding.logoUrl,b.alt="",r.appendChild(b)}else r.innerHTML=m.zap;i.appendChild(r);let n=u("div","us-picker-title",(c=(h=this.opts.branding)==null?void 0:h.title)!=null?c:He);i.appendChild(n),this.$closeBtn=document.createElement("button"),this.$closeBtn.type="button",this.$closeBtn.className="us-picker-close",this.$closeBtn.setAttribute("aria-label","Close"),this.$closeBtn.innerHTML=m.close,this.$closeBtn.onclick=()=>this.cancel(),i.appendChild(this.$closeBtn),t.appendChild(i);let a=u("div","us-picker-body"),s=this.resolvedSources();s.length>1&&a.appendChild(this.renderSourceTabs(s)),s.includes("device")&&(this.$deviceSource=this.renderDropzone(),a.appendChild(this.$deviceSource)),s.includes("url")&&(this.$urlSource=this.renderUrlSource(),a.appendChild(this.$urlSource)),this.activateSource((U=s[0])!=null?U:"device"),this.$list=u("div","us-file-list"),a.appendChild(this.$list),t.appendChild(a);let l=this.opts.autoUpload===!0,d=u("div","us-actions");this.$summary=u("div","us-actions-summary",""),d.appendChild(this.$summary);let p=u("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(),p.appendChild(this.$cancel),l||(this.$confirm=document.createElement("button"),this.$confirm.type="button",this.$confirm.className="us-btn us-btn-primary",this.$confirm.innerHTML=`${m.upload} <span>Upload</span>`,this.$confirm.disabled=!0,this.$confirm.onclick=()=>this.startUpload(),p.appendChild(this.$confirm)),d.appendChild(p),t.appendChild(d),!(($=this.opts.branding)!=null&&$.hideFooter)){let b=u("div","us-footer");b.innerHTML=`${m.zap} <span>Powered by <a href="${je}" target="_blank" rel="noopener">UnionStack</a></span>`,t.appendChild(b)}e.appendChild(t),((P=this.opts.container)!=null?P:document.body).appendChild(e),this.$backdrop=e,this.$panel=t}resolvedSources(){let e=this.opts.fromSources;return!e||e.length===0?["device","url"]:e}renderSourceTabs(e){let t=u("div","us-source-tabs");t.setAttribute("role","tablist");for(let i of e){let r=document.createElement("button");r.type="button",r.className="us-source-tab",r.setAttribute("role","tab"),r.dataset.source=i,r.innerHTML=i==="device"?`${m.device} <span>My Device</span>`:`${m.link} <span>Link</span>`,r.onclick=()=>this.activateSource(i),t.appendChild(r)}return t}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=>{r.dataset.active=r.dataset.source===e?"true":"false"})}renderUrlSource(){let e=u("div","us-url-source"),t=u("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=a=>{a.key==="Enter"&&(a.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 n=u("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=n,e.appendChild(n),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 Oe(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 n;let e=u("div","us-dropzone");e.setAttribute("role","button"),e.setAttribute("tabindex","0"),e.setAttribute("aria-label","Drop files here or click to browse");let t=u("div","us-dropzone-icon");t.innerHTML=m.fileUp,e.appendChild(t),e.appendChild(u("div","us-dropzone-title","Drop files to upload")),e.appendChild(u("div","us-dropzone-hint","or click to browse from your device"));let i=[];if(this.opts.maxFileSize&&i.push(`max ${H(this.opts.maxFileSize)}`),this.opts.accept){let a=this.opts.accept.split(",").map(s=>s.trim()).filter(s=>s&&s!=="*/*").map(s=>s.replace("/*",""));a.length>0&&a.length<=4&&i.push(a.join(" \xB7 "))}i.length>0&&e.appendChild(u("div","us-dropzone-constraints",i.join(" \xB7 ")));let r=document.createElement("input");return r.type="file",r.multiple=((n=this.opts.maxFiles)!=null?n:10)>1,this.opts.accept&&(r.accept=this.opts.accept),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())},e.addEventListener("dragover",a=>{a.preventDefault(),e.setAttribute("data-drag","over")}),e.addEventListener("dragleave",()=>e.removeAttribute("data-drag")),e.addEventListener("drop",a=>{var l;a.preventDefault(),e.removeAttribute("data-drag");let s=(l=a.dataTransfer)==null?void 0:l.files;s&&this.addFiles(Array.from(s))}),e}unmount(){var e,t,i;this.editor&&(this.editor.close(),this.editor=null),(e=this.$backdrop)!=null&&e.parentNode&&this.$backdrop.parentNode.removeChild(this.$backdrop),this.$backdrop=null,this.$panel=null;for(let r of this.items)r.objectUrl&&URL.revokeObjectURL(r.objectUrl);(i=(t=this.opts).onClose)==null||i.call(t)}addFiles(e){var s;let i=((s=this.opts.maxFiles)!=null?s:1/0)-this.items.length;if(i<=0)return;let r=e.slice(0,i);for(let l of r){if(this.opts.maxFileSize&&l.size>this.opts.maxFileSize){let p={uploadId:fe(),file:l,originalFile:l,edited:!1,state:"failed",progress:0,error:`File exceeds ${H(this.opts.maxFileSize)} limit`};this.items.push(p),this.renderItem(p);continue}let d={uploadId:fe(),file:l,originalFile:l,edited:!1,state:"queued",progress:0};this.items.push(d),this.renderItem(d)}this.refreshConfirm();let n=this.opts.autoUpload===!0,a=this.items.some(l=>l.state==="queued");n&&a&&!this.uploadStarted&&requestAnimationFrame(()=>{this.uploadStarted||this.startUpload()})}renderItem(e){if(!this.$list)return;let t=u("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=u("div","us-file-thumb");if(e.file.type.startsWith("image/")&&typeof URL!="undefined"&&URL.createObjectURL)try{let c=URL.createObjectURL(e.file);e.objectUrl=c,r.style.backgroundImage=`url("${c}")`,r.dataset.image="true"}catch(c){r.innerHTML=V(e.file.type)}else r.innerHTML=V(e.file.type);t.appendChild(r);let n=u("div","us-file-main"),a=u("div","us-file-row1");a.appendChild(u("div","us-file-name",e.file.name));let s=u("div","us-file-meta",H(e.file.size));a.appendChild(s),n.appendChild(a);let l=u("div","us-file-progress"),d=u("div","us-file-progress-bar");l.appendChild(d),n.appendChild(l),t.appendChild(n);let p=e.file.type.startsWith("image/"),g=this.opts.imageEditing!==!1;if(p&&g&&e.state==="queued"){let c=document.createElement("button");c.type="button",c.className="us-file-action",c.setAttribute("aria-label","Edit image"),c.title="Edit image",c.innerHTML=m.pencil,c.dataset.edited=e.edited?"true":"false",c.onclick=()=>this.openEditor(e),t.appendChild(c),e.$edit=c}let h=u("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=s,e.$thumb=r,this.$list.appendChild(t),this.updateSummary()}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=V(t.type)}else e.$thumb.innerHTML=V(t.type);if(e.$meta&&(e.$meta.textContent=H(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){!this.$panel||this.editor||e.state!=="queued"||(this.editor=new K({host:this.$panel,file:e.file,originalFile:e.originalFile,title:e.originalFile.name,onApply:t=>{let i=t!==e.originalFile;this.replaceItemFile(e,t,i),this.editor=null},onCancel:()=>{this.editor=null}}),this.editor.open())}statusIcon(e){switch(e){case"uploading":return m.spinner;case"done":return m.check;case"failed":return m.alert;case"cancelled":return m.alert;default:return m.spinner}}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=H(e.file.size);switch(t){case"uploading":e.$meta.textContent=`${r} \xB7 ${Math.round(e.progress)}%`;break;case"done":e.$meta.textContent=r;break;case"failed":e.$meta.textContent=e.error||"Failed";break;default:e.$meta.textContent=r}}this.updateSummary()}updateSummary(){if(!this.$summary)return;let e=this.items.length;if(e===0){this.$summary.textContent="";return}let t=this.items.filter(n=>n.state==="done").length,i=this.items.filter(n=>n.state==="failed").length,r=this.items.filter(n=>n.state==="uploading"||n.state==="queued").length;if(!this.uploadStarted&&r>0){let n=this.items.filter(a=>a.state==="queued").length;this.$summary.textContent=`${n} file${n===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`}refreshConfirm(){if(!this.$confirm)return;let e=this.items.filter(t=>t.state==="queued").length;this.$confirm.disabled=e===0||this.uploadStarted}async startUpload(){if(this.uploadStarted)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,S(y({},this.opts),{signal:this.abortCtrl.signal,onUploadStarted:r=>{var n,a;r.forEach((s,l)=>{let d=e[l];d&&(d.uploadId=s.uploadId,d.$row&&(d.$row.dataset.uploadId=s.uploadId),t.set(s.uploadId,d))}),(a=(n=this.opts).onUploadStarted)==null||a.call(n,r)},onFileUploadStarted:r=>{var a,s;let n=t.get(r.uploadId);n&&this.setItemState(n,"uploading",0),(s=(a=this.opts).onFileUploadStarted)==null||s.call(a,r)},onFileUploadProgress:(r,n)=>{var s,l;let a=t.get(r.uploadId);a&&this.setItemState(a,"uploading",n.totalPercent),(l=(s=this.opts).onFileUploadProgress)==null||l.call(s,r,n)},onFileUploadFinished:r=>{var a,s;let n=t.get(r.uploadId);n&&(n.uploaded=r,this.setItemState(n,"done",100)),(s=(a=this.opts).onFileUploadFinished)==null||s.call(a,r)},onFileUploadFailed:(r,n)=>{var s,l;let a=t.get(r.uploadId);a&&(a.error=n.message,this.setItemState(a,"failed")),(l=(s=this.opts).onFileUploadFailed)==null||l.call(s,r,n)},onUploadDone:r=>{var n,a;(a=(n=this.opts).onUploadDone)==null||a.call(n,r),this.resolveResult(r),this.unmount()},onError:r=>{var n,a;(a=(n=this.opts).onError)==null||a.call(n,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)}}});var ge={};re(ge,{Picker:()=>F,openPicker:()=>Y});var Q=W(()=>{"use strict";me()});var Ve={};re(Ve,{Picker:()=>F,UnionStackClient:()=>B,init:()=>Ke,openPicker:()=>Y});function f(o,e,t={}){var i;return{code:o,message:e,status:t.status,retryable:(i=t.retryable)!=null?i:Ue(o,t.status),cause:t.cause}}function Ue(o,e){return!!(o==="NETWORK"||o==="PART_FAILED"||o==="SERVER"&&e&&e>=500)}function ie(o,e){let t=e==null?void 0:e.error,i=(t==null?void 0:t.message)||`Request failed with status ${o}`,r=((t==null?void 0:t.code)||"").toUpperCase();if(o===401)return f("AUTH",i,{status:o,retryable:!1});if(o===403)return f("AUTH",i,{status:o,retryable:!1});if(o===413)return f("VALIDATION",i,{status:o,retryable:!1});if(o===415)return f("VALIDATION",i,{status:o,retryable:!1});if(o===429){let n=r==="QUOTA_EXCEEDED";return f(n?"QUOTA":"NETWORK",i,{status:o,retryable:!n})}return o>=500?f("SERVER",i,{status:o,retryable:!0}):f("SERVER",i,{status:o,retryable:!1})}var $e=3,Pe=3,oe=[400,1200,3600],q=class{constructor(e){this.cfg=e}describe(e,t={}){let i=typeof File!="undefined"&&e instanceof File,r=t.filename||(i?e.name:"untitled"),n=t.mimeType||e.type||"application/octet-stream";return{uploadId:Te(),filename:r,mimetype:n,size:e.size,source:"local"}}async upload(e,t={}){var r,n,a;let i=this.describe(e,{filename:t.filename,mimeType:t.mimeType});(r=t.onFileUploadStarted)==null||r.call(t,i);try{let s=await this.initUpload(i,t),l=await this.uploadAllParts(e,s,i,t),d=await this.completeUpload(s.sessionId,l,t),p=S(y({},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(n=t.onFileUploadFinished)==null||n.call(t,p),p}catch(s){let l=ne(s);throw(a=t.onFileUploadFailed)==null||a.call(t,i,l),s!=null&&s.sessionId&&this.abortSilently(s.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 b,T;let n=t.totalParts,a=t.chunkSize,s=Math.max(1,(b=r.concurrency)!=null?b:$e),l=(T=r.maxRetriesPerPart)!=null?T:Pe,d=new Map(t.partUrls.map(x=>[x.partNumber,x.url])),p=new Array(n),g=new Array(n).fill(0),h=1,c=e.size,U=()=>{var C;let x=g.reduce((I,v)=>I+v,0),R=c>0?Math.min(100,Math.round(x/c*100)):100,M={totalBytes:c,loaded:x,totalPercent:R};(C=r.onFileUploadProgress)==null||C.call(r,i,M)},$=async()=>{var x,R,M,C,I;for(;;){if((x=r.signal)!=null&&x.aborted)throw f("ABORTED","Upload aborted by caller.",{retryable:!1});let v=h++;if(v>n)return;let A=(v-1)*a,G=Math.min(A+a,e.size),j=e.slice(A,G),O=0,D;for(;O<=l;){if((R=r.signal)!=null&&R.aborted)throw f("ABORTED","Upload aborted by caller.",{retryable:!1});try{let L=d.get(v);L||(L=(await this.api("POST","/sdk/v1/uploads/sign-part",{sessionId:t.sessionId,partNumber:v},r.signal)).url,d.set(v,L));let z=(I=await((C=(M=this.cfg).fetch)==null?void 0:C.call(M,L,{method:"PUT",body:j,signal:r.signal})))!=null?I:await fetch(L,{method:"PUT",body:j,signal:r.signal});if(!z.ok)throw(z.status===403||z.status===401)&&d.delete(v),f("PART_FAILED",`Part ${v} PUT failed (HTTP ${z.status})`,{status:z.status});let J=z.headers.get("etag");if(!J)throw f("PART_FAILED",`Part ${v}: R2 did not return an ETag.`);p[v-1]={partNumber:v,etag:J,size:j.size},g[v-1]=j.size,U();break}catch(L){if(D=L,O++,O>l)break;await Re(oe[Math.min(O-1,oe.length-1)])}}if(!p[v-1])throw Me(ne(D!=null?D:f("PART_FAILED",`Part ${v} failed after ${l} retries.`)),t.sessionId)}},P=Array.from({length:Math.min(s,n)},$);return await Promise.all(P),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;let n=(d=this.cfg.fetch)!=null?d:fetch,a=`${this.cfg.apiBase}${t}`,s;try{s=await n(a,{method:e,headers:{Authorization:`Bearer ${this.cfg.apiKey}`,"Content-Type":"application/json"},body:i===void 0?void 0:JSON.stringify(i),signal:r})}catch(p){throw(p==null?void 0:p.name)==="AbortError"?f("ABORTED","Request aborted.",{retryable:!1,cause:p}):f("NETWORK","Network request failed.",{retryable:!0,cause:p})}let l=null;try{l=await s.json()}catch(p){}if(!s.ok)throw ie(s.status,l);return l}};function Te(){return typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36)}function Re(o){return new Promise(e=>setTimeout(e,o))}function ne(o){if(o&&typeof o=="object"&&"code"in o&&"message"in o&&"retryable"in o)return o;let e=(o==null?void 0:o.message)||"Upload failed.";return f("NETWORK",e,{cause:o})}function Me(o,e){return o&&typeof o=="object"&&(o.sessionId=e),o}var qe="https://api.unionstack.link/v1",ve="unionstack-preloader-styles";function _e(){if(typeof document=="undefined")return()=>{};if(!document.getElementById(ve)){let i=document.createElement("style");i.id=ve,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 o=document.createElement("div");o.setAttribute("role","status"),o.setAttribute("aria-label","Loading file picker"),o.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;",o.appendChild(e),document.body.appendChild(o);let t=!1;return()=>{t||(t=!0,o.remove())}}var B=class{constructor(e){if(!e.apiKey)throw f("CONFIG","apiKey is required.",{retryable:!1});this.resolvedCfg=S(y({},e),{apiBase:qe}),this.uploader=new q(this.resolvedCfg),this.pickerConfigPromise=this.resolvedCfg.skipConfigPrefetch?Promise.resolve(null):this.uploader.fetchPickerConfig().catch(()=>null)}upload(e,t={}){return this.uploader.upload(e,t)}async uploadMany(e,t={}){var s,l,d;if(!Array.isArray(e)||e.length===0){let p=f("VALIDATION","uploadMany requires a non-empty array of files.",{retryable:!1});throw(s=t.onError)==null||s.call(t,p),p}let i=e.map(p=>this.uploader.describe(p,{filename:t.filename,mimeType:t.mimeType}));(l=t.onUploadStarted)==null||l.call(t,i);let r=[],n=[];await Promise.all(e.map(async(p,g)=>{try{let h=await this.uploader.upload(p,t);h.uploadId=i[g].uploadId,r.push(h)}catch(h){n.push({file:i[g],error:h})}}));let a={filesUploaded:r,filesFailed:n};return(d=t.onUploadDone)==null||d.call(t,a),a}picker(e={}){let t=null,i=!1,r,n,a=new Promise((s,l)=>{r=s,n=l});return{open:async()=>{if(i)return a;i=!0;let s=_e();try{t=(await Promise.resolve().then(()=>(Q(),ge))).openPicker(this,S(y({},e),{onOpen:()=>{var p;s(),(p=e.onOpen)==null||p.call(e)}}));let d=await t.open();return s(),r(d),d}catch(l){s();let d=l!=null&&l.code?l:f("CONFIG","Failed to load picker.",{retryable:!1,cause:l});throw n(d),d}},close:()=>{t==null||t.close()},cancel:()=>{t==null||t.cancel()}}}get config(){return this.resolvedCfg}};var X={init(o){return new B(o)}};Q();var Ke=X.init.bind(X);(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=X.init({apiKey:t});queueMicrotask(()=>{window.UnionStack&&(window.UnionStack.client=i)})}catch(i){console.error("[UnionStack] auto-init failed:",i)}})();return Ee(Ve);})();
506
+ `});function w(o,e,t){let i=document.createElement(o);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function q(o,e){let t=document.createElement("button");return t.type="button",t.className="us-tool",t.innerHTML=`${e} <span>${He(o)}</span>`,t}function He(o){return o.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function k(o,e,t){return Math.max(e,Math.min(t,o))}function ue(o){return new Promise((e,t)=>{let i=URL.createObjectURL(o),r=new Image;r.onload=()=>{URL.revokeObjectURL(i),e(r)},r.onerror=()=>{URL.revokeObjectURL(i),t(new Error("decode failed"))},r.src=i})}function he(o){return/^image\/(png|webp|gif)$/.test(o)}var E,K,fe=_(()=>{"use strict";E={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>'},K=class{constructor(e){this.opts=e;this.cropBox=null;this.displayScale=1;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=e.clientX-this.dragStart.px,i=e.clientY-this.dragStart.py,r=this.dragStart.rect,n=this.displayCanvas.width,a=this.displayCanvas.height,s=24,{x:l,y:d,w:p,h:g}=r;switch(this.dragKind){case"move":l=k(r.x+t,0,n-r.w),d=k(r.y+i,0,a-r.h);break;case"nw":{let h=k(r.x+t,0,r.x+r.w-s),c=k(r.y+i,0,r.y+r.h-s);p=r.w+(r.x-h),g=r.h+(r.y-c),l=h,d=c;break}case"ne":{let h=k(r.w+t,s,n-r.x),c=k(r.y+i,0,r.y+r.h-s);g=r.h+(r.y-c),p=h,d=c;break}case"sw":{let h=k(r.x+t,0,r.x+r.w-s),c=k(r.h+i,s,a-r.y);p=r.w+(r.x-h),g=c,l=h;break}case"se":p=k(r.w+t,s,n-r.x),g=k(r.h+i,s,a-r.y);break}this.cropRect={x:l,y:d,w:p,h:g},this.updateCropBox()};this.onPointerUp=()=>{this.dragKind=null,this.dragStart=null,document.removeEventListener("pointermove",this.onPointerMove),document.removeEventListener("pointerup",this.onPointerUp)}}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=E.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);let i=w("div","us-editor-toolbar");this.cropTool=q("Crop",E.crop),this.cropTool.onclick=()=>this.toggleCropMode(),this.circleTool=q("Circle",E.circle),this.circleTool.onclick=()=>this.applyCircle(),this.rotateTool=q("Rotate 90\xB0",E.rotate),this.rotateTool.onclick=()=>this.applyRotate(),this.revertTool=q("Revert",E.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"),n=document.createElement("button");n.type="button",n.className="us-btn",n.textContent="Cancel",n.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=`${E.check} <span>Apply</span>`,this.applyBtn.onclick=()=>this.applyAndClose(),r.appendChild(n),r.appendChild(this.applyBtn),this.root.appendChild(r),this.opts.host.appendChild(this.root)}async loadOriginalIntoWorking(){let e=await ue(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=he(this.opts.file.type),this.markEdited(!1)}async loadTrueOriginalIntoWorking(){var n;let e=(n=this.opts.originalFile)!=null?n:this.opts.file,t=await ue(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=he(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)),n=Math.max(1,Math.round(t*i));this.displayCanvas.width=r,this.displayCanvas.height=n,this.displayScale=i;let a=this.displayCanvas.getContext("2d");a&&(a.clearRect(0,0,r,n),a.drawImage(this.working,0,0,r,n),this.updateCropBox())}toggleCropMode(){this.mode==="crop"?this.applyCrop():this.enterCropMode()}enterCropMode(){this.mode="crop",this.cropTool.dataset.active="true",this.cropTool.innerHTML=`${E.check} <span>Apply crop</span>`;let e=this.displayCanvas.width,t=this.displayCanvas.height,i=Math.round(Math.min(e,t)*.1);this.cropRect={x:i,y:i,w:e-i*2,h:t-i*2},this.renderCropBox()}exitCropMode(){this.mode="none",this.cropTool.removeAttribute("data-active"),this.cropTool.innerHTML=`${E.crop} <span>Crop</span>`,this.cropRect=null,this.cropBox&&(this.cropBox.remove(),this.cropBox=null)}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()}updateCropBox(){if(!this.cropBox||!this.cropRect)return;let e=this.displayCanvas.getBoundingClientRect(),t=this.canvasWrap.getBoundingClientRect(),i=e.left-t.left+this.cropRect.x,r=e.top-t.top+this.cropRect.y;this.cropBox.style.left=`${i}px`,this.cropBox.style.top=`${r}px`,this.cropBox.style.width=`${this.cropRect.w}px`,this.cropBox.style.height=`${this.cropRect.h}px`}beginDrag(e,t){this.cropRect&&(e.preventDefault(),this.dragKind=t,this.dragStart={px:e.clientX,py:e.clientY,rect:y({},this.cropRect)},document.addEventListener("pointermove",this.onPointerMove),document.addEventListener("pointerup",this.onPointerUp))}applyCrop(){if(!this.cropRect){this.exitCropMode();return}let e=this.displayScale,t=Math.round(this.cropRect.x/e),i=Math.round(this.cropRect.y/e),r=Math.round(this.cropRect.w/e),n=Math.round(this.cropRect.h/e),a=document.createElement("canvas");a.width=r,a.height=n;let s=a.getContext("2d");s&&(s.drawImage(this.working,t,i,r,n,0,0,r,n),this.working=a,this.exitCropMode(),this.markEdited(!0),this.draw())}applyRotate(){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),this.draw())}applyCircle(){let{width:e,height:t}=this.working,i=Math.min(e,t),r=Math.round((e-i)/2),n=Math.round((t-i)/2),a=document.createElement("canvas");a.width=i,a.height=i;let s=a.getContext("2d");s&&(s.save(),s.beginPath(),s.arc(i/2,i/2,i/2,0,Math.PI*2),s.closePath(),s.clip(),s.drawImage(this.working,r,n,i,i,0,0,i,i),s.restore(),this.working=a,this.hasAlpha=!0,this.exitCropMode(),this.markEdited(!0),this.draw())}async revert(){await this.loadTrueOriginalIntoWorking(),this.exitCropMode(),this.draw()}markEdited(e){this.revertTool.disabled=!e}async applyAndClose(){this.applyBtn.disabled=!0;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(n=>{if(!n)return t(new Error("toBlob returned null"));let a=this.opts.file.name.replace(/\.[^.]+$/,""),s=i==="image/png"?"png":"jpg";e(new File([n],`${a}-edited.${s}`,{type:i}))},i,r)})}}});function je(o,e){var n,a,s,l,d,p,g,h,c,U,$,P,b,T,x,R,S,C,I,v;let t=y({},e),i=e.branding||{};t.branding={logoUrl:(a=(n=i.logoUrl)!=null?n:o.branding.logoUrl)!=null?a:void 0,title:(l=(s=i.title)!=null?s:o.branding.title)!=null?l:void 0,hideFooter:(d=i.hideFooter)!=null?d:o.branding.hideFooter};let r=e.theme||{};if(t.theme={primary:(g=(p=r.primary)!=null?p:o.theme.primary)!=null?g:void 0,background:(c=(h=r.background)!=null?h:o.theme.background)!=null?c:void 0,foreground:($=(U=r.foreground)!=null?U:o.theme.foreground)!=null?$:void 0,border:(b=(P=r.border)!=null?P:o.theme.border)!=null?b:void 0,radius:(x=(T=r.radius)!=null?T:o.theme.radius)!=null?x:void 0,mode:(S=(R=r.mode)!=null?R:o.theme.mode)!=null?S:void 0},t.maxFileSize=(C=e.maxFileSize)!=null?C:o.constraints.maxFileSizeBytes,t.maxFiles=(I=e.maxFiles)!=null?I:o.constraints.maxFilesPerUpload,!e.accept&&((v=o.constraints.allowedMimeTypes)!=null&&v.length)){let A=o.constraints.allowedMimeTypes.filter(G=>G!=="*/*");A.length>0&&(t.accept=A.join(","))}return t}function V(o){return o?o.startsWith("image/")?m.image:o.startsWith("video/")?m.video:o.startsWith("audio/")?m.audio:o==="application/pdf"?m.pdf:o.startsWith("application/zip")||o.includes("compressed")||o==="application/x-tar"||o==="application/gzip"?m.archive:m.file:m.file}function u(o,e,t){let i=document.createElement(o);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function H(o){return o<1024?`${o} B`:o<1024*1024?`${(o/1024).toFixed(1)} KB`:o<1024*1024*1024?`${(o/1024/1024).toFixed(1)} MB`:`${(o/1024/1024/1024).toFixed(2)} GB`}function me(){return typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36)}async function Ne(o){let e;try{e=await fetch(o,{mode:"cors",credentials:"omit"})}catch(n){throw new Error(`Could not reach ${_e(o)} \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=We(o)||"download",r=t.type||qe(i);return new File([t],i,{type:r})}function _e(o){try{return new URL(o).host}catch(e){return"that host"}}function We(o){try{let t=new URL(o).pathname.split("/").filter(Boolean).pop();return t?decodeURIComponent(t):""}catch(e){return""}}function qe(o){let e=o.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 Y(o,e){let t=new F(o,e);return{open:()=>t.open(),close:()=>t.close(),cancel:()=>t.cancel()}}var Oe,De,m,F,ge=_(()=>{"use strict";ce();fe();Oe="Upload files",De="https://unionstack.link",m={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>',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>'};F=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.resolved=!1;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=je(i,this.opts))}catch(i){}return de(),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()}mount(){var g,h,c,U,$,P;let e=document.createElement("div");e.className="us-picker-backdrop",Object.entries(pe(this.opts.theme)).forEach(([b,T])=>{e.style.setProperty(b,T)}),e.addEventListener("click",b=>{b.target===e&&!this.uploadStarted&&this.cancel()});let t=u("div","us-picker"),i=u("div","us-picker-header"),r=u("div","us-picker-header-logo");if((g=this.opts.branding)!=null&&g.logoUrl){let b=document.createElement("img");b.src=this.opts.branding.logoUrl,b.alt="",r.appendChild(b)}else r.innerHTML=m.zap;i.appendChild(r);let n=u("div","us-picker-title",(c=(h=this.opts.branding)==null?void 0:h.title)!=null?c:Oe);i.appendChild(n),this.$closeBtn=document.createElement("button"),this.$closeBtn.type="button",this.$closeBtn.className="us-picker-close",this.$closeBtn.setAttribute("aria-label","Close"),this.$closeBtn.innerHTML=m.close,this.$closeBtn.onclick=()=>this.cancel(),i.appendChild(this.$closeBtn),t.appendChild(i);let a=u("div","us-picker-body"),s=this.resolvedSources();s.length>1&&a.appendChild(this.renderSourceTabs(s)),s.includes("device")&&(this.$deviceSource=this.renderDropzone(),a.appendChild(this.$deviceSource)),s.includes("url")&&(this.$urlSource=this.renderUrlSource(),a.appendChild(this.$urlSource)),this.activateSource((U=s[0])!=null?U:"device"),this.$list=u("div","us-file-list"),a.appendChild(this.$list),t.appendChild(a);let l=this.opts.autoUpload===!0,d=u("div","us-actions");this.$summary=u("div","us-actions-summary",""),d.appendChild(this.$summary);let p=u("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(),p.appendChild(this.$cancel),l||(this.$confirm=document.createElement("button"),this.$confirm.type="button",this.$confirm.className="us-btn us-btn-primary",this.$confirm.innerHTML=`${m.upload} <span>Upload</span>`,this.$confirm.disabled=!0,this.$confirm.onclick=()=>this.startUpload(),p.appendChild(this.$confirm)),d.appendChild(p),t.appendChild(d),!(($=this.opts.branding)!=null&&$.hideFooter)){let b=u("div","us-footer");b.innerHTML=`${m.zap} <span>Powered by <a href="${De}" target="_blank" rel="noopener">UnionStack</a></span>`,t.appendChild(b)}e.appendChild(t),((P=this.opts.container)!=null?P:document.body).appendChild(e),this.$backdrop=e,this.$panel=t}resolvedSources(){let e=this.opts.fromSources;return!e||e.length===0?["device","url"]:e}renderSourceTabs(e){let t=u("div","us-source-tabs");t.setAttribute("role","tablist");for(let i of e){let r=document.createElement("button");r.type="button",r.className="us-source-tab",r.setAttribute("role","tab"),r.dataset.source=i,r.innerHTML=i==="device"?`${m.device} <span>My Device</span>`:`${m.link} <span>Link</span>`,r.onclick=()=>this.activateSource(i),t.appendChild(r)}return t}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=>{r.dataset.active=r.dataset.source===e?"true":"false"})}renderUrlSource(){let e=u("div","us-url-source"),t=u("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=a=>{a.key==="Enter"&&(a.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 n=u("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=n,e.appendChild(n),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 Ne(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 n;let e=u("div","us-dropzone");e.setAttribute("role","button"),e.setAttribute("tabindex","0"),e.setAttribute("aria-label","Drop files here or click to browse");let t=u("div","us-dropzone-icon");t.innerHTML=m.fileUp,e.appendChild(t),e.appendChild(u("div","us-dropzone-title","Drop files to upload")),e.appendChild(u("div","us-dropzone-hint","or click to browse from your device"));let i=[];if(this.opts.maxFileSize&&i.push(`max ${H(this.opts.maxFileSize)}`),this.opts.accept){let a=this.opts.accept.split(",").map(s=>s.trim()).filter(s=>s&&s!=="*/*").map(s=>s.replace("/*",""));a.length>0&&a.length<=4&&i.push(a.join(" \xB7 "))}i.length>0&&e.appendChild(u("div","us-dropzone-constraints",i.join(" \xB7 ")));let r=document.createElement("input");return r.type="file",r.multiple=((n=this.opts.maxFiles)!=null?n:10)>1,this.opts.accept&&(r.accept=this.opts.accept),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())},e.addEventListener("dragover",a=>{a.preventDefault(),e.setAttribute("data-drag","over")}),e.addEventListener("dragleave",()=>e.removeAttribute("data-drag")),e.addEventListener("drop",a=>{var l;a.preventDefault(),e.removeAttribute("data-drag");let s=(l=a.dataTransfer)==null?void 0:l.files;s&&this.addFiles(Array.from(s))}),e}unmount(){var e,t,i;this.editor&&(this.editor.close(),this.editor=null),(e=this.$backdrop)!=null&&e.parentNode&&this.$backdrop.parentNode.removeChild(this.$backdrop),this.$backdrop=null,this.$panel=null;for(let r of this.items)r.objectUrl&&URL.revokeObjectURL(r.objectUrl);(i=(t=this.opts).onClose)==null||i.call(t)}addFiles(e){var s;let i=((s=this.opts.maxFiles)!=null?s:1/0)-this.items.length;if(i<=0)return;let r=e.slice(0,i);for(let l of r){if(this.opts.maxFileSize&&l.size>this.opts.maxFileSize){let p={uploadId:me(),file:l,originalFile:l,edited:!1,state:"failed",progress:0,error:`File exceeds ${H(this.opts.maxFileSize)} limit`};this.items.push(p),this.renderItem(p);continue}let d={uploadId:me(),file:l,originalFile:l,edited:!1,state:"queued",progress:0};this.items.push(d),this.renderItem(d)}this.refreshConfirm();let n=this.opts.autoUpload===!0,a=this.items.some(l=>l.state==="queued");n&&a&&!this.uploadStarted&&requestAnimationFrame(()=>{this.uploadStarted||this.startUpload()})}renderItem(e){if(!this.$list)return;let t=u("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=u("div","us-file-thumb");if(e.file.type.startsWith("image/")&&typeof URL!="undefined"&&URL.createObjectURL)try{let c=URL.createObjectURL(e.file);e.objectUrl=c,r.style.backgroundImage=`url("${c}")`,r.dataset.image="true"}catch(c){r.innerHTML=V(e.file.type)}else r.innerHTML=V(e.file.type);t.appendChild(r);let n=u("div","us-file-main"),a=u("div","us-file-row1");a.appendChild(u("div","us-file-name",e.file.name));let s=u("div","us-file-meta",H(e.file.size));a.appendChild(s),n.appendChild(a);let l=u("div","us-file-progress"),d=u("div","us-file-progress-bar");l.appendChild(d),n.appendChild(l),t.appendChild(n);let p=e.file.type.startsWith("image/"),g=this.opts.imageEditing!==!1;if(p&&g&&e.state==="queued"){let c=document.createElement("button");c.type="button",c.className="us-file-action",c.setAttribute("aria-label","Edit image"),c.title="Edit image",c.innerHTML=m.pencil,c.dataset.edited=e.edited?"true":"false",c.onclick=()=>this.openEditor(e),t.appendChild(c),e.$edit=c}let h=u("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=s,e.$thumb=r,this.$list.appendChild(t),this.updateSummary()}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=V(t.type)}else e.$thumb.innerHTML=V(t.type);if(e.$meta&&(e.$meta.textContent=H(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){!this.$panel||this.editor||e.state!=="queued"||(this.editor=new K({host:this.$panel,file:e.file,originalFile:e.originalFile,title:e.originalFile.name,onApply:t=>{let i=t!==e.originalFile;this.replaceItemFile(e,t,i),this.editor=null},onCancel:()=>{this.editor=null}}),this.editor.open())}statusIcon(e){switch(e){case"uploading":return m.spinner;case"done":return m.check;case"failed":return m.alert;case"cancelled":return m.alert;default:return m.spinner}}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=H(e.file.size);switch(t){case"uploading":e.$meta.textContent=`${r} \xB7 ${Math.round(e.progress)}%`;break;case"done":e.$meta.textContent=r;break;case"failed":e.$meta.textContent=e.error||"Failed";break;default:e.$meta.textContent=r}}this.updateSummary()}updateSummary(){if(!this.$summary)return;let e=this.items.length;if(e===0){this.$summary.textContent="";return}let t=this.items.filter(n=>n.state==="done").length,i=this.items.filter(n=>n.state==="failed").length,r=this.items.filter(n=>n.state==="uploading"||n.state==="queued").length;if(!this.uploadStarted&&r>0){let n=this.items.filter(a=>a.state==="queued").length;this.$summary.textContent=`${n} file${n===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`}refreshConfirm(){if(!this.$confirm)return;let e=this.items.filter(t=>t.state==="queued").length;this.$confirm.disabled=e===0||this.uploadStarted}async startUpload(){if(this.uploadStarted)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,L(y({},this.opts),{signal:this.abortCtrl.signal,onUploadStarted:r=>{var n,a;r.forEach((s,l)=>{let d=e[l];d&&(d.uploadId=s.uploadId,d.$row&&(d.$row.dataset.uploadId=s.uploadId),t.set(s.uploadId,d))}),(a=(n=this.opts).onUploadStarted)==null||a.call(n,r)},onFileUploadStarted:r=>{var a,s;let n=t.get(r.uploadId);n&&this.setItemState(n,"uploading",0),(s=(a=this.opts).onFileUploadStarted)==null||s.call(a,r)},onFileUploadProgress:(r,n)=>{var s,l;let a=t.get(r.uploadId);a&&this.setItemState(a,"uploading",n.totalPercent),(l=(s=this.opts).onFileUploadProgress)==null||l.call(s,r,n)},onFileUploadFinished:r=>{var a,s;let n=t.get(r.uploadId);n&&(n.uploaded=r,this.setItemState(n,"done",100)),(s=(a=this.opts).onFileUploadFinished)==null||s.call(a,r)},onFileUploadFailed:(r,n)=>{var s,l;let a=t.get(r.uploadId);a&&(a.error=n.message,this.setItemState(a,"failed")),(l=(s=this.opts).onFileUploadFailed)==null||l.call(s,r,n)},onUploadDone:r=>{var n,a;(a=(n=this.opts).onUploadDone)==null||a.call(n,r),this.resolveResult(r),this.unmount()},onError:r=>{var n,a;(a=(n=this.opts).onError)==null||a.call(n,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)}}});var ve={};re(ve,{Picker:()=>F,openPicker:()=>Y});var Q=_(()=>{"use strict";ge()});var Xe={};re(Xe,{Picker:()=>F,UnionStackClient:()=>B,init:()=>Ye,openPicker:()=>Y});function f(o,e,t={}){var i;return{code:o,message:e,status:t.status,retryable:(i=t.retryable)!=null?i:$e(o,t.status),cause:t.cause}}function $e(o,e){return!!(o==="NETWORK"||o==="PART_FAILED"||o==="SERVER"&&e&&e>=500)}function ie(o,e){let t=e==null?void 0:e.error,i=(t==null?void 0:t.message)||`Request failed with status ${o}`,r=((t==null?void 0:t.code)||"").toUpperCase();if(o===401)return f("AUTH",i,{status:o,retryable:!1});if(o===403)return f("AUTH",i,{status:o,retryable:!1});if(o===413)return f("VALIDATION",i,{status:o,retryable:!1});if(o===415)return f("VALIDATION",i,{status:o,retryable:!1});if(o===426)return f("CONFIG",i,{status:o,retryable:!1});if(o===429){let n=r==="QUOTA_EXCEEDED";return f(n?"QUOTA":"NETWORK",i,{status:o,retryable:!n})}return o>=500?f("SERVER",i,{status:o,retryable:!0}):f("SERVER",i,{status:o,retryable:!1})}var Pe="0.3.0",oe=`js/${Pe}`;var Te=3,Re=3,ne=[400,1200,3600],W=class{constructor(e){this.cfg=e}describe(e,t={}){let i=typeof File!="undefined"&&e instanceof File,r=t.filename||(i?e.name:"untitled"),n=t.mimeType||e.type||"application/octet-stream";return{uploadId:Se(),filename:r,mimetype:n,size:e.size,source:"local"}}async upload(e,t={}){var r,n,a;let i=this.describe(e,{filename:t.filename,mimeType:t.mimeType});(r=t.onFileUploadStarted)==null||r.call(t,i);try{let s=await this.initUpload(i,t),l=await this.uploadAllParts(e,s,i,t),d=await this.completeUpload(s.sessionId,l,t),p=L(y({},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(n=t.onFileUploadFinished)==null||n.call(t,p),p}catch(s){let l=se(s);throw(a=t.onFileUploadFailed)==null||a.call(t,i,l),s!=null&&s.sessionId&&this.abortSilently(s.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 b,T;let n=t.totalParts,a=t.chunkSize,s=Math.max(1,(b=r.concurrency)!=null?b:Te),l=(T=r.maxRetriesPerPart)!=null?T:Re,d=new Map(t.partUrls.map(x=>[x.partNumber,x.url])),p=new Array(n),g=new Array(n).fill(0),h=1,c=e.size,U=()=>{var C;let x=g.reduce((I,v)=>I+v,0),R=c>0?Math.min(100,Math.round(x/c*100)):100,S={totalBytes:c,loaded:x,totalPercent:R};(C=r.onFileUploadProgress)==null||C.call(r,i,S)},$=async()=>{var x,R,S,C,I;for(;;){if((x=r.signal)!=null&&x.aborted)throw f("ABORTED","Upload aborted by caller.",{retryable:!1});let v=h++;if(v>n)return;let A=(v-1)*a,G=Math.min(A+a,e.size),j=e.slice(A,G),O=0,D;for(;O<=l;){if((R=r.signal)!=null&&R.aborted)throw f("ABORTED","Upload aborted by caller.",{retryable:!1});try{let M=d.get(v);M||(M=(await this.api("POST","/sdk/v1/uploads/sign-part",{sessionId:t.sessionId,partNumber:v},r.signal)).url,d.set(v,M));let z=(I=await((C=(S=this.cfg).fetch)==null?void 0:C.call(S,M,{method:"PUT",body:j,signal:r.signal})))!=null?I:await fetch(M,{method:"PUT",body:j,signal:r.signal});if(!z.ok)throw(z.status===403||z.status===401)&&d.delete(v),f("PART_FAILED",`Part ${v} PUT failed (HTTP ${z.status})`,{status:z.status});let J=z.headers.get("etag");if(!J)throw f("PART_FAILED",`Part ${v}: R2 did not return an ETag.`);p[v-1]={partNumber:v,etag:J,size:j.size},g[v-1]=j.size,U();break}catch(M){if(D=M,O++,O>l)break;await Ie(ne[Math.min(O-1,ne.length-1)])}}if(!p[v-1])throw Me(se(D!=null?D:f("PART_FAILED",`Part ${v} failed after ${l} retries.`)),t.sessionId)}},P=Array.from({length:Math.min(s,n)},$);return await Promise.all(P),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;let n=(d=this.cfg.fetch)!=null?d:fetch,a=`${this.cfg.apiBase}${t}`,s;try{s=await n(a,{method:e,headers:{Authorization:`Bearer ${this.cfg.apiKey}`,"Content-Type":"application/json","X-UnionStack-SDK":oe},body:i===void 0?void 0:JSON.stringify(i),signal:r})}catch(p){throw(p==null?void 0:p.name)==="AbortError"?f("ABORTED","Request aborted.",{retryable:!1,cause:p}):f("NETWORK","Network request failed.",{retryable:!0,cause:p})}let l=null;try{l=await s.json()}catch(p){}if(!s.ok)throw ie(s.status,l);return l}};function Se(){return typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36)}function Ie(o){return new Promise(e=>setTimeout(e,o))}function se(o){if(o&&typeof o=="object"&&"code"in o&&"message"in o&&"retryable"in o)return o;let e=(o==null?void 0:o.message)||"Upload failed.";return f("NETWORK",e,{cause:o})}function Me(o,e){return o&&typeof o=="object"&&(o.sessionId=e),o}var Ke="https://api.unionstack.link/v1",be="unionstack-preloader-styles";function Ve(){if(typeof document=="undefined")return()=>{};if(!document.getElementById(be)){let i=document.createElement("style");i.id=be,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 o=document.createElement("div");o.setAttribute("role","status"),o.setAttribute("aria-label","Loading file picker"),o.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;",o.appendChild(e),document.body.appendChild(o);let t=!1;return()=>{t||(t=!0,o.remove())}}var B=class{constructor(e){if(!e.apiKey)throw f("CONFIG","apiKey is required.",{retryable:!1});this.resolvedCfg=L(y({},e),{apiBase:Ke}),this.uploader=new W(this.resolvedCfg),this.pickerConfigPromise=this.resolvedCfg.skipConfigPrefetch?Promise.resolve(null):this.uploader.fetchPickerConfig().then(t=>(t!=null&&t.sdkWarning&&console.warn(`[UnionStack] ${t.sdkWarning}`),t)).catch(()=>null)}upload(e,t={}){return this.uploader.upload(e,t)}async uploadMany(e,t={}){var s,l,d;if(!Array.isArray(e)||e.length===0){let p=f("VALIDATION","uploadMany requires a non-empty array of files.",{retryable:!1});throw(s=t.onError)==null||s.call(t,p),p}let i=e.map(p=>this.uploader.describe(p,{filename:t.filename,mimeType:t.mimeType}));(l=t.onUploadStarted)==null||l.call(t,i);let r=[],n=[];await Promise.all(e.map(async(p,g)=>{try{let h=await this.uploader.upload(p,t);h.uploadId=i[g].uploadId,r.push(h)}catch(h){n.push({file:i[g],error:h})}}));let a={filesUploaded:r,filesFailed:n};return(d=t.onUploadDone)==null||d.call(t,a),a}picker(e={}){let t=null,i=!1,r,n,a=new Promise((s,l)=>{r=s,n=l});return{open:async()=>{if(i)return a;i=!0;let s=Ve();try{t=(await Promise.resolve().then(()=>(Q(),ve))).openPicker(this,L(y({},e),{onOpen:()=>{var p;s(),(p=e.onOpen)==null||p.call(e)}}));let d=await t.open();return s(),r(d),d}catch(l){s();let d=l!=null&&l.code?l:f("CONFIG","Failed to load picker.",{retryable:!1,cause:l});throw n(d),d}},close:()=>{t==null||t.close()},cancel:()=>{t==null||t.cancel()}}}get config(){return this.resolvedCfg}};var X={init(o){return new B(o)}};Q();var Ye=X.init.bind(X);(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=X.init({apiKey:t});queueMicrotask(()=>{window.UnionStack&&(window.UnionStack.client=i)})}catch(i){console.error("[UnionStack] auto-init failed:",i)}})();return Ue(Xe);})();
507
507
  //# sourceMappingURL=loader.v1.global.js.map