@masters-union/union-stack 0.1.6 → 0.1.8

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 j=Object.defineProperty,le=Object.defineProperties,de=Object.getOwnPropertyDescriptor,pe=Object.getOwnPropertyDescriptors,ce=Object.getOwnPropertyNames,W=Object.getOwnPropertySymbols;var G=Object.prototype.hasOwnProperty,ue=Object.prototype.propertyIsEnumerable;var Y=(r,e,t)=>e in r?j(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,$=(r,e)=>{for(var t in e||(e={}))G.call(e,t)&&Y(r,t,e[t]);if(W)for(var t of W(e))ue.call(e,t)&&Y(r,t,e[t]);return r},z=(r,e)=>le(r,pe(e));var q=(r,e)=>()=>(r&&(e=r(r=0)),e);var Q=(r,e)=>{for(var t in e)j(r,t,{get:e[t],enumerable:!0})},fe=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ce(e))!G.call(r,i)&&i!==t&&j(r,i,{get:()=>e[i],enumerable:!(o=de(e,i))||o.enumerable});return r};var me=r=>fe(j({},"__esModule",{value:!0}),r);function te(){if(typeof document=="undefined"||document.getElementById(ee))return;let r=document.createElement("style");r.id=ee,r.textContent=Ue,document.head.appendChild(r)}function re(r){var o,i,s,a,n;let t=((r==null?void 0:r.mode)||"light")==="dark"?we:xe;return{"--us-primary":(o=r==null?void 0:r.primary)!=null?o:t.primary,"--us-bg":(i=r==null?void 0:r.background)!=null?i:t.background,"--us-fg":(s=r==null?void 0:r.foreground)!=null?s:t.foreground,"--us-muted":t.muted,"--us-subtle":t.subtle,"--us-border":(a=r==null?void 0:r.border)!=null?a:t.border,"--us-border-strong":t.borderStrong,"--us-elevated":t.elevated,"--us-success":t.success,"--us-danger":t.danger,"--us-radius":(n=r==null?void 0:r.radius)!=null?n:"12px"}}var ee,xe,we,Ue,ie=q(()=>{"use strict";ee="unionstack-picker-styles";xe={primary:"#4f46e5",background:"#ffffff",foreground:"#0f172a",muted:"#64748b",subtle:"#f8fafc",border:"#e2e8f0",borderStrong:"#cbd5e1",elevated:"#ffffff",success:"#16a34a",danger:"#dc2626"},we={primary:"#818cf8",background:"#0b0f1a",foreground:"#f1f5f9",muted:"#94a3b8",subtle:"#111827",border:"#1f2937",borderStrong:"#334155",elevated:"#0f1625",success:"#4ade80",danger:"#f87171"},Ue=`
1
+ "use strict";var UnionStack=(()=>{var N=Object.defineProperty,ge=Object.defineProperties,ve=Object.getOwnPropertyDescriptor,be=Object.getOwnPropertyDescriptors,xe=Object.getOwnPropertyNames,Z=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,ye=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,k=(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))ye.call(e,t)&&ee(o,t,e[t]);return o},z=(o,e)=>ge(o,be(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})},ke=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xe(e))!te.call(o,r)&&r!==t&&N(o,r,{get:()=>e[r],enumerable:!(i=ve(e,r))||i.enumerable});return o};var we=o=>ke(N({},"__esModule",{value:!0}),o);function ae(){if(typeof document=="undefined"||document.getElementById(se))return;let o=document.createElement("style");o.id=se,o.textContent=Le,document.head.appendChild(o)}function le(o){var i,r,n,a,s;let t=((o==null?void 0:o.mode)||"light")==="dark"?Me:Re;return{"--us-primary":(i=o==null?void 0:o.primary)!=null?i:t.primary,"--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-success":t.success,"--us-danger":t.danger,"--us-radius":(s=o==null?void 0:o.radius)!=null?s:"12px"}}var se,Re,Me,Le,de=W(()=>{"use strict";se="unionstack-picker-styles";Re={primary:"#4f46e5",background:"#ffffff",foreground:"#0f172a",muted:"#64748b",subtle:"#f8fafc",border:"#e2e8f0",borderStrong:"#cbd5e1",elevated:"#ffffff",success:"#16a34a",danger:"#dc2626"},Me={primary:"#818cf8",background:"#0b0f1a",foreground:"#f1f5f9",muted:"#94a3b8",subtle:"#111827",border:"#1f2937",borderStrong:"#334155",elevated:"#0f1625",success:"#4ade80",danger:"#f87171"},Le=`
2
2
  .us-picker-backdrop {
3
3
  position: fixed; inset: 0; z-index: 2147483000;
4
4
  background: color-mix(in srgb, #02060f 55%, transparent);
@@ -18,6 +18,7 @@
18
18
  width: 100%; max-width: 480px;
19
19
  max-height: min(calc(100dvh - 32px), 680px);
20
20
  display: flex; flex-direction: column;
21
+ position: relative;
21
22
  box-shadow:
22
23
  0 1px 1px rgba(0,0,0,0.04),
23
24
  0 18px 40px -8px rgba(0,0,0,0.18),
@@ -254,6 +255,178 @@
254
255
  .us-footer a { color: var(--us-muted); text-decoration: none; font-weight: 500; }
255
256
  .us-footer a:hover { color: var(--us-fg); }
256
257
 
258
+ /* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 source tabs (Device / URL) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
259
+ .us-source-tabs {
260
+ display: inline-flex; gap: 2px; padding: 3px;
261
+ background: var(--us-subtle);
262
+ border: 1px solid var(--us-border);
263
+ border-radius: 10px;
264
+ margin-bottom: 14px;
265
+ }
266
+ .us-source-tab {
267
+ appearance: none; background: transparent; border: 0;
268
+ font: inherit; cursor: pointer;
269
+ padding: 6px 14px; min-height: 30px;
270
+ border-radius: 7px;
271
+ font-size: 12.5px; font-weight: 500; letter-spacing: -0.005em;
272
+ color: var(--us-muted);
273
+ transition: background 140ms, color 140ms;
274
+ display: inline-flex; align-items: center; gap: 6px;
275
+ }
276
+ .us-source-tab svg { width: 13px; height: 13px; }
277
+ .us-source-tab:hover { color: var(--us-fg); }
278
+ .us-source-tab[data-active="true"] {
279
+ background: var(--us-bg);
280
+ color: var(--us-fg);
281
+ box-shadow: 0 1px 2px rgba(0,0,0,0.06);
282
+ }
283
+ .us-source-tab:focus-visible { outline: 2px solid var(--us-primary); outline-offset: 2px; }
284
+
285
+ /* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 URL source \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
286
+ .us-url-source { display: none; }
287
+ .us-url-source[data-active="true"] { display: block; }
288
+ .us-url-form {
289
+ display: flex; gap: 8px;
290
+ padding: 16px;
291
+ border: 1.5px dashed var(--us-border-strong);
292
+ border-radius: calc(var(--us-radius) - 2px);
293
+ background: color-mix(in srgb, var(--us-subtle) 60%, transparent);
294
+ }
295
+ .us-url-input {
296
+ appearance: none;
297
+ flex: 1; min-width: 0;
298
+ padding: 9px 12px; min-height: 36px;
299
+ border-radius: 8px; border: 1px solid var(--us-border);
300
+ background: var(--us-bg); color: var(--us-fg);
301
+ font: inherit; font-size: 13px;
302
+ transition: border-color 140ms, box-shadow 140ms;
303
+ }
304
+ .us-url-input::placeholder { color: var(--us-muted); }
305
+ .us-url-input:focus {
306
+ outline: none;
307
+ border-color: var(--us-primary);
308
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--us-primary) 18%, transparent);
309
+ }
310
+ .us-url-hint {
311
+ margin-top: 8px;
312
+ font-size: 11.5px; color: var(--us-muted);
313
+ }
314
+ .us-url-hint[data-error="true"] { color: var(--us-danger); }
315
+
316
+ /* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 per-row edit button \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
317
+ .us-file-actions { display: inline-flex; gap: 4px; }
318
+ .us-file-action {
319
+ appearance: none; background: transparent; border: 0; cursor: pointer;
320
+ width: 28px; height: 28px;
321
+ display: inline-flex; align-items: center; justify-content: center;
322
+ color: var(--us-muted); border-radius: 6px;
323
+ transition: background 140ms, color 140ms;
324
+ }
325
+ .us-file-action:hover { background: var(--us-subtle); color: var(--us-fg); }
326
+ .us-file-action:focus-visible { outline: 2px solid var(--us-primary); outline-offset: 1px; }
327
+ .us-file-action svg { width: 15px; height: 15px; }
328
+ .us-file-action[data-edited="true"] { color: var(--us-primary); }
329
+ .us-file:not([data-state="queued"]) .us-file-action { display: none; }
330
+
331
+ /* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 image editor overlay \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
332
+ .us-editor {
333
+ position: absolute; inset: 0; z-index: 2;
334
+ display: flex; flex-direction: column;
335
+ background: var(--us-bg);
336
+ animation: us-fade 140ms ease-out;
337
+ }
338
+ .us-editor-header {
339
+ display: flex; align-items: center; gap: 12px;
340
+ padding: 14px 16px;
341
+ border-bottom: 1px solid var(--us-border);
342
+ }
343
+ .us-editor-title { font-weight: 600; font-size: 14px; flex: 1; letter-spacing: -0.01em; }
344
+ .us-editor-back {
345
+ appearance: none; background: transparent; border: 0; cursor: pointer;
346
+ width: 32px; height: 32px; border-radius: 8px;
347
+ display: inline-flex; align-items: center; justify-content: center;
348
+ color: var(--us-muted);
349
+ transition: background 140ms, color 140ms;
350
+ }
351
+ .us-editor-back:hover { background: var(--us-subtle); color: var(--us-fg); }
352
+ .us-editor-back svg { width: 16px; height: 16px; }
353
+
354
+ .us-editor-canvas-wrap {
355
+ flex: 1; min-height: 0;
356
+ background: var(--us-subtle);
357
+ display: flex; align-items: center; justify-content: center;
358
+ padding: 16px;
359
+ position: relative;
360
+ overflow: hidden;
361
+ }
362
+ .us-editor-canvas {
363
+ max-width: 100%; max-height: 100%;
364
+ border-radius: 6px;
365
+ display: block;
366
+ /* Checkerboard for transparency awareness (visible only in circle mode). */
367
+ background-image:
368
+ linear-gradient(45deg, var(--us-border) 25%, transparent 25%, transparent 75%, var(--us-border) 75%),
369
+ linear-gradient(45deg, var(--us-border) 25%, transparent 25%, transparent 75%, var(--us-border) 75%);
370
+ background-size: 12px 12px;
371
+ background-position: 0 0, 6px 6px;
372
+ }
373
+ .us-editor-overlay {
374
+ position: absolute; inset: 0;
375
+ pointer-events: none;
376
+ }
377
+
378
+ .us-editor-toolbar {
379
+ display: flex; gap: 6px; flex-wrap: wrap;
380
+ padding: 10px 16px;
381
+ border-top: 1px solid var(--us-border);
382
+ }
383
+ .us-tool {
384
+ appearance: none; background: transparent; border: 1px solid var(--us-border);
385
+ font: inherit; cursor: pointer;
386
+ padding: 6px 11px; min-height: 32px;
387
+ border-radius: 8px;
388
+ font-size: 12.5px; font-weight: 500;
389
+ color: var(--us-fg);
390
+ display: inline-flex; align-items: center; gap: 6px;
391
+ transition: background 140ms, border-color 140ms, color 140ms;
392
+ }
393
+ .us-tool:hover { background: var(--us-subtle); border-color: var(--us-border-strong); }
394
+ .us-tool[data-active="true"] {
395
+ background: color-mix(in srgb, var(--us-primary) 10%, var(--us-bg));
396
+ border-color: var(--us-primary);
397
+ color: var(--us-primary);
398
+ }
399
+ .us-tool[disabled] { opacity: 0.45; cursor: not-allowed; }
400
+ .us-tool svg { width: 13px; height: 13px; }
401
+ .us-tool-spacer { flex: 1; }
402
+
403
+ .us-editor-footer {
404
+ display: flex; gap: 8px; justify-content: flex-end;
405
+ padding: 12px 16px;
406
+ border-top: 1px solid var(--us-border);
407
+ }
408
+
409
+ /* Crop drag handles. Drawn inside .us-editor-canvas-wrap, positioned over canvas. */
410
+ .us-crop-box {
411
+ position: absolute;
412
+ border: 1.5px solid var(--us-primary);
413
+ box-shadow: 0 0 0 9999px rgba(0,0,0,0.45);
414
+ pointer-events: auto;
415
+ cursor: move;
416
+ }
417
+ .us-crop-handle {
418
+ position: absolute;
419
+ width: 12px; height: 12px;
420
+ background: var(--us-bg);
421
+ border: 1.5px solid var(--us-primary);
422
+ border-radius: 2px;
423
+ pointer-events: auto;
424
+ }
425
+ .us-crop-handle[data-pos="nw"] { top: -6px; left: -6px; cursor: nwse-resize; }
426
+ .us-crop-handle[data-pos="ne"] { top: -6px; right: -6px; cursor: nesw-resize; }
427
+ .us-crop-handle[data-pos="sw"] { bottom: -6px; left: -6px; cursor: nesw-resize; }
428
+ .us-crop-handle[data-pos="se"] { bottom: -6px; right: -6px; cursor: nwse-resize; }
429
+
257
430
  /* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 reduced motion \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
258
431
  @media (prefers-reduced-motion: reduce) {
259
432
  .us-picker-backdrop,
@@ -263,11 +436,14 @@
263
436
  .us-dropzone-icon,
264
437
  .us-btn,
265
438
  .us-file-status,
266
- .us-file-progress-bar { animation: none !important; transition: none !important; }
439
+ .us-file-progress-bar,
440
+ .us-editor,
441
+ .us-source-tab,
442
+ .us-tool { animation: none !important; transition: none !important; }
267
443
  .us-file[data-state="uploading"] .us-file-progress-bar::after { animation: none; opacity: 0; }
268
444
  }
269
445
 
270
446
  /* \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 */
271
447
  .us-file-list:empty { display: none; }
272
- `});function Ce(r,e){var s,a,n,l,d,p,h,b,k,x,g,I,S,R,y,w,U,v,C,f;let t=$({},e),o=e.branding||{};t.branding={logoUrl:(a=(s=o.logoUrl)!=null?s:r.branding.logoUrl)!=null?a:void 0,title:(l=(n=o.title)!=null?n:r.branding.title)!=null?l:void 0,hideFooter:(d=o.hideFooter)!=null?d:r.branding.hideFooter};let i=e.theme||{};if(t.theme={primary:(h=(p=i.primary)!=null?p:r.theme.primary)!=null?h:void 0,background:(k=(b=i.background)!=null?b:r.theme.background)!=null?k:void 0,foreground:(g=(x=i.foreground)!=null?x:r.theme.foreground)!=null?g:void 0,border:(S=(I=i.border)!=null?I:r.theme.border)!=null?S:void 0,radius:(y=(R=i.radius)!=null?R:r.theme.radius)!=null?y:void 0,mode:(U=(w=i.mode)!=null?w:r.theme.mode)!=null?U:void 0},t.maxFileSize=(v=e.maxFileSize)!=null?v:r.constraints.maxFileSizeBytes,t.maxFiles=(C=e.maxFiles)!=null?C:r.constraints.maxFilesPerUpload,!e.accept&&((f=r.constraints.allowedMimeTypes)!=null&&f.length)){let A=r.constraints.allowedMimeTypes.filter(_=>_!=="*/*");A.length>0&&(t.accept=A.join(","))}return t}function oe(r){return r?r.startsWith("image/")?m.image:r.startsWith("video/")?m.video:r.startsWith("audio/")?m.audio:r==="application/pdf"?m.pdf:r.startsWith("application/zip")||r.includes("compressed")||r==="application/x-tar"||r==="application/gzip"?m.archive:m.file:m.file}function c(r,e,t){let o=document.createElement(r);return e&&(o.className=e),t!==void 0&&(o.textContent=t),o}function D(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:r<1024*1024*1024?`${(r/1024/1024).toFixed(1)} MB`:`${(r/1024/1024/1024).toFixed(2)} GB`}function ne(){return typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36)}function H(r,e){let t=new F(r,e);return{open:()=>t.open(),close:()=>t.close(),cancel:()=>t.cancel()}}var Pe,$e,m,F,se=q(()=>{"use strict";ie();Pe="Upload files",$e="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>',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>'};F=class{constructor(e,t){this.client=e;this.opts=t;this.$backdrop=null;this.$list=null;this.$confirm=null;this.$cancel=null;this.$closeBtn=null;this.$input=null;this.items=[];this.abortCtrl=new AbortController;this.uploadStarted=!1;this.resolved=!1;this.$summary=null;this.donePromise=new Promise(o=>{this.resolvePromise=o})}async open(){var e,t;if(typeof document=="undefined")throw new Error("[union-stack] Picker requires a browser environment.");try{let o=await this.client.pickerConfigPromise;o&&(this.opts=Ce(o,this.opts))}catch(o){}return te(),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 p,h,b,k,x;let e=document.createElement("div");e.className="us-picker-backdrop",Object.entries(re(this.opts.theme)).forEach(([g,I])=>{e.style.setProperty(g,I)}),e.addEventListener("click",g=>{g.target===e&&!this.uploadStarted&&this.cancel()});let t=c("div","us-picker"),o=c("div","us-picker-header"),i=c("div","us-picker-header-logo");if((p=this.opts.branding)!=null&&p.logoUrl){let g=document.createElement("img");g.src=this.opts.branding.logoUrl,g.alt="",i.appendChild(g)}else i.innerHTML=m.zap;o.appendChild(i);let s=c("div","us-picker-title",(b=(h=this.opts.branding)==null?void 0:h.title)!=null?b:Pe);o.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=m.close,this.$closeBtn.onclick=()=>this.cancel(),o.appendChild(this.$closeBtn),t.appendChild(o);let a=c("div","us-picker-body");a.appendChild(this.renderDropzone()),this.$list=c("div","us-file-list"),a.appendChild(this.$list),t.appendChild(a);let n=this.opts.autoUpload!==!1,l=c("div","us-actions");this.$summary=c("div","us-actions-summary",""),l.appendChild(this.$summary);let d=c("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(),d.appendChild(this.$cancel),n||(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(),d.appendChild(this.$confirm)),l.appendChild(d),t.appendChild(l),!((k=this.opts.branding)!=null&&k.hideFooter)){let g=c("div","us-footer");g.innerHTML=`${m.zap} <span>Powered by <a href="${$e}" target="_blank" rel="noopener">UnionStack</a></span>`,t.appendChild(g)}e.appendChild(t),((x=this.opts.container)!=null?x:document.body).appendChild(e),this.$backdrop=e}renderDropzone(){var s;let e=c("div","us-dropzone");e.setAttribute("role","button"),e.setAttribute("tabindex","0"),e.setAttribute("aria-label","Drop files here or click to browse");let t=c("div","us-dropzone-icon");t.innerHTML=m.upload,e.appendChild(t),e.appendChild(c("div","us-dropzone-title","Drop files to upload")),e.appendChild(c("div","us-dropzone-hint","or click to browse from your device"));let o=[];if(this.opts.maxFileSize&&o.push(`max ${D(this.opts.maxFileSize)}`),this.opts.accept){let a=this.opts.accept.split(",").map(n=>n.trim()).filter(n=>n&&n!=="*/*").map(n=>n.replace("/*",""));a.length>0&&a.length<=4&&o.push(a.join(" \xB7 "))}o.length>0&&e.appendChild(c("div","us-dropzone-constraints",o.join(" \xB7 ")));let i=document.createElement("input");return i.type="file",i.multiple=((s=this.opts.maxFiles)!=null?s:10)>1,this.opts.accept&&(i.accept=this.opts.accept),i.style.display="none",i.onchange=()=>{i.files&&this.addFiles(Array.from(i.files)),i.value=""},this.$input=i,e.appendChild(i),e.onclick=()=>i.click(),e.onkeydown=a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),i.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 n=(l=a.dataTransfer)==null?void 0:l.files;n&&this.addFiles(Array.from(n))}),e}unmount(){var e,t,o;(e=this.$backdrop)!=null&&e.parentNode&&this.$backdrop.parentNode.removeChild(this.$backdrop),this.$backdrop=null;for(let i of this.items)i.objectUrl&&URL.revokeObjectURL(i.objectUrl);(o=(t=this.opts).onClose)==null||o.call(t)}addFiles(e){var n;let o=((n=this.opts.maxFiles)!=null?n:1/0)-this.items.length;if(o<=0)return;let i=e.slice(0,o);for(let l of i){if(this.opts.maxFileSize&&l.size>this.opts.maxFileSize){let p={uploadId:ne(),file:l,state:"failed",progress:0,error:`File exceeds ${D(this.opts.maxFileSize)} limit`};this.items.push(p),this.renderItem(p);continue}let d={uploadId:ne(),file:l,state:"queued",progress:0};this.items.push(d),this.renderItem(d)}this.refreshConfirm();let s=this.opts.autoUpload!==!1,a=this.items.some(l=>l.state==="queued");s&&a&&!this.uploadStarted&&requestAnimationFrame(()=>{this.uploadStarted||this.startUpload()})}renderItem(e){if(!this.$list)return;let t=c("div","us-file");t.dataset.state=e.state,t.dataset.uploadId=e.uploadId;let o=Math.min(this.items.length-1,8);t.style.animationDelay=`${o*35}ms`;let i=c("div","us-file-thumb");if(e.file.type.startsWith("image/")&&typeof URL!="undefined"&&URL.createObjectURL)try{let h=URL.createObjectURL(e.file);e.objectUrl=h,i.style.backgroundImage=`url("${h}")`,i.dataset.image="true"}catch(h){i.innerHTML=oe(e.file.type)}else i.innerHTML=oe(e.file.type);t.appendChild(i);let s=c("div","us-file-main"),a=c("div","us-file-row1");a.appendChild(c("div","us-file-name",e.file.name));let n=c("div","us-file-meta",D(e.file.size));a.appendChild(n),s.appendChild(a);let l=c("div","us-file-progress"),d=c("div","us-file-progress-bar");l.appendChild(d),s.appendChild(l),t.appendChild(s);let p=c("div","us-file-status");p.setAttribute("aria-label",this.statusLabel(e)),p.innerHTML=this.statusIcon(e.state),t.appendChild(p),e.$row=t,e.$bar=d,e.$status=p,e.$meta=n,this.$list.appendChild(t),this.updateSummary()}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,o){if(e.state=t,o!==void 0&&(e.progress=o),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 i=D(e.file.size);switch(t){case"uploading":e.$meta.textContent=`${i} \xB7 ${Math.round(e.progress)}%`;break;case"done":e.$meta.textContent=i;break;case"failed":e.$meta.textContent=e.error||"Failed";break;default:e.$meta.textContent=i}}this.updateSummary()}updateSummary(){if(!this.$summary)return;let e=this.items.length;if(e===0){this.$summary.textContent="";return}let t=this.items.filter(s=>s.state==="done").length,o=this.items.filter(s=>s.state==="failed").length;this.items.filter(s=>s.state==="uploading"||s.state==="queued").length>0?this.$summary.textContent=`Uploading ${t+1} of ${e}`:o>0?this.$summary.textContent=`${t} of ${e} uploaded \xB7 ${o} 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(i=>i.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,o=e.map(i=>i.file);try{await this.client.uploadMany(o,z($({},this.opts),{signal:this.abortCtrl.signal,onUploadStarted:i=>{var s,a;i.forEach((n,l)=>{let d=e[l];d&&(d.uploadId=n.uploadId,d.$row&&(d.$row.dataset.uploadId=n.uploadId),t.set(n.uploadId,d))}),(a=(s=this.opts).onUploadStarted)==null||a.call(s,i)},onFileUploadStarted:i=>{var a,n;let s=t.get(i.uploadId);s&&this.setItemState(s,"uploading",0),(n=(a=this.opts).onFileUploadStarted)==null||n.call(a,i)},onFileUploadProgress:(i,s)=>{var n,l;let a=t.get(i.uploadId);a&&this.setItemState(a,"uploading",s.totalPercent),(l=(n=this.opts).onFileUploadProgress)==null||l.call(n,i,s)},onFileUploadFinished:i=>{var a,n;let s=t.get(i.uploadId);s&&(s.uploaded=i,this.setItemState(s,"done",100)),(n=(a=this.opts).onFileUploadFinished)==null||n.call(a,i)},onFileUploadFailed:(i,s)=>{var n,l;let a=t.get(i.uploadId);a&&(a.error=s.message,this.setItemState(a,"failed")),(l=(n=this.opts).onFileUploadFailed)==null||l.call(n,i,s)},onUploadDone:i=>{var s,a;(a=(s=this.opts).onUploadDone)==null||a.call(s,i),this.resolveResult(i),this.unmount()},onError:i=>{var s,a;(a=(s=this.opts).onError)==null||a.call(s,i),this.resolveResult(),this.unmount()}}))}catch(i){this.resolved||(this.resolveResult(),this.unmount())}}resolveResult(e){if(this.resolved)return;this.resolved=!0;let t=e!=null?e:{filesUploaded:this.items.filter(o=>o.uploaded).map(o=>o.uploaded),filesFailed:this.items.filter(o=>o.state==="failed").map(o=>({file:{uploadId:o.uploadId,filename:o.file.name,mimetype:o.file.type||"application/octet-stream",size:o.file.size,source:"local"},error:{code:"VALIDATION",message:o.error||"failed",retryable:!1}}))};this.resolvePromise(t)}}});var ae={};Q(ae,{Picker:()=>F,openPicker:()=>H});var V=q(()=>{"use strict";se()});var Ie={};Q(Ie,{Picker:()=>F,UnionStackClient:()=>E,init:()=>Ee,openPicker:()=>H});function u(r,e,t={}){var o;return{code:r,message:e,status:t.status,retryable:(o=t.retryable)!=null?o:he(r,t.status),cause:t.cause}}function he(r,e){return!!(r==="NETWORK"||r==="PART_FAILED"||r==="SERVER"&&e&&e>=500)}function X(r,e){let t=e==null?void 0:e.error,o=(t==null?void 0:t.message)||`Request failed with status ${r}`,i=((t==null?void 0:t.code)||"").toUpperCase();if(r===401)return u("AUTH",o,{status:r,retryable:!1});if(r===403)return u("AUTH",o,{status:r,retryable:!1});if(r===413)return u("VALIDATION",o,{status:r,retryable:!1});if(r===415)return u("VALIDATION",o,{status:r,retryable:!1});if(r===429){let s=i==="QUOTA_EXCEEDED";return u(s?"QUOTA":"NETWORK",o,{status:r,retryable:!s})}return r>=500?u("SERVER",o,{status:r,retryable:!0}):u("SERVER",o,{status:r,retryable:!1})}var ge=3,be=3,J=[400,1200,3600],O=class{constructor(e){this.cfg=e}describe(e,t={}){let o=typeof File!="undefined"&&e instanceof File,i=t.filename||(o?e.name:"untitled"),s=t.mimeType||e.type||"application/octet-stream";return{uploadId:ye(),filename:i,mimetype:s,size:e.size,source:"local"}}async upload(e,t={}){var i,s,a;let o=this.describe(e,{filename:t.filename,mimeType:t.mimeType});(i=t.onFileUploadStarted)==null||i.call(t,o);try{let n=await this.initUpload(o,t),l=await this.uploadAllParts(e,n,o,t),d=await this.completeUpload(n.sessionId,l,t),p=z($({},o),{handle:d.handle,fileId:d.fileId,url:d.url,size:d.size,mimetype:d.mimetype,filename:d.filename,status:"Stored",etag:d.etag});return(s=t.onFileUploadFinished)==null||s.call(t,p),p}catch(n){let l=Z(n);throw(a=t.onFileUploadFailed)==null||a.call(t,o,l),n!=null&&n.sessionId&&this.abortSilently(n.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,o,i){var S,R;let s=t.totalParts,a=t.chunkSize,n=Math.max(1,(S=i.concurrency)!=null?S:ge),l=(R=i.maxRetriesPerPart)!=null?R:be,d=new Map(t.partUrls.map(y=>[y.partNumber,y.url])),p=new Array(s),h=new Array(s).fill(0),b=1,k=e.size,x=()=>{var v;let y=h.reduce((C,f)=>C+f,0),w=k>0?Math.min(100,Math.round(y/k*100)):100,U={totalBytes:k,loaded:y,totalPercent:w};(v=i.onFileUploadProgress)==null||v.call(i,o,U)},g=async()=>{var y,w,U,v,C;for(;;){if((y=i.signal)!=null&&y.aborted)throw u("ABORTED","Upload aborted by caller.",{retryable:!1});let f=b++;if(f>s)return;let A=(f-1)*a,_=Math.min(A+a,e.size),L=e.slice(A,_),B=0,M;for(;B<=l;){if((w=i.signal)!=null&&w.aborted)throw u("ABORTED","Upload aborted by caller.",{retryable:!1});try{let P=d.get(f);P||(P=(await this.api("POST","/sdk/v1/uploads/sign-part",{sessionId:t.sessionId,partNumber:f},i.signal)).url,d.set(f,P));let T=(C=await((v=(U=this.cfg).fetch)==null?void 0:v.call(U,P,{method:"PUT",body:L,signal:i.signal})))!=null?C:await fetch(P,{method:"PUT",body:L,signal:i.signal});if(!T.ok)throw(T.status===403||T.status===401)&&d.delete(f),u("PART_FAILED",`Part ${f} PUT failed (HTTP ${T.status})`,{status:T.status});let K=T.headers.get("etag");if(!K)throw u("PART_FAILED",`Part ${f}: R2 did not return an ETag.`);p[f-1]={partNumber:f,etag:K,size:L.size},h[f-1]=L.size,x();break}catch(P){if(M=P,B++,B>l)break;await ke(J[Math.min(B-1,J.length-1)])}}if(!p[f-1])throw ve(Z(M!=null?M:u("PART_FAILED",`Part ${f} failed after ${l} retries.`)),t.sessionId)}},I=Array.from({length:Math.min(n,s)},g);return await Promise.all(I),p}async completeUpload(e,t,o){return this.api("POST","/sdk/v1/uploads/complete",{sessionId:e,parts:t.map(i=>({partNumber:i.partNumber,etag:i.etag}))},o.signal)}async abortSilently(e){try{await this.abort(e)}catch(t){}}async api(e,t,o,i){var d;let s=(d=this.cfg.fetch)!=null?d:fetch,a=`${this.cfg.apiBase}${t}`,n;try{n=await s(a,{method:e,headers:{Authorization:`Bearer ${this.cfg.apiKey}`,"Content-Type":"application/json"},body:o===void 0?void 0:JSON.stringify(o),signal:i})}catch(p){throw(p==null?void 0:p.name)==="AbortError"?u("ABORTED","Request aborted.",{retryable:!1,cause:p}):u("NETWORK","Network request failed.",{retryable:!0,cause:p})}let l=null;try{l=await n.json()}catch(p){}if(!n.ok)throw X(n.status,l);return l}};function ye(){return typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36)}function ke(r){return new Promise(e=>setTimeout(e,r))}function Z(r){if(r&&typeof r=="object"&&"code"in r&&"message"in r&&"retryable"in r)return r;let e=(r==null?void 0:r.message)||"Upload failed.";return u("NETWORK",e,{cause:r})}function ve(r,e){return r&&typeof r=="object"&&(r.sessionId=e),r}var Fe="https://cdn-api.mastersunion.org/cdn-api",E=class{constructor(e){if(!e.apiKey)throw u("CONFIG","apiKey is required.",{retryable:!1});this.resolvedCfg=z($({},e),{apiBase:Fe}),this.uploader=new O(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 n,l,d;if(!Array.isArray(e)||e.length===0){let p=u("VALIDATION","uploadMany requires a non-empty array of files.",{retryable:!1});throw(n=t.onError)==null||n.call(t,p),p}let o=e.map(p=>this.uploader.describe(p,{filename:t.filename,mimeType:t.mimeType}));(l=t.onUploadStarted)==null||l.call(t,o);let i=[],s=[];await Promise.all(e.map(async(p,h)=>{try{let b=await this.uploader.upload(p,t);b.uploadId=o[h].uploadId,i.push(b)}catch(b){s.push({file:o[h],error:b})}}));let a={filesUploaded:i,filesFailed:s};return(d=t.onUploadDone)==null||d.call(t,a),a}picker(e={}){let t=null,o=!1,i,s,a=new Promise((n,l)=>{i=n,s=l});return{open:async()=>{if(o)return a;o=!0;try{t=(await Promise.resolve().then(()=>(V(),ae))).openPicker(this,e);let l=await t.open();return i(l),l}catch(n){let l=n!=null&&n.code?n:u("CONFIG","Failed to load picker.",{retryable:!1,cause:n});throw s(l),l}},close:()=>{t==null||t.close()},cancel:()=>{t==null||t.cancel()}}}get config(){return this.resolvedCfg}};var N={init(r){return new E(r)}};V();var Ee=N.init.bind(N);(function(){if(typeof document=="undefined")return;let e=document.currentScript;if(!e)return;let t=e.getAttribute("data-unionstack-key");if(t)try{let o=N.init({apiKey:t});queueMicrotask(()=>{window.UnionStack&&(window.UnionStack.client=o)})}catch(o){console.error("[UnionStack] auto-init failed:",o)}})();return me(Ie);})();
448
+ `});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>${Se(o)}</span>`,t}function Se(o){return o.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function y(o,e,t){return Math.max(e,Math.min(t,o))}function pe(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 ce(o){return/^image\/(png|webp|gif)$/.test(o)}var U,K,ue=W(()=>{"use strict";U={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=y(r.x+t,0,n-r.w),d=y(r.y+i,0,a-r.h);break;case"nw":{let h=y(r.x+t,0,r.x+r.w-s),c=y(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=y(r.w+t,s,n-r.x),c=y(r.y+i,0,r.y+r.h-s);g=r.h+(r.y-c),p=h,d=c;break}case"sw":{let h=y(r.x+t,0,r.x+r.w-s),c=y(r.h+i,s,a-r.y);p=r.w+(r.x-h),g=c,l=h;break}case"se":p=y(r.w+t,s,n-r.x),g=y(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=U.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",U.crop),this.cropTool.onclick=()=>this.toggleCropMode(),this.circleTool=_("Circle",U.circle),this.circleTool.onclick=()=>this.applyCircle(),this.rotateTool=_("Rotate 90\xB0",U.rotate),this.rotateTool.onclick=()=>this.applyRotate(),this.revertTool=_("Revert",U.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=`${U.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 pe(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=ce(this.opts.file.type),this.markEdited(!1)}async loadTrueOriginalIntoWorking(){var n;let e=(n=this.opts.originalFile)!=null?n:this.opts.file,t=await pe(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=ce(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=`${U.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=`${U.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:k({},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 Ie(o,e){var n,a,s,l,d,p,g,h,c,E,$,P,b,T,x,R,M,C,L,v;let t=k({},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:($=(E=r.foreground)!=null?E: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=(L=e.maxFiles)!=null?L: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 he(){return typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36)}async function ze(o){let e;try{e=await fetch(o,{mode:"cors",credentials:"omit"})}catch(n){throw new Error(`Could not reach ${Ae(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=He(o)||"download",r=t.type||je(i);return new File([t],i,{type:r})}function Ae(o){try{return new URL(o).host}catch(e){return"that host"}}function He(o){try{let t=new URL(o).pathname.split("/").filter(Boolean).pop();return t?decodeURIComponent(t):""}catch(e){return""}}function je(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 I(o,e);return{open:()=>t.open(),close:()=>t.close(),cancel:()=>t.cancel()}}var Fe,Be,m,I,fe=W(()=>{"use strict";de();ue();Fe="Upload files",Be="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>',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>'};I=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=Ie(i,this.opts))}catch(i){}return ae(),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,E,$,P;let e=document.createElement("div");e.className="us-picker-backdrop",Object.entries(le(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:Fe);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((E=s[0])!=null?E:"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="${Be}" 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 ze(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.upload,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:he(),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:he(),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;this.items.filter(n=>n.state==="uploading"||n.state==="queued").length>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,z(k({},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 me={};re(me,{Picker:()=>I,openPicker:()=>Y});var Q=W(()=>{"use strict";fe()});var Ne={};re(Ne,{Picker:()=>I,UnionStackClient:()=>F,init:()=>De,openPicker:()=>Y});function f(o,e,t={}){var i;return{code:o,message:e,status:t.status,retryable:(i=t.retryable)!=null?i:Ce(o,t.status),cause:t.cause}}function Ce(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 Ue=3,Ee=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:$e(),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=z(k({},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:Ue),l=(T=r.maxRetriesPerPart)!=null?T:Ee,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,E=()=>{var C;let x=g.reduce((L,v)=>L+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,L;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 S=d.get(v);S||(S=(await this.api("POST","/sdk/v1/uploads/sign-part",{sessionId:t.sessionId,partNumber:v},r.signal)).url,d.set(v,S));let B=(L=await((C=(M=this.cfg).fetch)==null?void 0:C.call(M,S,{method:"PUT",body:j,signal:r.signal})))!=null?L:await fetch(S,{method:"PUT",body:j,signal:r.signal});if(!B.ok)throw(B.status===403||B.status===401)&&d.delete(v),f("PART_FAILED",`Part ${v} PUT failed (HTTP ${B.status})`,{status:B.status});let J=B.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,E();break}catch(S){if(D=S,O++,O>l)break;await Pe(oe[Math.min(O-1,oe.length-1)])}}if(!p[v-1])throw Te(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 $e(){return typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36)}function Pe(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 Te(o,e){return o&&typeof o=="object"&&(o.sessionId=e),o}var Oe="https://api.unionstack.link/v1",F=class{constructor(e){if(!e.apiKey)throw f("CONFIG","apiKey is required.",{retryable:!1});this.resolvedCfg=z(k({},e),{apiBase:Oe}),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;try{t=(await Promise.resolve().then(()=>(Q(),me))).openPicker(this,e);let l=await t.open();return r(l),l}catch(s){let l=s!=null&&s.code?s:f("CONFIG","Failed to load picker.",{retryable:!1,cause:s});throw n(l),l}},close:()=>{t==null||t.close()},cancel:()=>{t==null||t.cancel()}}}get config(){return this.resolvedCfg}};var X={init(o){return new F(o)}};Q();var De=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 we(Ne);})();
273
449
  //# sourceMappingURL=loader.v1.global.js.map