@swan-admin/swan-web-component 1.0.77 → 1.0.79

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.
Files changed (38) hide show
  1. package/dist/Header-CDkpLwYo.js +2 -0
  2. package/dist/Header-CDkpLwYo.js.map +1 -0
  3. package/dist/Header-F5rF4_EK.js +2 -0
  4. package/dist/Header-F5rF4_EK.js.map +1 -0
  5. package/dist/Header-KIq-IIp4.js +2 -0
  6. package/dist/Header-KIq-IIp4.js.map +1 -0
  7. package/dist/Header-SK4TdjTG.js +2 -0
  8. package/dist/Header-SK4TdjTG.js.map +1 -0
  9. package/dist/LoadingScreen-CJW5H884.js +2 -0
  10. package/dist/LoadingScreen-CJW5H884.js.map +1 -0
  11. package/dist/LoadingScreen-Cye_sGZu.js +2 -0
  12. package/dist/LoadingScreen-Cye_sGZu.js.map +1 -0
  13. package/dist/LoadingScreen-Czxa8Is0.js +2 -0
  14. package/dist/LoadingScreen-Czxa8Is0.js.map +1 -0
  15. package/dist/LoadingScreen-aAtRsi7Q.js +2 -0
  16. package/dist/LoadingScreen-aAtRsi7Q.js.map +1 -0
  17. package/dist/arrow-right-DWlQRbzE.js +27 -0
  18. package/dist/arrow-right-DWlQRbzE.js.map +1 -0
  19. package/dist/arrow-right-fsdw-5QY.js +27 -0
  20. package/dist/arrow-right-fsdw-5QY.js.map +1 -0
  21. package/dist/bodyScan.js +2 -2
  22. package/dist/bodyScan.js.map +1 -1
  23. package/dist/bodyScan.mjs +2 -2
  24. package/dist/bodyScan.mjs.map +1 -1
  25. package/dist/enums-BLzZlPIt.js +32 -0
  26. package/dist/enums-BLzZlPIt.js.map +1 -0
  27. package/dist/enums-BV1_VQpZ.js +32 -0
  28. package/dist/enums-BV1_VQpZ.js.map +1 -0
  29. package/dist/faceScan.js +1 -1
  30. package/dist/faceScan.js.map +1 -1
  31. package/dist/faceScan.mjs +1 -1
  32. package/dist/faceScan.mjs.map +1 -1
  33. package/dist/index.css +1 -1
  34. package/dist/index.js +2 -2
  35. package/dist/index.js.map +1 -1
  36. package/dist/index.mjs +2 -2
  37. package/dist/index.mjs.map +1 -1
  38. package/package.json +1 -1
package/dist/bodyScan.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var e=require("react/jsx-runtime"),t=require("react"),n=require("./Header-BiYtGF6l.js"),r=require("./enums-BD0ckKV4.js"),o=require("./LoadingScreen-D7OUJo45.js"),i=require("video.js");function s(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}require("react-dom");var a=s(t);function l(e){const{sx:t,...n}=e,{systemProps:o,otherProps:i}=(e=>{const t={systemProps:{},otherProps:{}},n=e?.theme?.unstable_sxConfig??r.defaultSxConfig;return Object.keys(e).forEach(r=>{n[r]?t.systemProps[r]=e[r]:t.otherProps[r]=e[r]}),t})(n);let s;return s=Array.isArray(t)?[o,...t]:"function"==typeof t?(...e)=>{const n=t(...e);return r.isPlainObject(n)?{...o,...n}:o}:{...o,...t},{...i,sx:s}}const c=r.generateUtilityClasses("MuiBox",["root"]),u=r.createTheme(),d=function(t={}){const{themeId:n,defaultTheme:o,defaultClassName:i="MuiBox-root",generateClassName:s}=t,c=r.styled$1("div",{shouldForwardProp:e=>"theme"!==e&&"sx"!==e&&"as"!==e})(r.styleFunctionSx);return a.forwardRef(function(t,a){const u=r.useTheme(o),{className:d,component:h="div",...p}=l(t);return e.jsx(c,{as:h,ref:a,className:r.clsx(d,s?s(i):i),theme:n&&u[n]||u,...p})})}({themeId:r.THEME_ID,defaultTheme:u,defaultClassName:c.root,generateClassName:r.ClassNameGenerator.generate});function h(e){return r.generateUtilityClass("MuiDialog",e)}"production"!==process.env.NODE_ENV&&(d.propTypes={children:r.PropTypes.node,component:r.PropTypes.elementType,sx:r.PropTypes.oneOfType([r.PropTypes.arrayOf(r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object,r.PropTypes.bool])),r.PropTypes.func,r.PropTypes.object])});const p=r.generateUtilityClasses("MuiDialog",["root","scrollPaper","scrollBody","container","paper","paperScrollPaper","paperScrollBody","paperWidthFalse","paperWidthXs","paperWidthSm","paperWidthMd","paperWidthLg","paperWidthXl","paperFullWidth","paperFullScreen"]),_=a.createContext({});"production"!==process.env.NODE_ENV&&(_.displayName="DialogContext");const f=r.styled(r.Backdrop,{name:"MuiDialog",slot:"Backdrop",overrides:(e,t)=>t.backdrop})({zIndex:-1}),m=r.styled(r.Modal,{name:"MuiDialog",slot:"Root"})({"@media print":{position:"absolute !important"}}),g=r.styled("div",{name:"MuiDialog",slot:"Container",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.container,t[`scroll${r.capitalize(n.scroll)}`]]}})({height:"100%","@media print":{height:"auto"},outline:0,variants:[{props:{scroll:"paper"},style:{display:"flex",justifyContent:"center",alignItems:"center"}},{props:{scroll:"body"},style:{overflowY:"auto",overflowX:"hidden",textAlign:"center","&::after":{content:'""',display:"inline-block",verticalAlign:"middle",height:"100%",width:"0"}}}]}),y=r.styled(r.Paper,{name:"MuiDialog",slot:"Paper",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.paper,t[`scrollPaper${r.capitalize(n.scroll)}`],t[`paperWidth${r.capitalize(String(n.maxWidth))}`],n.fullWidth&&t.paperFullWidth,n.fullScreen&&t.paperFullScreen]}})(r.memoTheme(({theme:e})=>({margin:32,position:"relative",overflowY:"auto","@media print":{overflowY:"visible",boxShadow:"none"},variants:[{props:{scroll:"paper"},style:{display:"flex",flexDirection:"column",maxHeight:"calc(100% - 64px)"}},{props:{scroll:"body"},style:{display:"inline-block",verticalAlign:"middle",textAlign:"initial"}},{props:({ownerState:e})=>!e.maxWidth,style:{maxWidth:"calc(100% - 64px)"}},{props:{maxWidth:"xs"},style:{maxWidth:"px"===e.breakpoints.unit?Math.max(e.breakpoints.values.xs,444):`max(${e.breakpoints.values.xs}${e.breakpoints.unit}, 444px)`,[`&.${p.paperScrollBody}`]:{[e.breakpoints.down(Math.max(e.breakpoints.values.xs,444)+64)]:{maxWidth:"calc(100% - 64px)"}}}},...Object.keys(e.breakpoints.values).filter(e=>"xs"!==e).map(t=>({props:{maxWidth:t},style:{maxWidth:`${e.breakpoints.values[t]}${e.breakpoints.unit}`,[`&.${p.paperScrollBody}`]:{[e.breakpoints.down(e.breakpoints.values[t]+64)]:{maxWidth:"calc(100% - 64px)"}}}})),{props:({ownerState:e})=>e.fullWidth,style:{width:"calc(100% - 64px)"}},{props:({ownerState:e})=>e.fullScreen,style:{margin:0,width:"100%",maxWidth:"100%",height:"100%",maxHeight:"none",borderRadius:0,[`&.${p.paperScrollBody}`]:{margin:0,maxWidth:"100%"}}}]}))),v=a.forwardRef(function(t,n){const o=r.useDefaultProps({props:t,name:"MuiDialog"}),i=r.useTheme$1(),s={enter:i.transitions.duration.enteringScreen,exit:i.transitions.duration.leavingScreen},{"aria-describedby":l,"aria-labelledby":c,"aria-modal":u=!0,BackdropComponent:d,BackdropProps:p,children:v,className:w,disableEscapeKeyDown:b=!1,fullScreen:S=!1,fullWidth:E=!1,maxWidth:P="sm",onClick:T,onClose:k,open:x,PaperComponent:C=r.Paper,PaperProps:O={},scroll:j="paper",slots:R={},slotProps:A={},TransitionComponent:N=r.Fade,transitionDuration:F=s,TransitionProps:I,...M}=o,U={...o,disableEscapeKeyDown:b,fullScreen:S,fullWidth:E,maxWidth:P,scroll:j},L=(e=>{const{classes:t,scroll:n,maxWidth:o,fullWidth:i,fullScreen:s}=e,a={root:["root"],container:["container",`scroll${r.capitalize(n)}`],paper:["paper",`paperScroll${r.capitalize(n)}`,`paperWidth${r.capitalize(String(o))}`,i&&"paperFullWidth",s&&"paperFullScreen"]};return r.composeClasses(a,h,t)})(U),z=a.useRef(),D=r.useId(c),B=a.useMemo(()=>({titleId:D}),[D]),$={slots:{transition:N,...R},slotProps:{transition:I,paper:O,backdrop:p,...A}},[q,W]=r.useSlot("root",{elementType:m,shouldForwardComponentProp:!0,externalForwardedProps:$,ownerState:U,className:r.clsx(L.root,w),ref:n}),[H,V]=r.useSlot("backdrop",{elementType:f,shouldForwardComponentProp:!0,externalForwardedProps:$,ownerState:U}),[K,Y]=r.useSlot("paper",{elementType:y,shouldForwardComponentProp:!0,externalForwardedProps:$,ownerState:U,className:r.clsx(L.paper,O.className)}),[G,J]=r.useSlot("container",{elementType:g,externalForwardedProps:$,ownerState:U,className:L.container}),[X,Q]=r.useSlot("transition",{elementType:r.Fade,externalForwardedProps:$,ownerState:U,additionalProps:{appear:!0,in:x,timeout:F,role:"presentation"}});return e.jsx(q,{closeAfterTransition:!0,slots:{backdrop:H},slotProps:{backdrop:{transitionDuration:F,as:d,...V}},disableEscapeKeyDown:b,onClose:k,open:x,onClick:e=>{T&&T(e),z.current&&(z.current=null,k&&k(e,"backdropClick"))},...W,...M,children:e.jsx(X,{...Q,children:e.jsx(G,{onMouseDown:e=>{z.current=e.target===e.currentTarget},...J,children:e.jsx(K,{as:C,elevation:24,role:"dialog","aria-describedby":l,"aria-labelledby":D,"aria-modal":u,...Y,children:e.jsx(_.Provider,{value:B,children:v})})})})})});function w(e){return"function"==typeof e?e():e}function b(e,t,n){const o=function(e,t,n){const o=t.getBoundingClientRect(),i=n&&n.getBoundingClientRect(),s=r.ownerWindow(t);let a;if(t.fakeTransform)a=t.fakeTransform;else{const e=s.getComputedStyle(t);a=e.getPropertyValue("-webkit-transform")||e.getPropertyValue("transform")}let l=0,c=0;if(a&&"none"!==a&&"string"==typeof a){const e=a.split("(")[1].split(")")[0].split(",");l=parseInt(e[4],10),c=parseInt(e[5],10)}return"left"===e?i?`translateX(${i.right+l-o.left}px)`:`translateX(${s.innerWidth+l-o.left}px)`:"right"===e?i?`translateX(-${o.right-i.left-l}px)`:`translateX(-${o.left+o.width-l}px)`:"up"===e?i?`translateY(${i.bottom+c-o.top}px)`:`translateY(${s.innerHeight+c-o.top}px)`:i?`translateY(-${o.top-i.top+o.height-c}px)`:`translateY(-${o.top+o.height-c}px)`}(e,t,w(n));o&&(t.style.webkitTransform=o,t.style.transform=o)}"production"!==process.env.NODE_ENV&&(v.propTypes={"aria-describedby":r.PropTypes.string,"aria-labelledby":r.PropTypes.string,"aria-modal":r.PropTypes.oneOfType([r.PropTypes.oneOf(["false","true"]),r.PropTypes.bool]),BackdropComponent:r.PropTypes.elementType,BackdropProps:r.PropTypes.object,children:r.PropTypes.node,classes:r.PropTypes.object,className:r.PropTypes.string,disableEscapeKeyDown:r.PropTypes.bool,fullScreen:r.PropTypes.bool,fullWidth:r.PropTypes.bool,maxWidth:r.PropTypes.oneOfType([r.PropTypes.oneOf(["xs","sm","md","lg","xl",!1]),r.PropTypes.string]),onClick:r.PropTypes.func,onClose:r.PropTypes.func,open:r.PropTypes.bool.isRequired,PaperComponent:r.PropTypes.elementType,PaperProps:r.PropTypes.object,scroll:r.PropTypes.oneOf(["body","paper"]),slotProps:r.PropTypes.shape({backdrop:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),container:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),paper:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),root:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),transition:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object])}),slots:r.PropTypes.shape({backdrop:r.PropTypes.elementType,container:r.PropTypes.elementType,paper:r.PropTypes.elementType,root:r.PropTypes.elementType,transition:r.PropTypes.elementType}),sx:r.PropTypes.oneOfType([r.PropTypes.arrayOf(r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object,r.PropTypes.bool])),r.PropTypes.func,r.PropTypes.object]),TransitionComponent:r.PropTypes.elementType,transitionDuration:r.PropTypes.oneOfType([r.PropTypes.number,r.PropTypes.shape({appear:r.PropTypes.number,enter:r.PropTypes.number,exit:r.PropTypes.number})]),TransitionProps:r.PropTypes.object});const S=a.forwardRef(function(t,n){const o=r.useTheme$1(),i={enter:o.transitions.easing.easeOut,exit:o.transitions.easing.sharp},s={enter:o.transitions.duration.enteringScreen,exit:o.transitions.duration.leavingScreen},{addEndListener:l,appear:c=!0,children:u,container:d,direction:h="down",easing:p=i,in:_,onEnter:f,onEntered:m,onEntering:g,onExit:y,onExited:v,onExiting:w,style:S,timeout:E=s,TransitionComponent:P=r.Transition,...T}=t,k=a.useRef(null),x=r.useForkRef(r.getReactElementRef(u),k,n),C=e=>t=>{e&&(void 0===t?e(k.current):e(k.current,t))},O=C((e,t)=>{b(h,e,d),r.reflow(e),f&&f(e,t)}),j=C((e,t)=>{const n=r.getTransitionProps({timeout:E,style:S,easing:p},{mode:"enter"});e.style.webkitTransition=o.transitions.create("-webkit-transform",{...n}),e.style.transition=o.transitions.create("transform",{...n}),e.style.webkitTransform="none",e.style.transform="none",g&&g(e,t)}),R=C(m),A=C(w),N=C(e=>{const t=r.getTransitionProps({timeout:E,style:S,easing:p},{mode:"exit"});e.style.webkitTransition=o.transitions.create("-webkit-transform",t),e.style.transition=o.transitions.create("transform",t),b(h,e,d),y&&y(e)}),F=C(e=>{e.style.webkitTransition="",e.style.transition="",v&&v(e)}),I=a.useCallback(()=>{k.current&&b(h,k.current,d)},[h,d]);return a.useEffect(()=>{if(_||"down"===h||"right"===h)return;const e=r.debounce(()=>{k.current&&b(h,k.current,d)}),t=r.ownerWindow(k.current);return t.addEventListener("resize",e),()=>{e.clear(),t.removeEventListener("resize",e)}},[h,_,d]),a.useEffect(()=>{_||I()},[_,I]),e.jsx(P,{nodeRef:k,onEnter:O,onEntered:R,onEntering:j,onExit:N,onExited:F,onExiting:A,addEndListener:e=>{l&&l(k.current,e)},appear:c,in:_,timeout:E,...T,children:(e,{ownerState:t,...n})=>a.cloneElement(u,{ref:x,style:{visibility:"exited"!==e||_?void 0:"hidden",...S,...u.props.style},...n})})});function E(e){return r.generateUtilityClass("MuiDrawer",e)}"production"!==process.env.NODE_ENV&&(S.propTypes={addEndListener:r.PropTypes.func,appear:r.PropTypes.bool,children:r.elementAcceptingRef.isRequired,container:r.chainPropTypes(r.PropTypes.oneOfType([r.HTMLElementType,r.PropTypes.func]),e=>{if(e.open){const t=w(e.container);if(t&&1===t.nodeType){const e=t.getBoundingClientRect();if("test"!==process.env.NODE_ENV&&0===e.top&&0===e.left&&0===e.right&&0===e.bottom)return new Error(["MUI: The `container` prop provided to the component is invalid.","The anchor element should be part of the document layout.","Make sure the element is present in the document or that it's not display none."].join("\n"))}else if(!t||"function"!=typeof t.getBoundingClientRect||null!=t.contextElement&&1!==t.contextElement.nodeType)return new Error(["MUI: The `container` prop provided to the component is invalid.","It should be an HTML element instance."].join("\n"))}return null}),direction:r.PropTypes.oneOf(["down","left","right","up"]),easing:r.PropTypes.oneOfType([r.PropTypes.shape({enter:r.PropTypes.string,exit:r.PropTypes.string}),r.PropTypes.string]),in:r.PropTypes.bool,onEnter:r.PropTypes.func,onEntered:r.PropTypes.func,onEntering:r.PropTypes.func,onExit:r.PropTypes.func,onExited:r.PropTypes.func,onExiting:r.PropTypes.func,style:r.PropTypes.object,timeout:r.PropTypes.oneOfType([r.PropTypes.number,r.PropTypes.shape({appear:r.PropTypes.number,enter:r.PropTypes.number,exit:r.PropTypes.number})])}),r.generateUtilityClasses("MuiDrawer",["root","docked","paper","anchorLeft","anchorRight","anchorTop","anchorBottom","paperAnchorLeft","paperAnchorRight","paperAnchorTop","paperAnchorBottom","paperAnchorDockedLeft","paperAnchorDockedRight","paperAnchorDockedTop","paperAnchorDockedBottom","modal"]);const P=(e,t)=>{const{ownerState:n}=e;return[t.root,("permanent"===n.variant||"persistent"===n.variant)&&t.docked,t.modal]},T=r.styled(r.Modal,{name:"MuiDrawer",slot:"Root",overridesResolver:P})(r.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.drawer}))),k=r.styled("div",{shouldForwardProp:r.rootShouldForwardProp,name:"MuiDrawer",slot:"Docked",skipVariantsResolver:!1,overridesResolver:P})({flex:"0 0 auto"}),x=r.styled(r.Paper,{name:"MuiDrawer",slot:"Paper",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.paper,t[`paperAnchor${r.capitalize(n.anchor)}`],"temporary"!==n.variant&&t[`paperAnchorDocked${r.capitalize(n.anchor)}`]]}})(r.memoTheme(({theme:e})=>({overflowY:"auto",display:"flex",flexDirection:"column",height:"100%",flex:"1 0 auto",zIndex:(e.vars||e).zIndex.drawer,WebkitOverflowScrolling:"touch",position:"fixed",top:0,outline:0,variants:[{props:{anchor:"left"},style:{left:0}},{props:{anchor:"top"},style:{top:0,left:0,right:0,height:"auto",maxHeight:"100%"}},{props:{anchor:"right"},style:{right:0}},{props:{anchor:"bottom"},style:{top:"auto",left:0,bottom:0,right:0,height:"auto",maxHeight:"100%"}},{props:({ownerState:e})=>"left"===e.anchor&&"temporary"!==e.variant,style:{borderRight:`1px solid ${(e.vars||e).palette.divider}`}},{props:({ownerState:e})=>"top"===e.anchor&&"temporary"!==e.variant,style:{borderBottom:`1px solid ${(e.vars||e).palette.divider}`}},{props:({ownerState:e})=>"right"===e.anchor&&"temporary"!==e.variant,style:{borderLeft:`1px solid ${(e.vars||e).palette.divider}`}},{props:({ownerState:e})=>"bottom"===e.anchor&&"temporary"!==e.variant,style:{borderTop:`1px solid ${(e.vars||e).palette.divider}`}}]}))),C={left:"right",right:"left",top:"down",bottom:"up"};const O=a.forwardRef(function(t,n){const o=r.useDefaultProps({props:t,name:"MuiDrawer"}),i=r.useTheme$1(),s=r.useRtl(),l={enter:i.transitions.duration.enteringScreen,exit:i.transitions.duration.leavingScreen},{anchor:c="left",BackdropProps:u,children:d,className:h,elevation:p=16,hideBackdrop:_=!1,ModalProps:{BackdropProps:f,...m}={},onClose:g,open:y=!1,PaperProps:v={},SlideProps:w,TransitionComponent:b,transitionDuration:P=l,variant:O="temporary",slots:j={},slotProps:R={},...A}=o,N=a.useRef(!1);a.useEffect(()=>{N.current=!0},[]);const F=function({direction:e},t){return"rtl"===e&&function(e){return["left","right"].includes(e)}(t)?C[t]:t}({direction:s?"rtl":"ltr"},c),I=c,M={...o,anchor:I,elevation:p,open:y,variant:O,...A},U=(e=>{const{classes:t,anchor:n,variant:o}=e,i={root:["root",`anchor${r.capitalize(n)}`],docked:[("permanent"===o||"persistent"===o)&&"docked"],modal:["modal"],paper:["paper",`paperAnchor${r.capitalize(n)}`,"temporary"!==o&&`paperAnchorDocked${r.capitalize(n)}`]};return r.composeClasses(i,E,t)})(M),L={slots:{transition:b,...j},slotProps:{paper:v,transition:w,...R,backdrop:r.mergeSlotProps$1(R.backdrop||{...u,...f},{transitionDuration:P})}},[z,D]=r.useSlot("root",{ref:n,elementType:T,className:r.clsx(U.root,U.modal,h),shouldForwardComponentProp:!0,ownerState:M,externalForwardedProps:{...L,...A,...m},additionalProps:{open:y,onClose:g,hideBackdrop:_,slots:{backdrop:L.slots.backdrop},slotProps:{backdrop:L.slotProps.backdrop}}}),[B,$]=r.useSlot("paper",{elementType:x,shouldForwardComponentProp:!0,className:r.clsx(U.paper,v.className),ownerState:M,externalForwardedProps:L,additionalProps:{elevation:"temporary"===O?p:0,square:!0,..."temporary"===O&&{role:"dialog","aria-modal":"true"}}}),[q,W]=r.useSlot("docked",{elementType:k,ref:n,className:r.clsx(U.root,U.docked,h),ownerState:M,externalForwardedProps:L,additionalProps:A}),[H,V]=r.useSlot("transition",{elementType:S,ownerState:M,externalForwardedProps:L,additionalProps:{in:y,direction:C[F],timeout:P,appear:N.current}}),K=e.jsx(B,{...$,children:d});if("permanent"===O)return e.jsx(q,{...W,children:K});const Y=e.jsx(H,{...V,children:K});return"persistent"===O?e.jsx(q,{...W,children:Y}):e.jsx(z,{...D,children:Y})});"production"!==process.env.NODE_ENV&&(O.propTypes={anchor:r.PropTypes.oneOf(["bottom","left","right","top"]),BackdropProps:r.PropTypes.object,children:r.PropTypes.node,classes:r.PropTypes.object,className:r.PropTypes.string,elevation:r.integerPropType,hideBackdrop:r.PropTypes.bool,ModalProps:r.PropTypes.object,onClose:r.PropTypes.func,open:r.PropTypes.bool,PaperProps:r.PropTypes.object,SlideProps:r.PropTypes.object,slotProps:r.PropTypes.shape({backdrop:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),docked:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),paper:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),root:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),transition:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object])}),slots:r.PropTypes.shape({backdrop:r.PropTypes.elementType,docked:r.PropTypes.elementType,paper:r.PropTypes.elementType,root:r.PropTypes.elementType,transition:r.PropTypes.elementType}),sx:r.PropTypes.oneOfType([r.PropTypes.arrayOf(r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object,r.PropTypes.bool])),r.PropTypes.func,r.PropTypes.object]),transitionDuration:r.PropTypes.oneOfType([r.PropTypes.number,r.PropTypes.shape({appear:r.PropTypes.number,enter:r.PropTypes.number,exit:r.PropTypes.number})]),variant:r.PropTypes.oneOf(["permanent","persistent","temporary"])});var j=t.memo(function({size:t=16}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 25 25",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M22.6968 14.6968C22.6968 16.8185 21.8539 18.8533 20.3536 20.3536C18.8533 21.8539 16.8185 22.6968 14.6968 22.6968",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M18.6968 11.6968V10.6968C18.6968 10.1663 18.4861 9.65764 18.111 9.28256C17.7359 8.90749 17.2272 8.69678 16.6968 8.69678C16.1663 8.69678 15.6576 8.90749 15.2826 9.28256C14.9075 9.65764 14.6968 10.1663 14.6968 10.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M14.6968 10.6968V9.69678C14.6968 9.16634 14.4861 8.65764 14.111 8.28256C13.7359 7.90749 13.2272 7.69678 12.6968 7.69678C12.1663 7.69678 11.6576 7.90749 11.2826 8.28256C10.9075 8.65764 10.6968 9.16634 10.6968 9.69678V10.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M10.6968 10.1968V4.69678C10.6968 4.16634 10.4861 3.65764 10.111 3.28256C9.73592 2.90749 9.22721 2.69678 8.69678 2.69678C8.16634 2.69678 7.65764 2.90749 7.28256 3.28256C6.90749 3.65764 6.69678 4.16634 6.69678 4.69678V14.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M18.6969 11.6968C18.6969 11.1663 18.9076 10.6576 19.2827 10.2826C19.6577 9.90749 20.1664 9.69678 20.6969 9.69678C21.2273 9.69678 21.736 9.90749 22.1111 10.2826C22.4862 10.6576 22.6969 11.1663 22.6969 11.6968V14.6968C22.6969 16.8185 21.854 18.8533 20.3537 20.3536C18.8534 21.8539 16.8186 22.6968 14.6969 22.6968H12.6969C9.89688 22.6968 8.19688 21.8368 6.70688 20.3568L3.10688 16.7568C2.76282 16.3757 2.57847 15.8769 2.592 15.3637C2.60554 14.8505 2.81593 14.3621 3.1796 13.9997C3.54327 13.6373 4.03238 13.4287 4.54565 13.417C5.05892 13.4053 5.55704 13.5914 5.93688 13.9368L7.69688 15.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})});var R,A=t.memo(function({angle:o,countdown:i,isScanning:s,isInTargetRange:a,stabilityScore:l,children:c,config:u}){const d=t.useCallback(()=>o<80?Math.max(0,Math.min(100,10*(o-60))):o>95?Math.max(0,Math.min(100,10*(105-o))):100,[o]),h=t.useMemo(()=>{if(s)return u?.style?.base?.brandColor||"#4f46e5";const e=d();if(0===e)return"#ffffff";if(100===e)return u?.style?.base?.brandColor||"#8b5cf6";return`rgb(${Math.round(255-e/100*116)}, ${Math.round(255-e/100*163)}, ${Math.round(255-e/100*9)})`},[s,d]),p=t.useCallback((e,t)=>t>70?e?"text-[#fff]/70":"text-[#fff]":e?"text-[#fff]/40":"text-[#000]/70",[]),_=t.useCallback((e=!1)=>{const t=d();return s?"text-[#fff]":p(e,t)},[s,d]),f=i;function m(){document.documentElement.style.setProperty("--real-vh",window.innerHeight+"px")}return m(),window.addEventListener("resize",m),e.jsxs("div",{className:"flex w-screen flex-col items-center h-[var(--real-vh)] overflow-hidden touch-none justify-center transition-all duration-300 max-w-[28rem] mx-auto",style:{backgroundColor:h},children:[e.jsx("div",{className:"flex justify-start fixed top-[.5rem] max-w-[28rem] mx-auto w-full px-[1rem]",children:e.jsx("div",{className:"flex justify-start ",children:e.jsx(n.Header,{noTitle:!0,resolvedConfig:u})})}),null!==f?e.jsx("div",{className:"relative flex h-[6rem] w-[6rem] items-center justify-center rounded-[9999px] border-2 border-[#fff] bg-[#fff]/20 transition-all duration-300",children:e.jsx("div",{className:"text-[3rem] font-bold text-[#fff]",style:{fontFamily:u?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:f})}):s?e.jsxs("div",{className:"relative flex flex-col items-center justify-center",children:[e.jsx("div",{className:"relative flex h-16 w-16 items-center justify-center rounded-[9999px] border-2 bg-[#fff]/30 border-[#fff]",children:e.jsx("div",{className:"h-4 w-4 rounded-[9999px] animate-pulse bg-[#fff]/80"})}),c]}):e.jsxs("div",{className:r.clsx("relative flex h-[4rem] w-[4rem] items-center justify-center rounded-[9999px] border-2 ",a?"bg-[#fff]/20 border-[#fff]":"bg-[#fff]/10 border-[#fff]"),style:{transform:`translateY(${3*(90-o)}px)`,transition:"transform 0.2s ease-out"},children:[e.jsx("div",{className:"h-[1rem] w-[1rem] rounded-[9999px] bg-[#fff]/80"}),e.jsxs("div",{className:"mt-[.5rem] w-[180px] flex-col flex items-center absolute top-[60px] text-[#fff]",children:[e.jsx(j,{size:30}),e.jsxs("p",{style:{fontFamily:u?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:[" ","Tap to start level check"]})]})]}),null!==f&&e.jsx("div",{className:"absolute bottom-[8rem] text-center",children:e.jsx("div",{className:"text-[#fff] text-sm font-medium px-4 py-1.5 bg-black/20 rounded-[9999px] mt-8",style:{fontFamily:u?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:"Leave your phone as is"})}),a&&null===f&&!s&&e.jsx("div",{className:"absolute bottom-[8rem] w-[12rem]",children:e.jsx("div",{className:"h-[.375rem] w-full bg-[#fff]/20 rounded-[9999px] overflow-hidden",children:e.jsx("div",{className:"h-full bg-[#fff]/70 transition-all duration-300 rounded-[9999px]",style:{width:`${l}%`}})})}),null===f&&!s&&e.jsx("div",{className:"absolute bottom-[5rem] text-center",children:e.jsxs("div",{className:r.clsx("text-[1.5rem] font-light",_()),children:[Math.round(o),"°"]})}),null===f&&!s&&e.jsx("div",{className:"absolute bottom-[2rem] text-center max-w-[20rem] mx-auto",children:e.jsx("div",{className:r.clsx("text-[.75rem] opacity-50",_(!0)),style:{fontFamily:u?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:"Place your phone upright against an object. Once stable and within the 80-95° range a countdown will start to move to the scan."})})]})}),N={exports:{}};var F,I=(R||(R=1,F=N,function(e,n){F.exports=n(t)}(0,function(e){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s="./src/react-webcam.tsx")}({"./src/react-webcam.tsx":
1
+ "use strict";var e=require("react/jsx-runtime"),t=require("react"),n=require("./Header-KIq-IIp4.js"),r=require("./enums-BLzZlPIt.js"),o=require("./LoadingScreen-aAtRsi7Q.js"),i=require("video.js");function s(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}require("react-dom");var a=s(t);function l(e){const{sx:t,...n}=e,{systemProps:o,otherProps:i}=(e=>{const t={systemProps:{},otherProps:{}},n=e?.theme?.unstable_sxConfig??r.defaultSxConfig;return Object.keys(e).forEach(r=>{n[r]?t.systemProps[r]=e[r]:t.otherProps[r]=e[r]}),t})(n);let s;return s=Array.isArray(t)?[o,...t]:"function"==typeof t?(...e)=>{const n=t(...e);return r.isPlainObject(n)?{...o,...n}:o}:{...o,...t},{...i,sx:s}}const c=r.generateUtilityClasses("MuiBox",["root"]),u=r.createTheme(),d=function(t={}){const{themeId:n,defaultTheme:o,defaultClassName:i="MuiBox-root",generateClassName:s}=t,c=r.styled$1("div",{shouldForwardProp:e=>"theme"!==e&&"sx"!==e&&"as"!==e})(r.styleFunctionSx);return a.forwardRef(function(t,a){const u=r.useTheme(o),{className:d,component:h="div",...p}=l(t);return e.jsx(c,{as:h,ref:a,className:r.clsx(d,s?s(i):i),theme:n&&u[n]||u,...p})})}({themeId:r.THEME_ID,defaultTheme:u,defaultClassName:c.root,generateClassName:r.ClassNameGenerator.generate});function h(e){return r.generateUtilityClass("MuiDialog",e)}"production"!==process.env.NODE_ENV&&(d.propTypes={children:r.PropTypes.node,component:r.PropTypes.elementType,sx:r.PropTypes.oneOfType([r.PropTypes.arrayOf(r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object,r.PropTypes.bool])),r.PropTypes.func,r.PropTypes.object])});const p=r.generateUtilityClasses("MuiDialog",["root","scrollPaper","scrollBody","container","paper","paperScrollPaper","paperScrollBody","paperWidthFalse","paperWidthXs","paperWidthSm","paperWidthMd","paperWidthLg","paperWidthXl","paperFullWidth","paperFullScreen"]),_=a.createContext({});"production"!==process.env.NODE_ENV&&(_.displayName="DialogContext");const f=r.styled(r.Backdrop,{name:"MuiDialog",slot:"Backdrop",overrides:(e,t)=>t.backdrop})({zIndex:-1}),m=r.styled(r.Modal,{name:"MuiDialog",slot:"Root"})({"@media print":{position:"absolute !important"}}),g=r.styled("div",{name:"MuiDialog",slot:"Container",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.container,t[`scroll${r.capitalize(n.scroll)}`]]}})({height:"100%","@media print":{height:"auto"},outline:0,variants:[{props:{scroll:"paper"},style:{display:"flex",justifyContent:"center",alignItems:"center"}},{props:{scroll:"body"},style:{overflowY:"auto",overflowX:"hidden",textAlign:"center","&::after":{content:'""',display:"inline-block",verticalAlign:"middle",height:"100%",width:"0"}}}]}),y=r.styled(r.Paper,{name:"MuiDialog",slot:"Paper",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.paper,t[`scrollPaper${r.capitalize(n.scroll)}`],t[`paperWidth${r.capitalize(String(n.maxWidth))}`],n.fullWidth&&t.paperFullWidth,n.fullScreen&&t.paperFullScreen]}})(r.memoTheme(({theme:e})=>({margin:32,position:"relative",overflowY:"auto","@media print":{overflowY:"visible",boxShadow:"none"},variants:[{props:{scroll:"paper"},style:{display:"flex",flexDirection:"column",maxHeight:"calc(100% - 64px)"}},{props:{scroll:"body"},style:{display:"inline-block",verticalAlign:"middle",textAlign:"initial"}},{props:({ownerState:e})=>!e.maxWidth,style:{maxWidth:"calc(100% - 64px)"}},{props:{maxWidth:"xs"},style:{maxWidth:"px"===e.breakpoints.unit?Math.max(e.breakpoints.values.xs,444):`max(${e.breakpoints.values.xs}${e.breakpoints.unit}, 444px)`,[`&.${p.paperScrollBody}`]:{[e.breakpoints.down(Math.max(e.breakpoints.values.xs,444)+64)]:{maxWidth:"calc(100% - 64px)"}}}},...Object.keys(e.breakpoints.values).filter(e=>"xs"!==e).map(t=>({props:{maxWidth:t},style:{maxWidth:`${e.breakpoints.values[t]}${e.breakpoints.unit}`,[`&.${p.paperScrollBody}`]:{[e.breakpoints.down(e.breakpoints.values[t]+64)]:{maxWidth:"calc(100% - 64px)"}}}})),{props:({ownerState:e})=>e.fullWidth,style:{width:"calc(100% - 64px)"}},{props:({ownerState:e})=>e.fullScreen,style:{margin:0,width:"100%",maxWidth:"100%",height:"100%",maxHeight:"none",borderRadius:0,[`&.${p.paperScrollBody}`]:{margin:0,maxWidth:"100%"}}}]}))),v=a.forwardRef(function(t,n){const o=r.useDefaultProps({props:t,name:"MuiDialog"}),i=r.useTheme$1(),s={enter:i.transitions.duration.enteringScreen,exit:i.transitions.duration.leavingScreen},{"aria-describedby":l,"aria-labelledby":c,"aria-modal":u=!0,BackdropComponent:d,BackdropProps:p,children:v,className:w,disableEscapeKeyDown:b=!1,fullScreen:S=!1,fullWidth:E=!1,maxWidth:P="sm",onClick:T,onClose:k,open:x,PaperComponent:C=r.Paper,PaperProps:O={},scroll:j="paper",slots:R={},slotProps:A={},TransitionComponent:N=r.Fade,transitionDuration:F=s,TransitionProps:I,...M}=o,U={...o,disableEscapeKeyDown:b,fullScreen:S,fullWidth:E,maxWidth:P,scroll:j},L=(e=>{const{classes:t,scroll:n,maxWidth:o,fullWidth:i,fullScreen:s}=e,a={root:["root"],container:["container",`scroll${r.capitalize(n)}`],paper:["paper",`paperScroll${r.capitalize(n)}`,`paperWidth${r.capitalize(String(o))}`,i&&"paperFullWidth",s&&"paperFullScreen"]};return r.composeClasses(a,h,t)})(U),z=a.useRef(),D=r.useId(c),B=a.useMemo(()=>({titleId:D}),[D]),$={slots:{transition:N,...R},slotProps:{transition:I,paper:O,backdrop:p,...A}},[q,W]=r.useSlot("root",{elementType:m,shouldForwardComponentProp:!0,externalForwardedProps:$,ownerState:U,className:r.clsx(L.root,w),ref:n}),[H,V]=r.useSlot("backdrop",{elementType:f,shouldForwardComponentProp:!0,externalForwardedProps:$,ownerState:U}),[K,Y]=r.useSlot("paper",{elementType:y,shouldForwardComponentProp:!0,externalForwardedProps:$,ownerState:U,className:r.clsx(L.paper,O.className)}),[G,J]=r.useSlot("container",{elementType:g,externalForwardedProps:$,ownerState:U,className:L.container}),[X,Q]=r.useSlot("transition",{elementType:r.Fade,externalForwardedProps:$,ownerState:U,additionalProps:{appear:!0,in:x,timeout:F,role:"presentation"}});return e.jsx(q,{closeAfterTransition:!0,slots:{backdrop:H},slotProps:{backdrop:{transitionDuration:F,as:d,...V}},disableEscapeKeyDown:b,onClose:k,open:x,onClick:e=>{T&&T(e),z.current&&(z.current=null,k&&k(e,"backdropClick"))},...W,...M,children:e.jsx(X,{...Q,children:e.jsx(G,{onMouseDown:e=>{z.current=e.target===e.currentTarget},...J,children:e.jsx(K,{as:C,elevation:24,role:"dialog","aria-describedby":l,"aria-labelledby":D,"aria-modal":u,...Y,children:e.jsx(_.Provider,{value:B,children:v})})})})})});function w(e){return"function"==typeof e?e():e}function b(e,t,n){const o=function(e,t,n){const o=t.getBoundingClientRect(),i=n&&n.getBoundingClientRect(),s=r.ownerWindow(t);let a;if(t.fakeTransform)a=t.fakeTransform;else{const e=s.getComputedStyle(t);a=e.getPropertyValue("-webkit-transform")||e.getPropertyValue("transform")}let l=0,c=0;if(a&&"none"!==a&&"string"==typeof a){const e=a.split("(")[1].split(")")[0].split(",");l=parseInt(e[4],10),c=parseInt(e[5],10)}return"left"===e?i?`translateX(${i.right+l-o.left}px)`:`translateX(${s.innerWidth+l-o.left}px)`:"right"===e?i?`translateX(-${o.right-i.left-l}px)`:`translateX(-${o.left+o.width-l}px)`:"up"===e?i?`translateY(${i.bottom+c-o.top}px)`:`translateY(${s.innerHeight+c-o.top}px)`:i?`translateY(-${o.top-i.top+o.height-c}px)`:`translateY(-${o.top+o.height-c}px)`}(e,t,w(n));o&&(t.style.webkitTransform=o,t.style.transform=o)}"production"!==process.env.NODE_ENV&&(v.propTypes={"aria-describedby":r.PropTypes.string,"aria-labelledby":r.PropTypes.string,"aria-modal":r.PropTypes.oneOfType([r.PropTypes.oneOf(["false","true"]),r.PropTypes.bool]),BackdropComponent:r.PropTypes.elementType,BackdropProps:r.PropTypes.object,children:r.PropTypes.node,classes:r.PropTypes.object,className:r.PropTypes.string,disableEscapeKeyDown:r.PropTypes.bool,fullScreen:r.PropTypes.bool,fullWidth:r.PropTypes.bool,maxWidth:r.PropTypes.oneOfType([r.PropTypes.oneOf(["xs","sm","md","lg","xl",!1]),r.PropTypes.string]),onClick:r.PropTypes.func,onClose:r.PropTypes.func,open:r.PropTypes.bool.isRequired,PaperComponent:r.PropTypes.elementType,PaperProps:r.PropTypes.object,scroll:r.PropTypes.oneOf(["body","paper"]),slotProps:r.PropTypes.shape({backdrop:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),container:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),paper:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),root:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),transition:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object])}),slots:r.PropTypes.shape({backdrop:r.PropTypes.elementType,container:r.PropTypes.elementType,paper:r.PropTypes.elementType,root:r.PropTypes.elementType,transition:r.PropTypes.elementType}),sx:r.PropTypes.oneOfType([r.PropTypes.arrayOf(r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object,r.PropTypes.bool])),r.PropTypes.func,r.PropTypes.object]),TransitionComponent:r.PropTypes.elementType,transitionDuration:r.PropTypes.oneOfType([r.PropTypes.number,r.PropTypes.shape({appear:r.PropTypes.number,enter:r.PropTypes.number,exit:r.PropTypes.number})]),TransitionProps:r.PropTypes.object});const S=a.forwardRef(function(t,n){const o=r.useTheme$1(),i={enter:o.transitions.easing.easeOut,exit:o.transitions.easing.sharp},s={enter:o.transitions.duration.enteringScreen,exit:o.transitions.duration.leavingScreen},{addEndListener:l,appear:c=!0,children:u,container:d,direction:h="down",easing:p=i,in:_,onEnter:f,onEntered:m,onEntering:g,onExit:y,onExited:v,onExiting:w,style:S,timeout:E=s,TransitionComponent:P=r.Transition,...T}=t,k=a.useRef(null),x=r.useForkRef(r.getReactElementRef(u),k,n),C=e=>t=>{e&&(void 0===t?e(k.current):e(k.current,t))},O=C((e,t)=>{b(h,e,d),r.reflow(e),f&&f(e,t)}),j=C((e,t)=>{const n=r.getTransitionProps({timeout:E,style:S,easing:p},{mode:"enter"});e.style.webkitTransition=o.transitions.create("-webkit-transform",{...n}),e.style.transition=o.transitions.create("transform",{...n}),e.style.webkitTransform="none",e.style.transform="none",g&&g(e,t)}),R=C(m),A=C(w),N=C(e=>{const t=r.getTransitionProps({timeout:E,style:S,easing:p},{mode:"exit"});e.style.webkitTransition=o.transitions.create("-webkit-transform",t),e.style.transition=o.transitions.create("transform",t),b(h,e,d),y&&y(e)}),F=C(e=>{e.style.webkitTransition="",e.style.transition="",v&&v(e)}),I=a.useCallback(()=>{k.current&&b(h,k.current,d)},[h,d]);return a.useEffect(()=>{if(_||"down"===h||"right"===h)return;const e=r.debounce(()=>{k.current&&b(h,k.current,d)}),t=r.ownerWindow(k.current);return t.addEventListener("resize",e),()=>{e.clear(),t.removeEventListener("resize",e)}},[h,_,d]),a.useEffect(()=>{_||I()},[_,I]),e.jsx(P,{nodeRef:k,onEnter:O,onEntered:R,onEntering:j,onExit:N,onExited:F,onExiting:A,addEndListener:e=>{l&&l(k.current,e)},appear:c,in:_,timeout:E,...T,children:(e,{ownerState:t,...n})=>a.cloneElement(u,{ref:x,style:{visibility:"exited"!==e||_?void 0:"hidden",...S,...u.props.style},...n})})});function E(e){return r.generateUtilityClass("MuiDrawer",e)}"production"!==process.env.NODE_ENV&&(S.propTypes={addEndListener:r.PropTypes.func,appear:r.PropTypes.bool,children:r.elementAcceptingRef.isRequired,container:r.chainPropTypes(r.PropTypes.oneOfType([r.HTMLElementType,r.PropTypes.func]),e=>{if(e.open){const t=w(e.container);if(t&&1===t.nodeType){const e=t.getBoundingClientRect();if("test"!==process.env.NODE_ENV&&0===e.top&&0===e.left&&0===e.right&&0===e.bottom)return new Error(["MUI: The `container` prop provided to the component is invalid.","The anchor element should be part of the document layout.","Make sure the element is present in the document or that it's not display none."].join("\n"))}else if(!t||"function"!=typeof t.getBoundingClientRect||null!=t.contextElement&&1!==t.contextElement.nodeType)return new Error(["MUI: The `container` prop provided to the component is invalid.","It should be an HTML element instance."].join("\n"))}return null}),direction:r.PropTypes.oneOf(["down","left","right","up"]),easing:r.PropTypes.oneOfType([r.PropTypes.shape({enter:r.PropTypes.string,exit:r.PropTypes.string}),r.PropTypes.string]),in:r.PropTypes.bool,onEnter:r.PropTypes.func,onEntered:r.PropTypes.func,onEntering:r.PropTypes.func,onExit:r.PropTypes.func,onExited:r.PropTypes.func,onExiting:r.PropTypes.func,style:r.PropTypes.object,timeout:r.PropTypes.oneOfType([r.PropTypes.number,r.PropTypes.shape({appear:r.PropTypes.number,enter:r.PropTypes.number,exit:r.PropTypes.number})])}),r.generateUtilityClasses("MuiDrawer",["root","docked","paper","anchorLeft","anchorRight","anchorTop","anchorBottom","paperAnchorLeft","paperAnchorRight","paperAnchorTop","paperAnchorBottom","paperAnchorDockedLeft","paperAnchorDockedRight","paperAnchorDockedTop","paperAnchorDockedBottom","modal"]);const P=(e,t)=>{const{ownerState:n}=e;return[t.root,("permanent"===n.variant||"persistent"===n.variant)&&t.docked,t.modal]},T=r.styled(r.Modal,{name:"MuiDrawer",slot:"Root",overridesResolver:P})(r.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.drawer}))),k=r.styled("div",{shouldForwardProp:r.rootShouldForwardProp,name:"MuiDrawer",slot:"Docked",skipVariantsResolver:!1,overridesResolver:P})({flex:"0 0 auto"}),x=r.styled(r.Paper,{name:"MuiDrawer",slot:"Paper",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.paper,t[`paperAnchor${r.capitalize(n.anchor)}`],"temporary"!==n.variant&&t[`paperAnchorDocked${r.capitalize(n.anchor)}`]]}})(r.memoTheme(({theme:e})=>({overflowY:"auto",display:"flex",flexDirection:"column",height:"100%",flex:"1 0 auto",zIndex:(e.vars||e).zIndex.drawer,WebkitOverflowScrolling:"touch",position:"fixed",top:0,outline:0,variants:[{props:{anchor:"left"},style:{left:0}},{props:{anchor:"top"},style:{top:0,left:0,right:0,height:"auto",maxHeight:"100%"}},{props:{anchor:"right"},style:{right:0}},{props:{anchor:"bottom"},style:{top:"auto",left:0,bottom:0,right:0,height:"auto",maxHeight:"100%"}},{props:({ownerState:e})=>"left"===e.anchor&&"temporary"!==e.variant,style:{borderRight:`1px solid ${(e.vars||e).palette.divider}`}},{props:({ownerState:e})=>"top"===e.anchor&&"temporary"!==e.variant,style:{borderBottom:`1px solid ${(e.vars||e).palette.divider}`}},{props:({ownerState:e})=>"right"===e.anchor&&"temporary"!==e.variant,style:{borderLeft:`1px solid ${(e.vars||e).palette.divider}`}},{props:({ownerState:e})=>"bottom"===e.anchor&&"temporary"!==e.variant,style:{borderTop:`1px solid ${(e.vars||e).palette.divider}`}}]}))),C={left:"right",right:"left",top:"down",bottom:"up"};const O=a.forwardRef(function(t,n){const o=r.useDefaultProps({props:t,name:"MuiDrawer"}),i=r.useTheme$1(),s=r.useRtl(),l={enter:i.transitions.duration.enteringScreen,exit:i.transitions.duration.leavingScreen},{anchor:c="left",BackdropProps:u,children:d,className:h,elevation:p=16,hideBackdrop:_=!1,ModalProps:{BackdropProps:f,...m}={},onClose:g,open:y=!1,PaperProps:v={},SlideProps:w,TransitionComponent:b,transitionDuration:P=l,variant:O="temporary",slots:j={},slotProps:R={},...A}=o,N=a.useRef(!1);a.useEffect(()=>{N.current=!0},[]);const F=function({direction:e},t){return"rtl"===e&&function(e){return["left","right"].includes(e)}(t)?C[t]:t}({direction:s?"rtl":"ltr"},c),I=c,M={...o,anchor:I,elevation:p,open:y,variant:O,...A},U=(e=>{const{classes:t,anchor:n,variant:o}=e,i={root:["root",`anchor${r.capitalize(n)}`],docked:[("permanent"===o||"persistent"===o)&&"docked"],modal:["modal"],paper:["paper",`paperAnchor${r.capitalize(n)}`,"temporary"!==o&&`paperAnchorDocked${r.capitalize(n)}`]};return r.composeClasses(i,E,t)})(M),L={slots:{transition:b,...j},slotProps:{paper:v,transition:w,...R,backdrop:r.mergeSlotProps$1(R.backdrop||{...u,...f},{transitionDuration:P})}},[z,D]=r.useSlot("root",{ref:n,elementType:T,className:r.clsx(U.root,U.modal,h),shouldForwardComponentProp:!0,ownerState:M,externalForwardedProps:{...L,...A,...m},additionalProps:{open:y,onClose:g,hideBackdrop:_,slots:{backdrop:L.slots.backdrop},slotProps:{backdrop:L.slotProps.backdrop}}}),[B,$]=r.useSlot("paper",{elementType:x,shouldForwardComponentProp:!0,className:r.clsx(U.paper,v.className),ownerState:M,externalForwardedProps:L,additionalProps:{elevation:"temporary"===O?p:0,square:!0,..."temporary"===O&&{role:"dialog","aria-modal":"true"}}}),[q,W]=r.useSlot("docked",{elementType:k,ref:n,className:r.clsx(U.root,U.docked,h),ownerState:M,externalForwardedProps:L,additionalProps:A}),[H,V]=r.useSlot("transition",{elementType:S,ownerState:M,externalForwardedProps:L,additionalProps:{in:y,direction:C[F],timeout:P,appear:N.current}}),K=e.jsx(B,{...$,children:d});if("permanent"===O)return e.jsx(q,{...W,children:K});const Y=e.jsx(H,{...V,children:K});return"persistent"===O?e.jsx(q,{...W,children:Y}):e.jsx(z,{...D,children:Y})});"production"!==process.env.NODE_ENV&&(O.propTypes={anchor:r.PropTypes.oneOf(["bottom","left","right","top"]),BackdropProps:r.PropTypes.object,children:r.PropTypes.node,classes:r.PropTypes.object,className:r.PropTypes.string,elevation:r.integerPropType,hideBackdrop:r.PropTypes.bool,ModalProps:r.PropTypes.object,onClose:r.PropTypes.func,open:r.PropTypes.bool,PaperProps:r.PropTypes.object,SlideProps:r.PropTypes.object,slotProps:r.PropTypes.shape({backdrop:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),docked:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),paper:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),root:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object]),transition:r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object])}),slots:r.PropTypes.shape({backdrop:r.PropTypes.elementType,docked:r.PropTypes.elementType,paper:r.PropTypes.elementType,root:r.PropTypes.elementType,transition:r.PropTypes.elementType}),sx:r.PropTypes.oneOfType([r.PropTypes.arrayOf(r.PropTypes.oneOfType([r.PropTypes.func,r.PropTypes.object,r.PropTypes.bool])),r.PropTypes.func,r.PropTypes.object]),transitionDuration:r.PropTypes.oneOfType([r.PropTypes.number,r.PropTypes.shape({appear:r.PropTypes.number,enter:r.PropTypes.number,exit:r.PropTypes.number})]),variant:r.PropTypes.oneOf(["permanent","persistent","temporary"])});var j=t.memo(function({size:t=16}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 25 25",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M22.6968 14.6968C22.6968 16.8185 21.8539 18.8533 20.3536 20.3536C18.8533 21.8539 16.8185 22.6968 14.6968 22.6968",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M18.6968 11.6968V10.6968C18.6968 10.1663 18.4861 9.65764 18.111 9.28256C17.7359 8.90749 17.2272 8.69678 16.6968 8.69678C16.1663 8.69678 15.6576 8.90749 15.2826 9.28256C14.9075 9.65764 14.6968 10.1663 14.6968 10.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M14.6968 10.6968V9.69678C14.6968 9.16634 14.4861 8.65764 14.111 8.28256C13.7359 7.90749 13.2272 7.69678 12.6968 7.69678C12.1663 7.69678 11.6576 7.90749 11.2826 8.28256C10.9075 8.65764 10.6968 9.16634 10.6968 9.69678V10.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M10.6968 10.1968V4.69678C10.6968 4.16634 10.4861 3.65764 10.111 3.28256C9.73592 2.90749 9.22721 2.69678 8.69678 2.69678C8.16634 2.69678 7.65764 2.90749 7.28256 3.28256C6.90749 3.65764 6.69678 4.16634 6.69678 4.69678V14.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M18.6969 11.6968C18.6969 11.1663 18.9076 10.6576 19.2827 10.2826C19.6577 9.90749 20.1664 9.69678 20.6969 9.69678C21.2273 9.69678 21.736 9.90749 22.1111 10.2826C22.4862 10.6576 22.6969 11.1663 22.6969 11.6968V14.6968C22.6969 16.8185 21.854 18.8533 20.3537 20.3536C18.8534 21.8539 16.8186 22.6968 14.6969 22.6968H12.6969C9.89688 22.6968 8.19688 21.8368 6.70688 20.3568L3.10688 16.7568C2.76282 16.3757 2.57847 15.8769 2.592 15.3637C2.60554 14.8505 2.81593 14.3621 3.1796 13.9997C3.54327 13.6373 4.03238 13.4287 4.54565 13.417C5.05892 13.4053 5.55704 13.5914 5.93688 13.9368L7.69688 15.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})});var R,A=t.memo(function({angle:o,countdown:i,isScanning:s,isInTargetRange:a,stabilityScore:l,children:c,config:u}){const d=t.useCallback(()=>o<80?Math.max(0,Math.min(100,10*(o-60))):o>95?Math.max(0,Math.min(100,10*(105-o))):100,[o]),h=t.useMemo(()=>{if(s)return u?.style?.base?.brandColor||"#4f46e5";const e=d();if(0===e)return"#ffffff";if(100===e)return u?.style?.base?.brandColor||"#8b5cf6";return`rgb(${Math.round(255-e/100*116)}, ${Math.round(255-e/100*163)}, ${Math.round(255-e/100*9)})`},[s,d]),p=t.useCallback((e,t)=>t>70?e?"text-[#fff]/70":"text-[#fff]":e?"text-[#fff]/40":"text-[#000]/70",[]),_=t.useCallback((e=!1)=>{const t=d();return s?"text-[#fff]":p(e,t)},[s,d]),f=i;function m(){document.documentElement.style.setProperty("--real-vh",window.innerHeight+"px")}return m(),window.addEventListener("resize",m),e.jsxs("div",{className:"flex w-screen flex-col items-center h-[var(--real-vh)] overflow-hidden touch-none justify-center transition-all duration-300 max-w-[28rem] mx-auto",style:{backgroundColor:h},children:[e.jsx("div",{className:"flex justify-start fixed top-[.5rem] max-w-[28rem] mx-auto w-full px-[1rem]",children:e.jsx("div",{className:"flex justify-start ",children:e.jsx(n.Header,{noTitle:!0,resolvedConfig:u})})}),null!==f?e.jsx("div",{className:"relative flex h-[6rem] w-[6rem] items-center justify-center rounded-[9999px] border-2 border-[#fff] bg-[#fff]/20 transition-all duration-300",children:e.jsx("div",{className:"text-[3rem] font-bold text-[#fff]",style:{fontFamily:u?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:f})}):s?e.jsxs("div",{className:"relative flex flex-col items-center justify-center",children:[e.jsx("div",{className:"relative flex h-16 w-16 items-center justify-center rounded-[9999px] border-2 bg-[#fff]/30 border-[#fff]",children:e.jsx("div",{className:"h-4 w-4 rounded-[9999px] animate-pulse bg-[#fff]/80"})}),c]}):e.jsxs("div",{className:r.clsx("relative flex h-[4rem] w-[4rem] items-center justify-center rounded-[9999px] border-2 ",a?"bg-[#fff]/20 border-[#fff]":"bg-[#fff]/10 border-[#fff]"),style:{transform:`translateY(${3*(90-o)}px)`,transition:"transform 0.2s ease-out"},children:[e.jsx("div",{className:"h-[1rem] w-[1rem] rounded-[9999px] bg-[#fff]/80"}),e.jsxs("div",{className:"mt-[.5rem] w-[180px] flex-col flex items-center absolute top-[60px] text-[#fff]",children:[e.jsx(j,{size:30}),e.jsxs("p",{style:{fontFamily:u?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:[" ","Tap to start level check"]})]})]}),null!==f&&e.jsx("div",{className:"absolute bottom-[8rem] text-center",children:e.jsx("div",{className:"text-[#fff] text-sm font-medium px-4 py-1.5 bg-black/20 rounded-[9999px] mt-8",style:{fontFamily:u?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:"Leave your phone as is"})}),a&&null===f&&!s&&e.jsx("div",{className:"absolute bottom-[8rem] w-[12rem]",children:e.jsx("div",{className:"h-[.375rem] w-full bg-[#fff]/20 rounded-[9999px] overflow-hidden",children:e.jsx("div",{className:"h-full bg-[#fff]/70 transition-all duration-300 rounded-[9999px]",style:{width:`${l}%`}})})}),null===f&&!s&&e.jsx("div",{className:"absolute bottom-[5rem] text-center",children:e.jsxs("div",{className:r.clsx("text-[1.5rem] font-light",_()),children:[Math.round(o),"°"]})}),null===f&&!s&&e.jsx("div",{className:"absolute bottom-[2rem] text-center max-w-[20rem] mx-auto",children:e.jsx("div",{className:r.clsx("text-[.75rem] opacity-50",_(!0)),style:{fontFamily:u?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:"Place your phone upright against an object. Once stable and within the 80-95° range a countdown will start to move to the scan."})})]})}),N={exports:{}};var F,I=(R||(R=1,F=N,function(e,n){F.exports=n(t)}(0,function(e){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s="./src/react-webcam.tsx")}({"./src/react-webcam.tsx":
2
2
  /*!******************************!*\
3
3
  !*** ./src/react-webcam.tsx ***!
4
4
  \******************************/
@@ -16,5 +16,5 @@
16
16
  *
17
17
  * @param phrase that needs interpolation, with placeholders
18
18
  * @param options with values that will be used to replace placeholders
19
- */function Tr(e,t){const n=/\$/g;let r=[e];if(null==t)return r;for(const e of Object.keys(t))if("_"!==e){let o=t[e];"string"==typeof o&&(o=n[Symbol.replace](o,"$$$$")),r=Pr(r,new RegExp(`%\\{${e}\\}`,"g"),o)}return r}const kr=e=>{throw new Error(`missing string: ${e}`)};var xr,Cr,Or=Er("onMissingKey"),jr=Er("apply");class Rr{constructor(e,t){let{onMissingKey:n=kr}=void 0===t?{}:t;Object.defineProperty(this,jr,{value:Ar}),Object.defineProperty(this,Or,{writable:!0,value:void 0}),this.locale={strings:{},pluralize:e=>1===e?0:1},Array.isArray(e)?e.forEach(br(this,jr)[jr],this):br(this,jr)[jr](e),br(this,Or)[Or]=n}translate(e,t){return this.translateArray(e,t).join("")}translateArray(e,t){let n=this.locale.strings[e];null==n&&(br(this,Or)[Or](e),n=e);if("object"==typeof n){if(t&&void 0!==t.smart_count){return Tr(n[this.locale.pluralize(t.smart_count)],t)}throw new Error("Attempted to use a string with plural forms, but no value was given for %{smart_count}")}if("string"!=typeof n)throw new Error("string was not a string");return Tr(n,t)}}function Ar(e){if(null==e||!e.strings)return;const t=this.locale;Object.assign(this.locale,{strings:{...t.strings,...e.strings},pluralize:e.pluralize||t.pluralize})}var Nr=(Cr||(Cr=1,xr=function(){var e={},t=e._fns={};return e.emit=function(e,n,r,o,i,s,a){var l=function(e){for(var n=t[e]?t[e]:[],r=e.indexOf(":"),o=-1===r?[e]:[e.substring(0,r),e.substring(r+1)],i=Object.keys(t),s=0,a=i.length;s<a;s++){var l=i[s];if("*"===l&&(n=n.concat(t[l])),2===o.length&&o[0]===l){n=n.concat(t[l]);break}}return n}(e);l.length&&function(e,t,n){for(var r=0,o=t.length;r<o&&t[r];r++)t[r].event=e,t[r].apply(t[r],n)}(e,l,[n,r,o,i,s,a])},e.on=function(e,n){t[e]||(t[e]=[]),t[e].push(n)},e.once=function(t,n){this.on(t,function r(){n.apply(this,arguments),e.off(t,r)})},e.off=function(e,t){var n=[];if(e&&t)for(var r=this._fns[e],o=0,i=r?r.length:0;o<i;o++)r[o]!==t&&n.push(r[o]);n.length?this._fns[e]=n:delete this._fns[e]},e}),xr),Fr=r.getDefaultExportFromCjs(Nr);var Ir,Mr,Ur,Lr,zr,Dr,Br,$r,qr,Wr,Hr,Vr,Kr,Yr,Gr,Jr,Xr,Qr,Zr,eo,to,no,ro,oo,io,so,ao,lo,co,uo;function ho(){if(Mr)return Ir;return Mr=1,Ir=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},Ir}function po(){if(Dr)return zr;Dr=1;var e=function(){if(Lr)return Ur;Lr=1;var e="object"==typeof r.commonjsGlobal&&r.commonjsGlobal&&r.commonjsGlobal.Object===Object&&r.commonjsGlobal;return Ur=e}(),t="object"==typeof self&&self&&self.Object===Object&&self,n=e||t||Function("return this")();return zr=n}function _o(){if(Vr)return Hr;Vr=1;var e=function(){if(Wr)return qr;Wr=1;var e=/\s/;return qr=function(t){for(var n=t.length;n--&&e.test(t.charAt(n)););return n}}(),t=/^\s+/;return Hr=function(n){return n?n.slice(0,e(n)+1).replace(t,""):n}}function fo(){if(Yr)return Kr;Yr=1;var e=po().Symbol;return Kr=e}function mo(){if(eo)return Zr;eo=1;var e=fo(),t=function(){if(Jr)return Gr;Jr=1;var e=fo(),t=Object.prototype,n=t.hasOwnProperty,r=t.toString,o=e?e.toStringTag:void 0;return Gr=function(e){var t=n.call(e,o),i=e[o];try{e[o]=void 0;var s=!0}catch(e){}var a=r.call(e);return s&&(t?e[o]=i:delete e[o]),a},Gr}(),n=function(){if(Qr)return Xr;Qr=1;var e=Object.prototype.toString;return Xr=function(t){return e.call(t)},Xr}(),r=e?e.toStringTag:void 0;return Zr=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":r&&r in Object(e)?t(e):n(e)},Zr}function go(){if(oo)return ro;oo=1;var e=mo(),t=(no||(no=1,to=function(e){return null!=e&&"object"==typeof e}),to);return ro=function(n){return"symbol"==typeof n||t(n)&&"[object Symbol]"==e(n)},ro}function yo(){if(lo)return ao;lo=1;var e=ho(),t=function(){if($r)return Br;$r=1;var e=po();return Br=function(){return e.Date.now()}}(),n=function(){if(so)return io;so=1;var e=_o(),t=ho(),n=go(),r=/^[-+]0x[0-9a-f]+$/i,o=/^0b[01]+$/i,i=/^0o[0-7]+$/i,s=parseInt;return io=function(a){if("number"==typeof a)return a;if(n(a))return NaN;if(t(a)){var l="function"==typeof a.valueOf?a.valueOf():a;a=t(l)?l+"":l}if("string"!=typeof a)return 0===a?a:+a;a=e(a);var c=o.test(a);return c||i.test(a)?s(a.slice(2),c?2:8):r.test(a)?NaN:+a},io}(),r=Math.max,o=Math.min;return ao=function(i,s,a){var l,c,u,d,h,p,_=0,f=!1,m=!1,g=!0;if("function"!=typeof i)throw new TypeError("Expected a function");function y(e){var t=l,n=c;return l=c=void 0,_=e,d=i.apply(n,t)}function v(e){var t=e-p;return void 0===p||t>=s||t<0||m&&e-_>=u}function w(){var e=t();if(v(e))return b(e);h=setTimeout(w,function(e){var t=s-(e-p);return m?o(t,u-(e-_)):t}(e))}function b(e){return h=void 0,g&&l?y(e):(l=c=void 0,d)}function S(){var e=t(),n=v(e);if(l=arguments,c=this,p=e,n){if(void 0===h)return function(e){return _=e,h=setTimeout(w,s),f?y(e):d}(p);if(m)return clearTimeout(h),h=setTimeout(w,s),y(p)}return void 0===h&&(h=setTimeout(w,s)),d}return s=n(s)||0,e(a)&&(f=!!a.leading,u=(m="maxWait"in a)?r(n(a.maxWait)||0,s):u,g="trailing"in a?!!a.trailing:g),S.cancel=function(){void 0!==h&&clearTimeout(h),_=0,l=p=c=h=void 0},S.flush=function(){return void 0===h?d:b(t())},S},ao}var vo=function(){if(uo)return co;uo=1;var e=yo(),t=ho();return co=function(n,r,o){var i=!0,s=!0;if("function"!=typeof n)throw new TypeError("Expected a function");return t(o)&&(i="leading"in o?!!o.leading:i,s="trailing"in o?!!o.trailing:s),e(n,r,{leading:i,maxWait:r,trailing:s})}}(),wo=r.getDefaultExportFromCjs(vo);function bo(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var So=0;function Eo(e){return"__private_"+So+++"_"+e}var Po=Eo("callbacks"),To=Eo("publish");class ko{constructor(){Object.defineProperty(this,To,{value:xo}),this.state={},Object.defineProperty(this,Po,{writable:!0,value:new Set})}getState(){return this.state}setState(e){const t={...this.state},n={...this.state,...e};this.state=n,bo(this,To)[To](t,n,e)}subscribe(e){return bo(this,Po)[Po].add(e),()=>{bo(this,Po)[Po].delete(e)}}}function xo(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];bo(this,Po)[Po].forEach(e=>{e(...t)})}function Co(e){const t=e.lastIndexOf(".");return-1===t||t===e.length-1?{name:e,extension:void 0}:{name:e.slice(0,t),extension:e.slice(t+1)}}ko.VERSION="3.2.2";var Oo={__proto__:null,md:"text/markdown",markdown:"text/markdown",mp4:"video/mp4",mp3:"audio/mp3",svg:"image/svg+xml",jpg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",heic:"image/heic",heif:"image/heif",yaml:"text/yaml",yml:"text/yaml",csv:"text/csv",tsv:"text/tab-separated-values",tab:"text/tab-separated-values",avi:"video/x-msvideo",mks:"video/x-matroska",mkv:"video/x-matroska",mov:"video/quicktime",dicom:"application/dicom",doc:"application/msword",docm:"application/vnd.ms-word.document.macroenabled.12",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",dot:"application/msword",dotm:"application/vnd.ms-word.template.macroenabled.12",dotx:"application/vnd.openxmlformats-officedocument.wordprocessingml.template",xla:"application/vnd.ms-excel",xlam:"application/vnd.ms-excel.addin.macroenabled.12",xlc:"application/vnd.ms-excel",xlf:"application/x-xliff+xml",xlm:"application/vnd.ms-excel",xls:"application/vnd.ms-excel",xlsb:"application/vnd.ms-excel.sheet.binary.macroenabled.12",xlsm:"application/vnd.ms-excel.sheet.macroenabled.12",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xlt:"application/vnd.ms-excel",xltm:"application/vnd.ms-excel.template.macroenabled.12",xltx:"application/vnd.openxmlformats-officedocument.spreadsheetml.template",xlw:"application/vnd.ms-excel",txt:"text/plain",text:"text/plain",conf:"text/plain",log:"text/plain",pdf:"application/pdf",zip:"application/zip","7z":"application/x-7z-compressed",rar:"application/x-rar-compressed",tar:"application/x-tar",gz:"application/gzip",dmg:"application/x-apple-diskimage"};function jo(e){var t;if(e.type)return e.type;const n=e.name?null==(t=Co(e.name).extension)?void 0:t.toLowerCase():null;return n&&n in Oo?Oo[n]:"application/octet-stream"}function Ro(e){let t="";return e.replace(/[^A-Z0-9]/gi,e=>(t+=`-${function(e){return e.charCodeAt(0).toString(32)}(e)}`,"/"))+t}function Ao(e,t){if(function(e){return!(!e.isRemote||!e.remote)&&new Set(["box","dropbox","drive","facebook","unsplash"]).has(e.remote.provider)}(e))return e.id;const n=jo(e);return function(e,t){let n=t||"uppy";return"string"==typeof e.name&&(n+=`-${Ro(e.name.toLowerCase())}`),void 0!==e.type&&(n+=`-${e.type}`),e.meta&&"string"==typeof e.meta.relativePath&&(n+=`-${Ro(e.meta.relativePath.toLowerCase())}`),void 0!==e.data.size&&(n+=`-${e.data.size}`),void 0!==e.data.lastModified&&(n+=`-${e.data.lastModified}`),n}({...e,type:n},t)}function No(e){if(null==e&&"undefined"!=typeof navigator&&(e=navigator.userAgent),!e)return!0;const t=/Edge\/(\d+\.\d+)/.exec(e);if(!t)return!0;const n=t[1].split(".",2),r=parseInt(n[0],10),o=parseInt(n[1],10);return r<15||15===r&&o<15063||(r>18||18===r&&o>=18218)}function Fo(e){return e<10?`0${e}`:e.toString()}function Io(){const e=new Date;return`${Fo(e.getHours())}:${Fo(e.getMinutes())}:${Fo(e.getSeconds())}`}const Mo={debug:()=>{},warn:()=>{},error:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return console.error(`[Uppy] [${Io()}]`,...t)}},Uo={debug:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return console.debug(`[Uppy] [${Io()}]`,...t)},warn:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return console.warn(`[Uppy] [${Io()}]`,...t)},error:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return console.error(`[Uppy] [${Io()}]`,...t)}};var Lo,zo;var Do,Bo,$o,qo,Wo=(zo||(zo=1,Lo=function(e){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("Expected a number, got "+typeof e);const t=e<0;let n=Math.abs(e);if(t&&(n=-n),0===n)return"0 B";const r=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],o=Math.min(Math.floor(Math.log(n)/Math.log(1024)),r.length-1),i=Number(n/1024**o),s=r[o];return`${i>=10||i%1==0?Math.round(i):i.toFixed(1)} ${s}`}),Lo),Ho=r.getDefaultExportFromCjs(Wo);function Vo(){if(Bo)return Do;function e(e,t){this.text=e=e||"",this.hasWild=~e.indexOf("*"),this.separator=t,this.parts=e.split(t)}return Bo=1,e.prototype.match=function(e){var t,n,r=!0,o=this.parts,i=o.length;if("string"==typeof e||e instanceof String)if(this.hasWild||this.text==e){for(n=(e||"").split(this.separator),t=0;r&&t<i;t++)"*"!==o[t]&&(r=t<n.length&&o[t]===n[t]);r=r&&n}else r=!1;else if("function"==typeof e.splice)for(r=[],t=e.length;t--;)this.match(e[t])&&(r[r.length]=e[t]);else if("object"==typeof e)for(var s in r={},e)this.match(s)&&(r[s]=e[s]);return r},Do=function(t,n,r){var o=new e(t,r||/[\/\.]/);return void 0!==n?o.match(n):o},Do}var Ko=function(){if(qo)return $o;qo=1;var e=Vo(),t=/[\/\+\.]/;return $o=function(n,r){function o(r){var o=e(r,n,t);return o&&o.length>=2}return r?o(r.split(";")[0]):o},$o}(),Yo=r.getDefaultExportFromCjs(Ko);const Go={maxFileSize:null,minFileSize:null,maxTotalFileSize:null,maxNumberOfFiles:null,minNumberOfFiles:null,allowedFileTypes:null,requiredMetaFields:[]};class Jo extends Error{constructor(e,t){var n;super(e),this.isRestriction=!0,this.isUserFacing=null==(n=null==t?void 0:t.isUserFacing)||n,null!=t&&t.file&&(this.file=t.file)}}class Xo{constructor(e,t){this.getI18n=t,this.getOpts=()=>{var t;const n=e();if(null!=(null==(t=n.restrictions)?void 0:t.allowedFileTypes)&&!Array.isArray(n.restrictions.allowedFileTypes))throw new TypeError("`restrictions.allowedFileTypes` must be an array");return n}}validateAggregateRestrictions(e,t){const{maxTotalFileSize:n,maxNumberOfFiles:r}=this.getOpts().restrictions;if(r){if(e.filter(e=>!e.isGhost).length+t.length>r)throw new Jo(`${this.getI18n()("youCanOnlyUploadX",{smart_count:r})}`)}if(n){const r=[...e,...t].reduce((e,t)=>{var n;return e+(null!=(n=t.size)?n:0)},0);if(r>n)throw new Jo(this.getI18n()("aggregateExceedsSize",{sizeAllowed:Ho(n),size:Ho(r)}))}}validateSingleFile(e){const{maxFileSize:t,minFileSize:n,allowedFileTypes:r}=this.getOpts().restrictions;if(r){if(!r.some(t=>t.includes("/")?!!e.type&&Yo(e.type.replace(/;.*?$/,""),t):!("."!==t[0]||!e.extension)&&e.extension.toLowerCase()===t.slice(1).toLowerCase())){const t=r.join(", ");throw new Jo(this.getI18n()("youCanOnlyUploadFileTypes",{types:t}),{file:e})}}if(t&&null!=e.size&&e.size>t)throw new Jo(this.getI18n()("exceedsSize",{size:Ho(t),file:e.name}),{file:e});if(n&&null!=e.size&&e.size<n)throw new Jo(this.getI18n()("inferiorSize",{size:Ho(n)}),{file:e})}validate(e,t){t.forEach(e=>{this.validateSingleFile(e)}),this.validateAggregateRestrictions(e,t)}validateMinNumberOfFiles(e){const{minNumberOfFiles:t}=this.getOpts().restrictions;if(t&&Object.keys(e).length<t)throw new Jo(this.getI18n()("youHaveToAtLeastSelectX",{smart_count:t}))}getMissingRequiredMetaFields(e){const t=new Jo(this.getI18n()("missingRequiredMetaFieldOnFile",{fileName:e.name})),{requiredMetaFields:n}=this.getOpts().restrictions,r=[];for(const t of n)Object.hasOwn(e.meta,t)&&""!==e.meta[t]||r.push(t);return{missingFields:r,error:t}}}var Qo={strings:{addBulkFilesFailed:{0:"Failed to add %{smart_count} file due to an internal error",1:"Failed to add %{smart_count} files due to internal errors"},youCanOnlyUploadX:{0:"You can only upload %{smart_count} file",1:"You can only upload %{smart_count} files"},youHaveToAtLeastSelectX:{0:"You have to select at least %{smart_count} file",1:"You have to select at least %{smart_count} files"},aggregateExceedsSize:"You selected %{size} of files, but maximum allowed size is %{sizeAllowed}",exceedsSize:"%{file} exceeds maximum allowed size of %{size}",missingRequiredMetaField:"Missing required meta fields",missingRequiredMetaFieldOnFile:"Missing required meta fields in %{fileName}",inferiorSize:"This file is smaller than the allowed size of %{size}",youCanOnlyUploadFileTypes:"You can only upload: %{types}",noMoreFilesAllowed:"Cannot add more files",noDuplicates:"Cannot add the duplicate file '%{fileName}', it already exists",companionError:"Connection with Companion failed",authAborted:"Authentication aborted",companionUnauthorizeHint:"To unauthorize to your %{provider} account, please go to %{url}",failedToUpload:"Failed to upload %{file}",noInternetConnection:"No Internet connection",connectedToInternet:"Connected to the Internet",noFilesFound:"You have no files or folders here",noSearchResults:"Unfortunately, there are no results for this search",selectX:{0:"Select %{smart_count}",1:"Select %{smart_count}"},allFilesFromFolderNamed:"All files from folder %{name}",openFolderNamed:"Open folder %{name}",cancel:"Cancel",logOut:"Log out",filter:"Filter",resetFilter:"Reset filter",loading:"Loading...",loadedXFiles:"Loaded %{numFiles} files",authenticateWithTitle:"Please authenticate with %{pluginName} to select files",authenticateWith:"Connect to %{pluginName}",signInWithGoogle:"Sign in with Google",searchImages:"Search for images",enterTextToSearch:"Enter text to search for images",search:"Search",resetSearch:"Reset search",emptyFolderAdded:"No files were added from empty folder",addedNumFiles:"Added %{numFiles} file(s)",folderAlreadyAdded:'The folder "%{folder}" was already added',folderAdded:{0:"Added %{smart_count} file from %{folder}",1:"Added %{smart_count} files from %{folder}"},additionalRestrictionsFailed:"%{count} additional restrictions were not fulfilled",unnamed:"Unnamed"}};let Zo,ei;function ti(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var ni=0;function ri(e){return"__private_"+ni+++"_"+e}const oi={totalProgress:0,allowNewUpload:!0,error:null,recoveredState:null};var ii=ri("plugins"),si=ri("restricter"),ai=ri("storeUnsubscribe"),li=ri("emitter"),ci=ri("preProcessors"),ui=ri("uploaders"),di=ri("postProcessors"),hi=ri("informAndEmit"),pi=ri("checkRequiredMetaFieldsOnFile"),_i=ri("checkRequiredMetaFields"),fi=ri("assertNewUploadAllowed"),mi=ri("transformFile"),gi=ri("startIfAutoProceed"),yi=ri("checkAndUpdateFileState"),vi=ri("addListeners"),wi=ri("updateOnlineStatus"),bi=ri("requestClientById"),Si=ri("createUpload"),Ei=ri("getUpload"),Pi=ri("removeUpload"),Ti=ri("runUpload");Zo=Symbol.for("uppy test: getPlugins"),ei=Symbol.for("uppy test: createUpload");class ki{constructor(e){Object.defineProperty(this,Ti,{value:Li}),Object.defineProperty(this,Pi,{value:Ui}),Object.defineProperty(this,Ei,{value:Mi}),Object.defineProperty(this,Si,{value:Ii}),Object.defineProperty(this,vi,{value:Fi}),Object.defineProperty(this,yi,{value:Ni}),Object.defineProperty(this,gi,{value:Ai}),Object.defineProperty(this,mi,{value:Ri}),Object.defineProperty(this,fi,{value:ji}),Object.defineProperty(this,_i,{value:Oi}),Object.defineProperty(this,pi,{value:Ci}),Object.defineProperty(this,hi,{value:xi}),Object.defineProperty(this,ii,{writable:!0,value:Object.create(null)}),Object.defineProperty(this,si,{writable:!0,value:void 0}),Object.defineProperty(this,ai,{writable:!0,value:void 0}),Object.defineProperty(this,li,{writable:!0,value:Fr()}),Object.defineProperty(this,ci,{writable:!0,value:new Set}),Object.defineProperty(this,ui,{writable:!0,value:new Set}),Object.defineProperty(this,di,{writable:!0,value:new Set}),this.scheduledAutoProceed=null,this.wasOffline=!1,this.calculateProgress=wo((e,t)=>{const n=this.getFile(null==e?void 0:e.id);if(null==e||!n)return void this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`);if(100===n.progress.percentage)return void this.log(`Not setting progress for a file that has been already uploaded: ${e.id}`);const r=Number.isFinite(t.bytesTotal)&&t.bytesTotal>0;this.setFileState(e.id,{progress:{...n.progress,bytesUploaded:t.bytesUploaded,bytesTotal:t.bytesTotal,percentage:r?Math.round(t.bytesUploaded/t.bytesTotal*100):0}}),this.calculateTotalProgress()},500,{leading:!0,trailing:!0}),Object.defineProperty(this,wi,{writable:!0,value:this.updateOnlineStatus.bind(this)}),Object.defineProperty(this,bi,{writable:!0,value:new Map}),this.defaultLocale=Qo;const t={id:"uppy",autoProceed:!1,allowMultipleUploadBatches:!0,debug:!1,restrictions:Go,meta:{},onBeforeFileAdded:(e,t)=>!Object.hasOwn(t,e.id),onBeforeUpload:e=>e,store:new ko,logger:Mo,infoTimeout:5e3},n={...t,...e};this.opts={...n,restrictions:{...t.restrictions,...e&&e.restrictions}},e&&e.logger&&e.debug?this.log("You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.","warning"):e&&e.debug&&(this.opts.logger=Uo),this.log(`Using Core v${ki.VERSION}`),this.i18nInit(),this.store=this.opts.store,this.setState({...oi,plugins:{},files:{},currentUploads:{},capabilities:{uploadProgress:No(),individualCancellation:!0,resumableUploads:!1},meta:{...this.opts.meta},info:[]}),ti(this,si)[si]=new Xo(()=>this.opts,()=>this.i18n),ti(this,ai)[ai]=this.store.subscribe((e,t,n)=>{this.emit("state-update",e,t,n),this.updateAll(t)}),this.opts.debug&&"undefined"!=typeof window&&(window[this.opts.id]=this),ti(this,vi)[vi]()}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];ti(this,li)[li].emit(e,...n)}on(e,t){return ti(this,li)[li].on(e,t),this}once(e,t){return ti(this,li)[li].once(e,t),this}off(e,t){return ti(this,li)[li].off(e,t),this}updateAll(e){this.iteratePlugins(t=>{t.update(e)})}setState(e){this.store.setState(e)}getState(){return this.store.getState()}patchFilesState(e){const t=this.getState().files;this.setState({files:{...t,...Object.fromEntries(Object.entries(e).map(e=>{let[n,r]=e;return[n,{...t[n],...r}]}))}})}setFileState(e,t){if(!this.getState().files[e])throw new Error(`Can’t set state for ${e} (the file could have been removed)`);this.patchFilesState({[e]:t})}i18nInit(){const e=new Rr([this.defaultLocale,this.opts.locale],{onMissingKey:e=>this.log(`Missing i18n string: ${e}`,"error")});this.i18n=e.translate.bind(e),this.i18nArray=e.translateArray.bind(e),this.locale=e.locale}setOptions(e){this.opts={...this.opts,...e,restrictions:{...this.opts.restrictions,...null==e?void 0:e.restrictions}},e.meta&&this.setMeta(e.meta),this.i18nInit(),e.locale&&this.iteratePlugins(t=>{t.setOptions(e)}),this.setState(void 0)}resetProgress(){const e={percentage:0,bytesUploaded:0,uploadComplete:!1,uploadStarted:null},t={...this.getState().files},n={};Object.keys(t).forEach(r=>{n[r]={...t[r],progress:{...t[r].progress,...e}}}),this.setState({files:n,...oi}),this.emit("reset-progress")}clearUploadedFiles(){const{capabilities:e,currentUploads:t}=this.getState();if(Object.keys(t).length>0&&!e.individualCancellation)throw new Error("The installed uploader plugin does not allow removing files during an upload.");this.setState({...oi,files:{}})}addPreProcessor(e){ti(this,ci)[ci].add(e)}removePreProcessor(e){return ti(this,ci)[ci].delete(e)}addPostProcessor(e){ti(this,di)[di].add(e)}removePostProcessor(e){return ti(this,di)[di].delete(e)}addUploader(e){ti(this,ui)[ui].add(e)}removeUploader(e){return ti(this,ui)[ui].delete(e)}setMeta(e){const t={...this.getState().meta,...e},n={...this.getState().files};Object.keys(n).forEach(t=>{n[t]={...n[t],meta:{...n[t].meta,...e}}}),this.log("Adding metadata:"),this.log(e),this.setState({meta:t,files:n})}setFileMeta(e,t){const n={...this.getState().files};if(!n[e])return void this.log("Was trying to set metadata for a file that has been removed: ",e);const r={...n[e].meta,...t};n[e]={...n[e],meta:r},this.setState({files:n})}getFile(e){return this.getState().files[e]}getFiles(){const{files:e}=this.getState();return Object.values(e)}getFilesByIds(e){return e.map(e=>this.getFile(e))}getObjectOfFilesPerState(){const{files:e,totalProgress:t,error:n}=this.getState(),r=Object.values(e),o=[],i=[],s=[],a=[],l=[],c=[],u=[],d=[],h=[];for(const e of r){const{progress:t}=e;!t.uploadComplete&&t.uploadStarted&&(o.push(e),e.isPaused||d.push(e)),t.uploadStarted||i.push(e),(t.uploadStarted||t.preprocess||t.postprocess)&&s.push(e),t.uploadStarted&&a.push(e),e.isPaused&&l.push(e),t.uploadComplete&&c.push(e),e.error&&u.push(e),(t.preprocess||t.postprocess)&&h.push(e)}return{newFiles:i,startedFiles:s,uploadStartedFiles:a,pausedFiles:l,completeFiles:c,erroredFiles:u,inProgressFiles:o,inProgressNotPausedFiles:d,processingFiles:h,isUploadStarted:a.length>0,isAllComplete:100===t&&c.length===r.length&&0===h.length,isAllErrored:!!n&&u.length===r.length,isAllPaused:0!==o.length&&l.length===o.length,isUploadInProgress:o.length>0,isSomeGhost:r.some(e=>e.isGhost)}}validateRestrictions(e,t){void 0===t&&(t=this.getFiles());try{ti(this,si)[si].validate(t,[e])}catch(e){return e}return null}checkIfFileAlreadyExists(e){const{files:t}=this.getState();return!(!t[e]||t[e].isGhost)}addFile(e){ti(this,fi)[fi](e);const{nextFilesState:t,validFilesToAdd:n,errors:r}=ti(this,yi)[yi]([e]),o=r.filter(e=>e.isRestriction);if(ti(this,hi)[hi](o),r.length>0)throw r[0];this.setState({files:t});const[i]=n;return this.emit("file-added",i),this.emit("files-added",n),this.log(`Added file: ${i.name}, ${i.id}, mime type: ${i.type}`),ti(this,gi)[gi](),i.id}addFiles(e){ti(this,fi)[fi]();const{nextFilesState:t,validFilesToAdd:n,errors:r}=ti(this,yi)[yi](e),o=r.filter(e=>e.isRestriction);ti(this,hi)[hi](o);const i=r.filter(e=>!e.isRestriction);if(i.length>0){let e="Multiple errors occurred while adding files:\n";if(i.forEach(t=>{e+=`\n * ${t.message}`}),this.info({message:this.i18n("addBulkFilesFailed",{smart_count:i.length}),details:e},"error",this.opts.infoTimeout),"function"==typeof AggregateError)throw new AggregateError(i,e);{const t=new Error(e);throw t.errors=i,t}}this.setState({files:t}),n.forEach(e=>{this.emit("file-added",e)}),this.emit("files-added",n),n.length>5?this.log(`Added batch of ${n.length} files`):Object.values(n).forEach(e=>{this.log(`Added file: ${e.name}\n id: ${e.id}\n type: ${e.type}`)}),n.length>0&&ti(this,gi)[gi]()}removeFiles(e,t){const{files:n,currentUploads:r}=this.getState(),o={...n},i={...r},s=Object.create(null);function a(e){return void 0===s[e]}e.forEach(e=>{n[e]&&(s[e]=n[e],delete o[e])}),Object.keys(i).forEach(e=>{const t=r[e].fileIDs.filter(a);if(0===t.length)return void delete i[e];const{capabilities:n}=this.getState();if(t.length!==r[e].fileIDs.length&&!n.individualCancellation)throw new Error("The installed uploader plugin does not allow removing files during an upload.");i[e]={...r[e],fileIDs:t}});const l={currentUploads:i,files:o};0===Object.keys(o).length&&(l.allowNewUpload=!0,l.error=null,l.recoveredState=null),this.setState(l),this.calculateTotalProgress();const c=Object.keys(s);c.forEach(e=>{this.emit("file-removed",s[e],t)}),c.length>5?this.log(`Removed ${c.length} files`):this.log(`Removed files: ${c.join(", ")}`)}removeFile(e,t){this.removeFiles([e],t)}pauseResume(e){if(!this.getState().capabilities.resumableUploads||this.getFile(e).progress.uploadComplete)return;const t=!(this.getFile(e).isPaused||!1);return this.setFileState(e,{isPaused:t}),this.emit("upload-pause",e,t),t}pauseAll(){const e={...this.getState().files};Object.keys(e).filter(t=>!e[t].progress.uploadComplete&&e[t].progress.uploadStarted).forEach(t=>{const n={...e[t],isPaused:!0};e[t]=n}),this.setState({files:e}),this.emit("pause-all")}resumeAll(){const e={...this.getState().files};Object.keys(e).filter(t=>!e[t].progress.uploadComplete&&e[t].progress.uploadStarted).forEach(t=>{const n={...e[t],isPaused:!1,error:null};e[t]=n}),this.setState({files:e}),this.emit("resume-all")}retryAll(){const e={...this.getState().files},t=Object.keys(e).filter(t=>e[t].error);if(t.forEach(t=>{const n={...e[t],isPaused:!1,error:null};e[t]=n}),this.setState({files:e,error:null}),this.emit("retry-all",t),0===t.length)return Promise.resolve({successful:[],failed:[]});const n=ti(this,Si)[Si](t,{forceAllowNewUpload:!0});return ti(this,Ti)[Ti](n)}cancelAll(e){let{reason:t="user"}=void 0===e?{}:e;if(this.emit("cancel-all",{reason:t}),"user"===t){const{files:e}=this.getState(),t=Object.keys(e);t.length&&this.removeFiles(t,"cancel-all"),this.setState(oi)}}retryUpload(e){this.setFileState(e,{error:null,isPaused:!1}),this.emit("upload-retry",e);const t=ti(this,Si)[Si]([e],{forceAllowNewUpload:!0});return ti(this,Ti)[Ti](t)}logout(){this.iteratePlugins(e=>{var t;null==(t=e.provider)||null==t.logout||t.logout()})}calculateTotalProgress(){const e=this.getFiles().filter(e=>e.progress.uploadStarted||e.progress.preprocess||e.progress.postprocess);if(0===e.length)return this.emit("progress",0),void this.setState({totalProgress:0});const t=e.filter(e=>null!=e.progress.bytesTotal),n=e.filter(e=>null==e.progress.bytesTotal);if(0===t.length){const t=100*e.length,r=n.reduce((e,t)=>e+t.progress.percentage,0),o=Math.round(r/t*100);return void this.setState({totalProgress:o})}let r=t.reduce((e,t)=>{var n;return e+(null!=(n=t.progress.bytesTotal)?n:0)},0);const o=r/t.length;r+=o*n.length;let i=0;t.forEach(e=>{i+=e.progress.bytesUploaded}),n.forEach(e=>{i+=o*(e.progress.percentage||0)/100});let s=0===r?0:Math.round(i/r*100);s>100&&(s=100),this.setState({totalProgress:s}),this.emit("progress",s)}updateOnlineStatus(){var e;null==(e=window.navigator.onLine)||e?(this.emit("is-online"),this.wasOffline&&(this.emit("back-online"),this.info(this.i18n("connectedToInternet"),"success",3e3),this.wasOffline=!1)):(this.emit("is-offline"),this.info(this.i18n("noInternetConnection"),"error",0),this.wasOffline=!0)}getID(){return this.opts.id}use(e,t){if("function"!=typeof e){throw new TypeError(`Expected a plugin class, but got ${null===e?"null":typeof e}. Please verify that the plugin was imported and spelled correctly.`)}const n=new e(this,t),r=n.id;if(!r)throw new Error("Your plugin must have an id");if(!n.type)throw new Error("Your plugin must have a type");const o=this.getPlugin(r);if(o){const e=`Already found a plugin named '${o.id}'. Tried to use: '${r}'.\nUppy plugins must have unique \`id\` options. See https://uppy.io/docs/plugins/#id.`;throw new Error(e)}return e.VERSION&&this.log(`Using ${r} v${e.VERSION}`),n.type in ti(this,ii)[ii]?ti(this,ii)[ii][n.type].push(n):ti(this,ii)[ii][n.type]=[n],n.install(),this.emit("plugin-added",n),this}getPlugin(e){for(const t of Object.values(ti(this,ii)[ii])){const n=t.find(t=>t.id===e);if(null!=n)return n}}[Zo](e){return ti(this,ii)[ii][e]}iteratePlugins(e){Object.values(ti(this,ii)[ii]).flat(1).forEach(e)}removePlugin(e){this.log(`Removing plugin ${e.id}`),this.emit("plugin-remove",e),e.uninstall&&e.uninstall();const t=ti(this,ii)[ii][e.type],n=t.findIndex(t=>t.id===e.id);-1!==n&&t.splice(n,1);const r={plugins:{...this.getState().plugins,[e.id]:void 0}};this.setState(r)}close(e){let{reason:t}=void 0===e?{}:e;this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`),this.cancelAll({reason:t}),ti(this,ai)[ai](),this.iteratePlugins(e=>{this.removePlugin(e)}),"undefined"!=typeof window&&window.removeEventListener&&(window.removeEventListener("online",ti(this,wi)[wi]),window.removeEventListener("offline",ti(this,wi)[wi]))}hideInfo(){const{info:e}=this.getState();this.setState({info:e.slice(1)}),this.emit("info-hidden")}info(e,t,n){void 0===t&&(t="info"),void 0===n&&(n=3e3);const r="object"==typeof e;this.setState({info:[...this.getState().info,{type:t,message:r?e.message:e,details:r?e.details:null}]}),setTimeout(()=>this.hideInfo(),n),this.emit("info-visible")}log(e,t){const{logger:n}=this.opts;switch(t){case"error":n.error(e);break;case"warning":n.warn(e);break;default:n.debug(e)}}registerRequestClient(e,t){ti(this,bi)[bi].set(e,t)}getRequestClientForFile(e){if(!e.remote)throw new Error(`Tried to get RequestClient for a non-remote file ${e.id}`);const t=ti(this,bi)[bi].get(e.remote.requestClientId);if(null==t)throw new Error(`requestClientId "${e.remote.requestClientId}" not registered for file "${e.id}"`);return t}restore(e){return this.log(`Core: attempting to restore upload "${e}"`),this.getState().currentUploads[e]?ti(this,Ti)[Ti](e):(ti(this,Pi)[Pi](e),Promise.reject(new Error("Nonexistent upload")))}[ei](){return ti(this,Si)[Si](...arguments)}addResultData(e,t){if(!ti(this,Ei)[Ei](e))return void this.log(`Not setting result for an upload that has been removed: ${e}`);const{currentUploads:n}=this.getState(),r={...n[e],result:{...n[e].result,...t}};this.setState({currentUploads:{...n,[e]:r}})}upload(){var e;null!=(e=ti(this,ii)[ii].uploader)&&e.length||this.log("No uploader type plugins are used","warning");let{files:t}=this.getState();const n=this.opts.onBeforeUpload(t);return!1===n?Promise.reject(new Error("Not starting the upload because onBeforeUpload returned false")):(n&&"object"==typeof n&&(t=n,this.setState({files:t})),Promise.resolve().then(()=>ti(this,si)[si].validateMinNumberOfFiles(t)).catch(e=>{throw ti(this,hi)[hi]([e]),e}).then(()=>{if(!ti(this,_i)[_i](t))throw new Jo(this.i18n("missingRequiredMetaField"))}).catch(e=>{throw e}).then(()=>{const{currentUploads:e}=this.getState(),n=Object.values(e).flatMap(e=>e.fileIDs),r=[];Object.keys(t).forEach(e=>{const t=this.getFile(e);t.progress.uploadStarted||-1!==n.indexOf(e)||r.push(t.id)});const o=ti(this,Si)[Si](r);return ti(this,Ti)[Ti](o)}).catch(e=>{throw this.emit("error",e),this.log(e,"error"),e}))}}function xi(e){for(const t of e)t.isRestriction?this.emit("restriction-failed",t.file,t):this.emit("error",t,t.file),this.log(t,"warning");const t=e.filter(e=>e.isUserFacing),n=t.slice(0,4),r=t.slice(4);n.forEach(e=>{let{message:t,details:n=""}=e;this.info({message:t,details:n},"error",this.opts.infoTimeout)}),r.length>0&&this.info({message:this.i18n("additionalRestrictionsFailed",{count:r.length})})}function Ci(e){const{missingFields:t,error:n}=ti(this,si)[si].getMissingRequiredMetaFields(e);return!(t.length>0)||(this.setFileState(e.id,{missingRequiredMetaFields:t}),this.log(n.message),this.emit("restriction-failed",e,n),!1)}function Oi(e){let t=!0;for(const n of Object.values(e))ti(this,pi)[pi](n)||(t=!1);return t}function ji(e){const{allowNewUpload:t}=this.getState();if(!1===t){const t=new Jo(this.i18n("noMoreFilesAllowed"),{file:e});throw ti(this,hi)[hi]([t]),t}}function Ri(e){const t=e instanceof File?{name:e.name,type:e.type,size:e.size,data:e}:e,n=jo(t),r=function(e,t){return t.name?t.name:"image"===e.split("/")[0]?`${e.split("/")[0]}.${e.split("/")[1]}`:"noname"}(n,t),o=Co(r).extension,i=Ao(t,this.getID()),s=t.meta||{};s.name=r,s.type=n;const a=Number.isFinite(t.data.size)?t.data.size:null;return{source:t.source||"",id:i,name:r,extension:o||"",meta:{...this.getState().meta,...s},type:n,data:t.data,progress:{percentage:0,bytesUploaded:0,bytesTotal:a,uploadComplete:!1,uploadStarted:null},size:a,isGhost:!1,isRemote:t.isRemote||!1,remote:t.remote||"",preview:t.preview}}function Ai(){this.opts.autoProceed&&!this.scheduledAutoProceed&&(this.scheduledAutoProceed=setTimeout(()=>{this.scheduledAutoProceed=null,this.upload().catch(e=>{e.isRestriction||this.log(e.stack||e.message||e)})},4))}function Ni(e){const{files:t}=this.getState(),n={...t},r=[],o=[];for(const s of e)try{var i;let e=ti(this,mi)[mi](s);const o=null==(i=t[e.id])?void 0:i.isGhost;if(o){e={...t[e.id],isGhost:!1,data:s.data},this.log(`Replaced the blob in the restored ghost file: ${e.name}, ${e.id}`)}const a=this.opts.onBeforeFileAdded(e,n);if(!a&&this.checkIfFileAlreadyExists(e.id))throw new Jo(this.i18n("noDuplicates",{fileName:e.name}),{file:s});if(!1===a&&!o)throw new Jo("Cannot add the file because onBeforeFileAdded returned false.",{isUserFacing:!1,file:s});"object"==typeof a&&null!==a&&(e=a),ti(this,si)[si].validateSingleFile(e),n[e.id]=e,r.push(e)}catch(e){o.push(e)}try{ti(this,si)[si].validateAggregateRestrictions(Object.values(t),r)}catch(e){return o.push(e),{nextFilesState:t,validFilesToAdd:[],errors:o}}return{nextFilesState:n,validFilesToAdd:r,errors:o}}function Fi(){const e=(e,t,n)=>{let r=e.message||"Unknown error";e.details&&(r+=` ${e.details}`),this.setState({error:r}),null!=t&&t.id in this.getState().files&&this.setFileState(t.id,{error:r,response:n})};this.on("error",e),this.on("upload-error",(t,n,r)=>{if(e(n,t,r),"object"==typeof n&&n.message){var o;this.log(n.message,"error");const e=new Error(this.i18n("failedToUpload",{file:null!=(o=null==t?void 0:t.name)?o:""}));e.isUserFacing=!0,e.details=n.message,n.details&&(e.details+=` ${n.details}`),ti(this,hi)[hi]([e])}else ti(this,hi)[hi]([n])});let t=null;this.on("upload-stalled",(e,n)=>{const{message:r}=e,o=n.map(e=>e.meta.name).join(", ");t||(this.info({message:r,details:o},"warning",this.opts.infoTimeout),t=setTimeout(()=>{t=null},this.opts.infoTimeout)),this.log(`${r} ${o}`.trim(),"warning")}),this.on("upload",()=>{this.setState({error:null})});const n=e=>{const t=e.filter(e=>{const t=null!=e&&this.getFile(e.id);return t||this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`),t}),n=Object.fromEntries(t.map(e=>[e.id,{progress:{uploadStarted:Date.now(),uploadComplete:!1,percentage:0,bytesUploaded:0,bytesTotal:e.size}}]));this.patchFilesState(n)};this.on("upload-start",e=>{e.forEach(e=>{this.emit("upload-started",e)}),n(e)}),this.on("upload-progress",this.calculateProgress),this.on("upload-success",(e,t)=>{if(null==e||!this.getFile(e.id))return void this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`);const n=this.getFile(e.id).progress;this.setFileState(e.id,{progress:{...n,postprocess:ti(this,di)[di].size>0?{mode:"indeterminate"}:void 0,uploadComplete:!0,percentage:100,bytesUploaded:n.bytesTotal},response:t,uploadURL:t.uploadURL,isPaused:!1}),null==e.size&&this.setFileState(e.id,{size:t.bytesUploaded||n.bytesTotal}),this.calculateTotalProgress()}),this.on("preprocess-progress",(e,t)=>{null!=e&&this.getFile(e.id)?this.setFileState(e.id,{progress:{...this.getFile(e.id).progress,preprocess:t}}):this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`)}),this.on("preprocess-complete",e=>{if(null==e||!this.getFile(e.id))return void this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`);const t={...this.getState().files};t[e.id]={...t[e.id],progress:{...t[e.id].progress}},delete t[e.id].progress.preprocess,this.setState({files:t})}),this.on("postprocess-progress",(e,t)=>{null!=e&&this.getFile(e.id)?this.setFileState(e.id,{progress:{...this.getState().files[e.id].progress,postprocess:t}}):this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`)}),this.on("postprocess-complete",e=>{if(null==e||!this.getFile(e.id))return void this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`);const t={...this.getState().files};t[e.id]={...t[e.id],progress:{...t[e.id].progress}},delete t[e.id].progress.postprocess,this.setState({files:t})}),this.on("restored",()=>{this.calculateTotalProgress()}),this.on("dashboard:file-edit-complete",e=>{e&&ti(this,pi)[pi](e)}),"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("online",ti(this,wi)[wi]),window.addEventListener("offline",ti(this,wi)[wi]),setTimeout(ti(this,wi)[wi],3e3))}function Ii(e,t){void 0===t&&(t={});const{forceAllowNewUpload:n=!1}=t,{allowNewUpload:r,currentUploads:o}=this.getState();if(!r&&!n)throw new Error("Cannot create a new upload: already uploading.");const i=((e=21)=>{let t="",n=e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t})();return this.emit("upload",{id:i,fileIDs:e}),this.setState({allowNewUpload:!1!==this.opts.allowMultipleUploadBatches&&!1!==this.opts.allowMultipleUploads,currentUploads:{...o,[i]:{fileIDs:e,step:0,result:{}}}}),i}function Mi(e){const{currentUploads:t}=this.getState();return t[e]}function Ui(e){const t={...this.getState().currentUploads};delete t[e],this.setState({currentUploads:t})}async function Li(e){const t=()=>{const{currentUploads:t}=this.getState();return t[e]};let n=t();const r=[...ti(this,ci)[ci],...ti(this,ui)[ui],...ti(this,di)[di]];try{for(let o=n.step||0;o<r.length&&n;o++){const i=r[o];this.setState({currentUploads:{...this.getState().currentUploads,[e]:{...n,step:o}}});const{fileIDs:s}=n;await i(s,e),n=t()}}catch(t){throw ti(this,Pi)[Pi](e),t}if(n){n.fileIDs.forEach(e=>{const t=this.getFile(e);t&&t.progress.postprocess&&this.emit("postprocess-complete",t)});const r=n.fileIDs.map(e=>this.getFile(e)),o=r.filter(e=>!e.error),i=r.filter(e=>e.error);this.addResultData(e,{successful:o,failed:i,uploadID:e}),n=t()}let o;return n&&(o=n.result,this.emit("complete",o),ti(this,Pi)[Pi](e)),null==o&&this.log(`Not setting result for an upload that has been removed: ${e}`),o}ki.VERSION="3.13.1";class zi{constructor(e,t){this.uppy=e,this.opts=null!=t?t:{}}getPluginState(){const{plugins:e}=this.uppy.getState();return(null==e?void 0:e[this.id])||{}}setPluginState(e){const{plugins:t}=this.uppy.getState();this.uppy.setState({plugins:{...t,[this.id]:{...t[this.id],...e}}})}setOptions(e){this.opts={...this.opts,...e},this.setPluginState(void 0),this.i18nInit()}i18nInit(){const e=new Rr([this.defaultLocale,this.uppy.locale,this.opts.locale]);this.i18n=e.translate.bind(e),this.i18nArray=e.translateArray.bind(e),this.setPluginState(void 0)}addTarget(e){throw new Error("Extend the addTarget method to add your plugin to another plugin's target")}install(){}uninstall(){}update(e){}afterUpdate(){}}class Di extends Error{constructor(){super(...arguments),this.name="UserFacingApiError"}}var Bi,$i,qi,Wi,Hi,Vi={};function Ki(){return qi||(qi=1,e=Vi,t=function(){if($i)return Bi;function e(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return $i=1,Bi=e,e.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},e.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},e.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(void 0===n){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1)}var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0},e.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},e.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},e.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},e.prototype.start=e.prototype.try,e.prototype.errors=function(){return this._errors},e.prototype.attempts=function(){return this._attempts},e.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var o=this._errors[r],i=o.message,s=(e[i]||0)+1;e[i]=s,s>=n&&(t=o,n=s)}return t},Bi}(),e.operation=function(n){var r=e.timeouts(n);return new t(r,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],o=0;o<t.retries;o++)r.push(this.createTimeout(o,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(o,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return r=Math.min(r,t.maxTimeout)},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var o in r=[],t)"function"==typeof t[o]&&r.push(o);for(var i=0;i<r.length;i++){var s=r[i],a=t[s];t[s]=function(r){var o=e.operation(n),i=Array.prototype.slice.call(arguments,1),s=i.pop();i.push(function(e){o.retry(e)||(e&&(arguments[0]=o.mainError()),s.apply(this,arguments))}),o.attempt(function(){r.apply(t,i)})}.bind(t,a),t[s].options=n}}),Vi;var e,t}var Yi=Hi?Wi:(Hi=1,Wi=Ki()),Gi=r.getDefaultExportFromCjs(Yi);const Ji=Object.prototype.toString,Xi=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Qi(e){const t=e&&(e=>"[object Error]"===Ji.call(e))(e)&&"TypeError"===e.name&&"string"==typeof e.message;if(!t)return!1;const{message:n,stack:r}=e;return"Load failed"===n?void 0===r||"__sentry_captured__"in e:!!n.startsWith("error sending request for url")||Xi.has(n)}class Zi extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const es=(e,t,n)=>{const r=n.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=r,e};async function ts(e,t){return new Promise((n,r)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const o=Gi.operation(t),i=()=>{o.stop(),r(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",i,{once:!0});const s=()=>{t.signal?.removeEventListener("abort",i),o.stop()};o.attempt(async i=>{try{const t=await e(i);s(),n(t)}catch(e){try{if(!(e instanceof Error))throw new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(e instanceof Zi)throw e.originalError;if(e instanceof TypeError&&!Qi(e))throw e;if(es(e,i,t),await t.shouldRetry(e)||(o.stop(),r(e)),await t.onFailedAttempt(e),!o.retry(e))throw o.mainError()}catch(e){es(e,i,t),s(),r(e)}}})})}class ns extends Error{constructor(e,t){void 0===t&&(t=null),super("This looks like a network error, the endpoint might be blocked by an internet provider or a firewall."),this.cause=e,this.isNetworkError=!0,this.request=t}}function rs(e,t){return Object.prototype.hasOwnProperty.call(e,t)}class os extends Error{constructor(e,t){super(e),this.cause=null==t?void 0:t.cause,this.cause&&rs(this.cause,"isNetworkError")?this.isNetworkError=this.cause.isNetworkError:this.isNetworkError=!1}}var is=wo(function(e,t,n){const{progress:r,bytesUploaded:o,bytesTotal:i}=t;r&&(e.uppy.log(`Upload progress: ${r}`),e.uppy.emit("upload-progress",n,{uploader:e,bytesUploaded:o,bytesTotal:i}))},300,{leading:!0,trailing:!0});class ss extends Error{constructor(){super("Authorization required"),this.name="AuthError",this.isAuthError=!0}}let as;function ls(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var cs=0;function us(e){return"__private_"+cs+++"_"+e}class ds extends Error{constructor(e){let{statusCode:t,message:n}=e;super(n),this.name="HttpError",this.statusCode=t}}var hs=us("companionHeaders"),ps=us("getUrl"),_s=us("requestSocketToken"),fs=us("awaitRemoteFileUpload");as=Symbol.for("uppy test: getCompanionHeaders");class ms{constructor(e,t){Object.defineProperty(this,fs,{value:ys}),Object.defineProperty(this,ps,{value:gs}),Object.defineProperty(this,hs,{writable:!0,value:void 0}),Object.defineProperty(this,_s,{writable:!0,value:async e=>{var t;let{file:n,postBody:r,signal:o}=e;if(null==(null==(t=n.remote)?void 0:t.url))throw new Error("Cannot connect to an undefined URL");return(await this.post(n.remote.url,{...n.remote.body,...r},{signal:o})).token}}),this.uppy=e,this.opts=t,this.onReceiveResponse=this.onReceiveResponse.bind(this),ls(this,hs)[hs]=null==t?void 0:t.companionHeaders}setCompanionHeaders(e){ls(this,hs)[hs]=e}[as](){return ls(this,hs)[hs]}get hostname(){const{companion:e}=this.uppy.getState(),t=this.opts.companionUrl;return function(e){return e.replace(/\/$/,"")}(e&&e[t]?e[t]:t)}async headers(e){void 0===e&&(e=!1);return{...{Accept:"application/json",...e?void 0:{"Content-Type":"application/json"}},...ls(this,hs)[hs]}}onReceiveResponse(e){const{headers:t}=e,n=this.uppy.getState().companion||{},r=this.opts.companionUrl;t.has("i-am")&&t.get("i-am")!==n[r]&&this.uppy.setState({companion:{...n,[r]:t.get("i-am")}})}async request(e){let{path:t,method:n="GET",data:r,skipPostResponse:o,signal:i}=e;try{const e=await this.headers(!r),s=await function(){return fetch(...arguments).catch(e=>{throw"AbortError"===e.name?e:new ns(e)})}(ls(this,ps)[ps](t),{method:n,signal:i,headers:e,credentials:this.opts.companionCookiesRule||"same-origin",body:r?JSON.stringify(r):null});return o||this.onReceiveResponse(s),await async function(e){if(401===e.status)throw new ss;if(e.ok)return e.json();let t,n=`Failed request with status: ${e.status}. ${e.statusText}`;try{t=await e.json(),t.message&&(n=`${n} message: ${t.message}`),t.requestId&&(n=`${n} request-Id: ${t.requestId}`)}catch(e){throw new Error(n,{cause:e})}if(e.status>=400&&e.status<=499&&t.message)throw new Di(t.message);throw new ds({statusCode:e.status,message:n})}(s)}catch(e){if(e.isAuthError||"UserFacingApiError"===e.name||"AbortError"===e.name)throw e;throw new os(`Could not ${n} ${ls(this,ps)[ps](t)}`,{cause:e})}}async get(e,t){return"boolean"==typeof t&&(t={skipPostResponse:t}),this.request({...t,path:e})}async post(e,t,n){return"boolean"==typeof n&&(n={skipPostResponse:n}),this.request({...n,path:e,method:"POST",data:t})}async delete(e,t,n){return"boolean"==typeof n&&(n={skipPostResponse:n}),this.request({...n,path:e,method:"DELETE",data:t})}async uploadRemoteFile(e,t,n){var r=this;try{const{signal:o,getQueue:i}=n||{};return await ts(async()=>{var n;const s=null==(n=this.uppy.getFile(e.id))?void 0:n.serverToken;if(null!=s)return this.uppy.log(`Connecting to exiting websocket ${s}`),ls(this,fs)[fs]({file:e,queue:i(),signal:o});const a=i().wrapPromiseFunction(async function(){try{return await ls(r,_s)[_s](...arguments)}catch(e){if(e.isAuthError)throw new Zi(e);if(null==e.cause)throw e;const t=e.cause,n=()=>[408,409,429,418,423].includes(t.statusCode)||t.statusCode>=500&&t.statusCode<=599&&![501,505].includes(t.statusCode);if("HttpError"===t.name&&!n())throw new Zi(t);throw t}},{priority:-1}),l=await a({file:e,postBody:t,signal:o}).abortOn(o);return this.uppy.getFile(e.id)?(this.uppy.setFileState(e.id,{serverToken:l}),ls(this,fs)[fs]({file:this.uppy.getFile(e.id),queue:i(),signal:o})):void 0},{retries:10,signal:o,onFailedAttempt:e=>this.uppy.log(`Retrying upload due to: ${e.message}`,"warning")})}catch(t){if("AbortError"===t.name)return;throw this.uppy.emit("upload-error",e,t),t}}}function gs(e){return/^(https?:|)\/\//.test(e)?e:`${this.hostname}/${e}`}async function ys(e){let t,{file:n,queue:r,signal:o}=e;const{capabilities:i}=this.uppy.getState();try{return await new Promise((e,s)=>{const a=n.serverToken,l=function(e){var t;const n=null==(t=/^(?:https?:\/\/|\/\/)?(?:[^@\n]+@)?(?:www\.)?([^\n]+)/i.exec(e))?void 0:t[1];return`${/^http:\/\//i.test(e)?"ws":"wss"}://${n}`}(n.remote.companionUrl);let c,u,d,{isPaused:h}=n;const p=(e,t)=>{var r;null!=c&&c.readyState===c.OPEN?c.send(JSON.stringify({action:e,payload:null!=t?t:{}})):this.uppy.log(`Cannot send "${e}" to socket ${n.id} because the socket state was ${String(null==(r=c)?void 0:r.readyState)}`,"warning")};function _(){i.resumableUploads&&p(h?"pause":"resume")}const f=async()=>{u&&u.abort(),u=new AbortController;const t=e=>{var t;this.uppy.setFileState(n.id,{serverToken:null}),null==(t=u)||null==t.abort||t.abort(),s(e)};function o(){clearTimeout(d),h||(d=setTimeout(()=>t(new Error("Timeout waiting for message from Companion socket")),3e5))}try{await r.wrapPromiseFunction(async()=>{await ts(async()=>new Promise((r,i)=>{c=new WebSocket(`${l}/api/${a}`),o(),c.addEventListener("close",()=>{c=void 0,i(new Error("Socket closed unexpectedly"))}),c.addEventListener("error",e=>{var t;this.uppy.log(`Companion socket error ${JSON.stringify(e)}, closing socket`,"warning"),null==(t=c)||t.close()}),c.addEventListener("open",()=>{_()}),c.addEventListener("message",r=>{o();try{const{action:t,payload:o}=JSON.parse(r.data);switch(t){case"progress":is(this,o,this.uppy.getFile(n.id));break;case"success":{var i,s,a,l;const t=null==(i=o.response)?void 0:i.responseText;this.uppy.emit("upload-success",this.uppy.getFile(n.id),{uploadURL:o.url,status:null!=(s=null==(a=o.response)?void 0:a.status)?s:200,body:t?JSON.parse(t):void 0}),null==(l=u)||null==l.abort||l.abort(),e();break}case"error":{const{message:e}=o.error;throw Object.assign(new Error(e),{cause:o.error})}default:this.uppy.log(`Companion socket unknown action ${t}`,"warning")}}catch(e){t(e)}});const s=()=>{this.uppy.log(`Closing socket ${n.id}`,"info"),clearTimeout(d),c&&c.close(),c=void 0};u.signal.addEventListener("abort",()=>{s()})}),{retries:10,signal:u.signal,onFailedAttempt:()=>{u.signal.aborted||this.uppy.log(`Retrying websocket ${n.id}`,"info")}})})().abortOn(u.signal)}catch(e){if(u.signal.aborted)return;t(e)}},m=e=>{var t;i.resumableUploads&&(h=e,c&&_(),e?null==(t=u)||null==t.abort||t.abort():f())},g=t=>{var r;i.individualCancellation&&t.id===n.id&&(p("cancel"),null==(r=u)||null==r.abort||r.abort(),this.uppy.log(`upload ${n.id} was removed`,"info"),e())},y=t=>{var r;let{reason:o}=t;"user"===o&&p("cancel"),null==(r=u)||null==r.abort||r.abort(),this.uppy.log(`upload ${n.id} was canceled`,"info"),e()},v=(e,t)=>{e===n.id&&m(t)},w=()=>m(!0),b=()=>m(!1);this.uppy.on("file-removed",g),this.uppy.on("cancel-all",y),this.uppy.on("upload-pause",v),this.uppy.on("pause-all",w),this.uppy.on("resume-all",b),t=()=>{this.uppy.off("file-removed",g),this.uppy.off("cancel-all",y),this.uppy.off("upload-pause",v),this.uppy.off("pause-all",w),this.uppy.off("resume-all",b)},o.addEventListener("abort",()=>{var e;null==(e=u)||e.abort()}),f()})}finally{null==t||t()}}function vs(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}ms.VERSION="3.8.2";var ws=0;function bs(e){return"__private_"+ws+++"_"+e}var Ss=bs("uppy"),Es=bs("events");class Ps{constructor(e){Object.defineProperty(this,Ss,{writable:!0,value:void 0}),Object.defineProperty(this,Es,{writable:!0,value:[]}),vs(this,Ss)[Ss]=e}on(e,t){return vs(this,Es)[Es].push([e,t]),vs(this,Ss)[Ss].on(e,t)}remove(){for(const[e,t]of vs(this,Es)[Es].splice(0))vs(this,Ss)[Ss].off(e,t)}onFilePause(e,t){this.on("upload-pause",(n,r)=>{e===n&&t(r)})}onFileRemove(e,t){this.on("file-removed",n=>{e===n.id&&t(n.id)})}onPause(e,t){this.on("upload-pause",(n,r)=>{e===n&&t(r)})}onRetry(e,t){this.on("upload-retry",n=>{e===n&&t()})}onRetryAll(e,t){this.on("retry-all",()=>{vs(this,Ss)[Ss].getFile(e)&&t()})}onPauseAll(e,t){this.on("pause-all",()=>{vs(this,Ss)[Ss].getFile(e)&&t()})}onCancelAll(e,t){var n=this;this.on("cancel-all",function(){vs(n,Ss)[Ss].getFile(e)&&t(...arguments)})}onResumeAll(e,t){this.on("resume-all",()=>{vs(this,Ss)[Ss].getFile(e)&&t()})}}function Ts(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var ks=0;function xs(e){return"__private_"+ks+++"_"+e}function Cs(e){if(null!=e){var t;const n=()=>this.abort(e.reason);e.addEventListener("abort",n,{once:!0});const r=()=>{e.removeEventListener("abort",n)};null==(t=this.then)||t.call(this,r,r)}return this}var Os=xs("activeRequests"),js=xs("queuedHandlers"),Rs=xs("paused"),As=xs("pauseTimer"),Ns=xs("downLimit"),Fs=xs("upperLimit"),Is=xs("rateLimitingTimer"),Ms=xs("call"),Us=xs("queueNext"),Ls=xs("next"),zs=xs("queue"),Ds=xs("dequeue"),Bs=xs("resume"),$s=xs("increaseLimit");class qs{constructor(e){Object.defineProperty(this,Ds,{value:Ys}),Object.defineProperty(this,zs,{value:Ks}),Object.defineProperty(this,Ls,{value:Vs}),Object.defineProperty(this,Us,{value:Hs}),Object.defineProperty(this,Ms,{value:Ws}),Object.defineProperty(this,Os,{writable:!0,value:0}),Object.defineProperty(this,js,{writable:!0,value:[]}),Object.defineProperty(this,Rs,{writable:!0,value:!1}),Object.defineProperty(this,As,{writable:!0,value:void 0}),Object.defineProperty(this,Ns,{writable:!0,value:1}),Object.defineProperty(this,Fs,{writable:!0,value:void 0}),Object.defineProperty(this,Is,{writable:!0,value:void 0}),Object.defineProperty(this,Bs,{writable:!0,value:()=>this.resume()}),Object.defineProperty(this,$s,{writable:!0,value:()=>{if(Ts(this,Rs)[Rs])Ts(this,Is)[Is]=setTimeout(Ts(this,$s)[$s],0);else{Ts(this,Ns)[Ns]=this.limit,this.limit=Math.ceil((Ts(this,Fs)[Fs]+Ts(this,Ns)[Ns])/2);for(let e=Ts(this,Ns)[Ns];e<=this.limit;e++)Ts(this,Us)[Us]();Ts(this,Fs)[Fs]-Ts(this,Ns)[Ns]>3?Ts(this,Is)[Is]=setTimeout(Ts(this,$s)[$s],2e3):Ts(this,Ns)[Ns]=Math.floor(Ts(this,Ns)[Ns]/2)}}}),this.limit="number"!=typeof e||0===e?1/0:e}run(e,t){return!Ts(this,Rs)[Rs]&&Ts(this,Os)[Os]<this.limit?Ts(this,Ms)[Ms](e):Ts(this,zs)[zs](e,t)}wrapSyncFunction(e,t){var n=this;return function(){for(var r=arguments.length,o=new Array(r),i=0;i<r;i++)o[i]=arguments[i];const s=n.run(()=>(e(...o),queueMicrotask(()=>s.done()),()=>{}),t);return{abortOn:Cs,abort(){s.abort()}}}}wrapPromiseFunction(e,t){var n=this;return function(){for(var r=arguments.length,o=new Array(r),i=0;i<r;i++)o[i]=arguments[i];let s;const a=new Promise((r,i)=>{s=n.run(()=>{let t,n;try{n=Promise.resolve(e(...o))}catch(e){n=Promise.reject(e)}return n.then(e=>{t?i(t):(s.done(),r(e))},e=>{t?i(t):(s.done(),i(e))}),e=>{t=function(e){return new Error("Cancelled",{cause:e})}(e)}},t)});return a.abort=e=>{s.abort(e)},a.abortOn=Cs,a}}resume(){Ts(this,Rs)[Rs]=!1,clearTimeout(Ts(this,As)[As]);for(let e=0;e<this.limit;e++)Ts(this,Us)[Us]()}pause(e){void 0===e&&(e=null),Ts(this,Rs)[Rs]=!0,clearTimeout(Ts(this,As)[As]),null!=e&&(Ts(this,As)[As]=setTimeout(Ts(this,Bs)[Bs],e))}rateLimit(e){clearTimeout(Ts(this,Is)[Is]),this.pause(e),this.limit>1&&Number.isFinite(this.limit)&&(Ts(this,Fs)[Fs]=this.limit-1,this.limit=Ts(this,Ns)[Ns],Ts(this,Is)[Is]=setTimeout(Ts(this,$s)[$s],e))}get isPaused(){return Ts(this,Rs)[Rs]}}function Ws(e){Ts(this,Os)[Os]+=1;let t,n=!1;try{t=e()}catch(e){throw Ts(this,Os)[Os]-=1,e}return{abort:e=>{n||(n=!0,Ts(this,Os)[Os]-=1,null==t||t(e),Ts(this,Us)[Us]())},done:()=>{n||(n=!0,Ts(this,Os)[Os]-=1,Ts(this,Us)[Us]())}}}function Hs(){queueMicrotask(()=>Ts(this,Ls)[Ls]())}function Vs(){if(Ts(this,Rs)[Rs]||Ts(this,Os)[Os]>=this.limit)return;if(0===Ts(this,js)[js].length)return;const e=Ts(this,js)[js].shift();if(null==e)throw new Error("Invariant violation: next is null");const t=Ts(this,Ms)[Ms](e.fn);e.abort=t.abort,e.done=t.done}function Ks(e,t){const n={fn:e,priority:(null==t?void 0:t.priority)||0,abort:()=>{Ts(this,Ds)[Ds](n)},done:()=>{throw new Error("Cannot mark a queued request as done: this indicates a bug")}},r=Ts(this,js)[js].findIndex(e=>n.priority>e.priority);return-1===r?Ts(this,js)[js].push(n):Ts(this,js)[js].splice(r,0,n),n}function Ys(e){const t=Ts(this,js)[js].indexOf(e);-1!==t&&Ts(this,js)[js].splice(t,1)}const{AbortController:Gs}=globalThis,Js=function(e,t){void 0===e&&(e="Aborted");const n=new DOMException(e,"AbortError");return null!=t&&rs(t,"cause")&&Object.defineProperty(n,"cause",{__proto__:null,configurable:!0,writable:!0,value:t.cause}),n};function Xs(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var Qs=0;function Zs(e){return"__private_"+Qs+++"_"+e}const ea={getChunkSize:e=>Math.ceil(e.size/1e4),onProgress(){},onPartComplete(){},onSuccess(){},onError(e){throw e}};const ta=Symbol("pausing upload, not an actual error");var na=Zs("abortController"),ra=Zs("chunks"),oa=Zs("chunkState"),ia=Zs("data"),sa=Zs("file"),aa=Zs("uploadHasStarted"),la=Zs("onError"),ca=Zs("onSuccess"),ua=Zs("shouldUseMultipart"),da=Zs("isRestoring"),ha=Zs("onReject"),pa=Zs("maxMultipartParts"),_a=Zs("minPartSize"),fa=Zs("initChunks"),ma=Zs("createUpload"),ga=Zs("resumeUpload"),ya=Zs("onPartProgress"),va=Zs("onPartComplete"),wa=Zs("abortUpload");class ba{constructor(e,t){var n;Object.defineProperty(this,wa,{value:Ta}),Object.defineProperty(this,ga,{value:Pa}),Object.defineProperty(this,ma,{value:Ea}),Object.defineProperty(this,fa,{value:Sa}),Object.defineProperty(this,na,{writable:!0,value:new Gs}),Object.defineProperty(this,ra,{writable:!0,value:void 0}),Object.defineProperty(this,oa,{writable:!0,value:void 0}),Object.defineProperty(this,ia,{writable:!0,value:void 0}),Object.defineProperty(this,sa,{writable:!0,value:void 0}),Object.defineProperty(this,aa,{writable:!0,value:!1}),Object.defineProperty(this,la,{writable:!0,value:void 0}),Object.defineProperty(this,ca,{writable:!0,value:void 0}),Object.defineProperty(this,ua,{writable:!0,value:void 0}),Object.defineProperty(this,da,{writable:!0,value:void 0}),Object.defineProperty(this,ha,{writable:!0,value:e=>(null==e?void 0:e.cause)===ta?null:Xs(this,la)[la](e)}),Object.defineProperty(this,pa,{writable:!0,value:1e4}),Object.defineProperty(this,_a,{writable:!0,value:5242880}),Object.defineProperty(this,ya,{writable:!0,value:e=>t=>{if(!t.lengthComputable)return;Xs(this,oa)[oa][e].uploaded=function(e){if("string"==typeof e)return parseInt(e,10);if("number"==typeof e)return e;throw new TypeError("Expected a number")}(t.loaded);const n=Xs(this,oa)[oa].reduce((e,t)=>e+t.uploaded,0);this.options.onProgress(n,Xs(this,ia)[ia].size)}}),Object.defineProperty(this,va,{writable:!0,value:e=>t=>{Xs(this,ra)[ra][e]=null,Xs(this,oa)[oa][e].etag=t,Xs(this,oa)[oa][e].done=!0;const n={PartNumber:e+1,ETag:t};this.options.onPartComplete(n)}}),this.options={...ea,...t},null!=(n=this.options).getChunkSize||(n.getChunkSize=ea.getChunkSize),Xs(this,ia)[ia]=e,Xs(this,sa)[sa]=t.file,Xs(this,ca)[ca]=this.options.onSuccess,Xs(this,la)[la]=this.options.onError,Xs(this,ua)[ua]=this.options.shouldUseMultipart,Xs(this,da)[da]=t.uploadId&&t.key,Xs(this,fa)[fa]()}start(){Xs(this,aa)[aa]?(Xs(this,na)[na].signal.aborted||Xs(this,na)[na].abort(ta),Xs(this,na)[na]=new Gs,Xs(this,ga)[ga]()):Xs(this,da)[da]?(this.options.companionComm.restoreUploadFile(Xs(this,sa)[sa],{uploadId:this.options.uploadId,key:this.options.key}),Xs(this,ga)[ga]()):Xs(this,ma)[ma]()}pause(){Xs(this,na)[na].abort(ta),Xs(this,na)[na]=new Gs}abort(e){null!=e&&e.really?Xs(this,wa)[wa]():this.pause()}get chunkState(){return Xs(this,oa)[oa]}}function Sa(){const e=Xs(this,ia)[ia].size,t="function"==typeof Xs(this,ua)[ua]?Xs(this,ua)[ua](Xs(this,sa)[sa]):Boolean(Xs(this,ua)[ua]);if(t&&e>Xs(this,_a)[_a]){let n=Math.max(this.options.getChunkSize(Xs(this,ia)[ia]),Xs(this,_a)[_a]),r=Math.floor(e/n);r>Xs(this,pa)[pa]&&(r=Xs(this,pa)[pa],n=e/Xs(this,pa)[pa]),Xs(this,ra)[ra]=Array(r);for(let r=0,o=0;r<e;r+=n,o++){const i=Math.min(e,r+n),s=()=>{const e=r;return Xs(this,ia)[ia].slice(e,i)};if(Xs(this,ra)[ra][o]={getData:s,onProgress:Xs(this,ya)[ya](o),onComplete:Xs(this,va)[va](o),shouldUseMultipart:t},Xs(this,da)[da]){const t=r+n>e?e-r:n;Xs(this,ra)[ra][o].setAsUploaded=()=>{Xs(this,ra)[ra][o]=null,Xs(this,oa)[oa][o].uploaded=t}}}}else Xs(this,ra)[ra]=[{getData:()=>Xs(this,ia)[ia],onProgress:Xs(this,ya)[ya](0),onComplete:Xs(this,va)[va](0),shouldUseMultipart:t}];Xs(this,oa)[oa]=Xs(this,ra)[ra].map(()=>({uploaded:0}))}function Ea(){this.options.companionComm.uploadFile(Xs(this,sa)[sa],Xs(this,ra)[ra],Xs(this,na)[na].signal).then(Xs(this,ca)[ca],Xs(this,ha)[ha]),Xs(this,aa)[aa]=!0}function Pa(){this.options.companionComm.resumeUploadFile(Xs(this,sa)[sa],Xs(this,ra)[ra],Xs(this,na)[na].signal).then(Xs(this,ca)[ca],Xs(this,ha)[ha])}function Ta(){Xs(this,na)[na].abort(),this.options.companionComm.abortFileUpload(Xs(this,sa)[sa]).catch(e=>this.options.log(e))}function ka(e){if(null!=e&&e.aborted)throw Js("The operation was aborted",{cause:e.reason})}const xa=new TextEncoder,Ca={name:"HMAC",hash:"SHA-256"};function Oa(e){const t=new Uint8Array(e);let n="";for(let e=0;e<t.length;e++)n+=t[e].toString(16).padStart(2,"0");return n}async function ja(e,t){const{subtle:n}=globalThis.crypto;return n.sign(Ca,await async function(e){const{subtle:t}=globalThis.crypto;return t.importKey("raw","string"==typeof e?xa.encode(e):e,Ca,!1,["sign"])}(e),xa.encode(t))}async function Ra(e){let{accountKey:t,accountSecret:n,sessionToken:r,bucketName:o,Key:i,Region:s,expires:a,uploadId:l,partNumber:c}=e;const u="s3",d=`${o}.${u}.${s}.amazonaws.com`,h=`/${encodeURI(i).replace(/[;?:@&=+$,#!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}`,p="UNSIGNED-PAYLOAD",_=(new Date).toISOString().replace(/[-:]|\.\d+/g,""),f=_.slice(0,8),m=`${f}/${s}/${u}/aws4_request`,g=new URL(`https://${d}${h}`);g.searchParams.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),g.searchParams.set("X-Amz-Content-Sha256",p),g.searchParams.set("X-Amz-Credential",`${t}/${m}`),g.searchParams.set("X-Amz-Date",_),g.searchParams.set("X-Amz-Expires",a),g.searchParams.set("X-Amz-Security-Token",r),g.searchParams.set("X-Amz-SignedHeaders","host"),c&&g.searchParams.set("partNumber",c),l&&g.searchParams.set("uploadId",l),g.searchParams.set("x-id",c&&l?"UploadPart":"PutObject");const y=function(e){let{method:t="PUT",CanonicalUri:n="/",CanonicalQueryString:r="",SignedHeaders:o,HashedPayload:i}=e;const s=Object.keys(o).map(e=>e.toLowerCase()).sort();return[t,n,r,...s.map(e=>`${e}:${o[e]}`),"",s.join(";"),i].join("\n")}({CanonicalUri:h,CanonicalQueryString:g.search.slice(1),SignedHeaders:{host:d},HashedPayload:p}),v=["AWS4-HMAC-SHA256",_,m,Oa(await async function(e){const{subtle:t}=globalThis.crypto;return t.digest(Ca.hash,xa.encode(e))}(y))].join("\n"),w=await ja(`AWS4${n}`,f),b=await ja(w,s),S=await ja(b,u),E=await ja(S,"aws4_request"),P=Oa(await ja(E,v));return g.searchParams.set("X-Amz-Signature",P),g}function Aa(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var Na=0;function Fa(e){return"__private_"+Na+++"_"+e}function Ia(e){const t=new URL(e);return t.search="",t.hash="",t.href}var Ma=Fa("abortMultipartUpload"),Ua=Fa("cache"),La=Fa("createMultipartUpload"),za=Fa("fetchSignature"),Da=Fa("getUploadParameters"),Ba=Fa("listParts"),$a=Fa("previousRetryDelay"),qa=Fa("requests"),Wa=Fa("retryDelays"),Ha=Fa("sendCompletionRequest"),Va=Fa("setS3MultipartState"),Ka=Fa("uploadPartBytes"),Ya=Fa("getFile"),Ga=Fa("shouldRetry"),Ja=Fa("nonMultipartUpload");class Xa{constructor(e,t,n,r){Object.defineProperty(this,Ja,{value:Za}),Object.defineProperty(this,Ga,{value:Qa}),Object.defineProperty(this,Ma,{writable:!0,value:void 0}),Object.defineProperty(this,Ua,{writable:!0,value:new WeakMap}),Object.defineProperty(this,La,{writable:!0,value:void 0}),Object.defineProperty(this,za,{writable:!0,value:void 0}),Object.defineProperty(this,Da,{writable:!0,value:void 0}),Object.defineProperty(this,Ba,{writable:!0,value:void 0}),Object.defineProperty(this,$a,{writable:!0,value:void 0}),Object.defineProperty(this,qa,{writable:!0,value:void 0}),Object.defineProperty(this,Wa,{writable:!0,value:void 0}),Object.defineProperty(this,Ha,{writable:!0,value:void 0}),Object.defineProperty(this,Va,{writable:!0,value:void 0}),Object.defineProperty(this,Ka,{writable:!0,value:void 0}),Object.defineProperty(this,Ya,{writable:!0,value:void 0}),Aa(this,qa)[qa]=e,Aa(this,Va)[Va]=n,Aa(this,Ya)[Ya]=r,this.setOptions(t)}setOptions(e){const t=Aa(this,qa)[qa];var n;("abortMultipartUpload"in e&&(Aa(this,Ma)[Ma]=t.wrapPromiseFunction(e.abortMultipartUpload,{priority:1})),"createMultipartUpload"in e&&(Aa(this,La)[La]=t.wrapPromiseFunction(e.createMultipartUpload,{priority:-1})),"signPart"in e&&(Aa(this,za)[za]=t.wrapPromiseFunction(e.signPart)),"listParts"in e&&(Aa(this,Ba)[Ba]=t.wrapPromiseFunction(e.listParts)),"completeMultipartUpload"in e&&(Aa(this,Ha)[Ha]=t.wrapPromiseFunction(e.completeMultipartUpload,{priority:1})),"retryDelays"in e)&&(Aa(this,Wa)[Wa]=null!=(n=e.retryDelays)?n:[]);"uploadPartBytes"in e&&(Aa(this,Ka)[Ka]=t.wrapPromiseFunction(e.uploadPartBytes,{priority:1/0})),"getUploadParameters"in e&&(Aa(this,Da)[Da]=t.wrapPromiseFunction(e.getUploadParameters))}async getUploadId(e,t){let n;for(;null!=(n=Aa(this,Ua)[Ua].get(e.data));)try{return await n}catch{}const r=Aa(this,La)[La](Aa(this,Ya)[Ya](e),t),o=()=>{r.abort(t.reason),Aa(this,Ua)[Ua].delete(e.data)};return t.addEventListener("abort",o,{once:!0}),Aa(this,Ua)[Ua].set(e.data,r),r.then(async n=>{t.removeEventListener("abort",o),Aa(this,Va)[Va](e,n),Aa(this,Ua)[Ua].set(e.data,n)},()=>{t.removeEventListener("abort",o),Aa(this,Ua)[Ua].delete(e.data)}),r}async abortFileUpload(e){const t=Aa(this,Ua)[Ua].get(e.data);if(null==t)return;let n;Aa(this,Ua)[Ua].delete(e.data),Aa(this,Va)[Va](e,Object.create(null));try{n=await t}catch{return}await Aa(this,Ma)[Ma](Aa(this,Ya)[Ya](e),n)}async uploadFile(e,t,n){if(ka(n),1===t.length&&!t[0].shouldUseMultipart)return Aa(this,Ja)[Ja](e,t[0],n);const{uploadId:r,key:o}=await this.getUploadId(e,n);ka(n);try{const i=await Promise.all(t.map((t,r)=>this.uploadChunk(e,r+1,t,n)));return ka(n),await Aa(this,Ha)[Ha](Aa(this,Ya)[Ya](e),{key:o,uploadId:r,parts:i,signal:n},n).abortOn(n)}catch(t){throw(null==t?void 0:t.cause)!==ta&&"AbortError"!==(null==t?void 0:t.name)&&this.abortFileUpload(e),t}}restoreUploadFile(e,t){Aa(this,Ua)[Ua].set(e.data,t)}async resumeUploadFile(e,t,n){if(ka(n),1===t.length&&null!=t[0]&&!t[0].shouldUseMultipart)return Aa(this,Ja)[Ja](e,t[0],n);const{uploadId:r,key:o}=await this.getUploadId(e,n);ka(n);const i=await Aa(this,Ba)[Ba](Aa(this,Ya)[Ya](e),{uploadId:r,key:o,signal:n},n).abortOn(n);ka(n);const s=await Promise.all(t.map((t,r)=>{const o=r+1,s=i.find(e=>{let{PartNumber:t}=e;return t===o});return null==s?this.uploadChunk(e,o,t,n):(null==t||null==t.setAsUploaded||t.setAsUploaded(),{PartNumber:o,ETag:s.ETag})}));return ka(n),Aa(this,Ha)[Ha](Aa(this,Ya)[Ya](e),{key:o,uploadId:r,parts:s,signal:n},n).abortOn(n)}async uploadChunk(e,t,n,r){ka(r);const{uploadId:o,key:i}=await this.getUploadId(e,r),s=Aa(this,Wa)[Wa].values(),a=Aa(this,Wa)[Wa].values(),l=()=>{const e=s.next();return null==e||e.done?null:e.value};for(;;){ka(r);const s=n.getData(),{onProgress:c,onComplete:u}=n;let d;try{d=await Aa(this,za)[za](Aa(this,Ya)[Ya](e),{uploadId:o,key:i,partNumber:t,body:s,signal:r}).abortOn(r)}catch(e){const t=l();if(null==t||r.aborted)throw e;await new Promise(e=>setTimeout(e,t));continue}ka(r);try{return{PartNumber:t,...await Aa(this,Ka)[Ka]({signature:d,body:s,size:s.size,onProgress:c,onComplete:u,signal:r}).abortOn(r)}}catch(e){if(!await Aa(this,Ga)[Ga](e,a))throw e}}}}async function Qa(e,t){var n;const r=Aa(this,qa)[qa],o=null==e||null==(n=e.source)?void 0:n.status;if(null==o)return!1;if(403===o&&"Request has expired"===e.message){if(!r.isPaused){if(1===r.limit||null==Aa(this,$a)[$a]){const e=t.next();if(null==e||e.done)return!1;Aa(this,$a)[$a]=e.value}r.rateLimit(0),await new Promise(e=>setTimeout(e,Aa(this,$a)[$a]))}}else if(429===o){if(!r.isPaused){const e=t.next();if(null==e||e.done)return!1;r.rateLimit(e.value)}}else{if(o>400&&o<500&&409!==o)return!1;if("undefined"!=typeof navigator&&!1===navigator.onLine)r.isPaused||(r.pause(),window.addEventListener("online",()=>{r.resume()},{once:!0}));else{const e=t.next();if(null==e||e.done)return!1;await new Promise(t=>setTimeout(t,e.value))}}return!0}async function Za(e,t,n){const{method:r="POST",url:o,fields:i,headers:s}=await Aa(this,Da)[Da](Aa(this,Ya)[Ya](e),{signal:n}).abortOn(n);let a;const l=t.getData();if("POST"===r.toUpperCase()){const e=new FormData;Object.entries(i).forEach(t=>{let[n,r]=t;return e.set(n,r)}),e.set("file",l),a=e}else a=l;const{onProgress:c,onComplete:u}=t,d=await Aa(this,Ka)[Ka]({signature:{url:o,headers:s,method:r},body:a,size:l.size,onProgress:c,onComplete:u,signal:n}).abortOn(n);return"location"in d?d:{location:Ia(o),...d}}let el;function tl(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var nl=0;function rl(e){return"__private_"+nl+++"_"+e}function ol(e){if(null!=e&&e.error){const t=new Error(e.message);throw Object.assign(t,e.error),t}return e}function il(e){const t=e.Expiration;if(t){const e=Math.floor((new Date(t)-Date.now())/1e3);if(e>9)return e}}function sl(e){let{meta:t,allowedMetaFields:n,querify:r=!1}=e;const o=null!=n?n:Object.keys(t);return t?Object.fromEntries(o.filter(e=>null!=t[e]).map(e=>[r?`metadata[${e}]`:e,String(t[e])])):{}}const al={allowedMetaFields:null,limit:6,getTemporarySecurityCredentials:!1,shouldUseMultipart:e=>0!==e.size,retryDelays:[0,1e3,3e3,5e3],companionHeaders:{}};var ll=rl("companionCommunicationQueue"),cl=rl("client"),ul=rl("cachedTemporaryCredentials"),dl=rl("getTemporarySecurityCredentials"),hl=rl("setS3MultipartState"),pl=rl("getFile"),_l=rl("uploadLocalFile"),fl=rl("getCompanionClientArgs"),ml=rl("upload"),gl=rl("setCompanionHeaders"),yl=rl("setResumableUploadsCapability"),vl=rl("resetResumableCapability");el=Symbol.for("uppy test: getClient");class wl extends zi{constructor(e,t){var n;super(e,{...al,uploadPartBytes:wl.uploadPartBytes,createMultipartUpload:null,listParts:null,abortMultipartUpload:null,completeMultipartUpload:null,signPart:null,getUploadParameters:null,...t}),Object.defineProperty(this,fl,{value:El}),Object.defineProperty(this,_l,{value:Sl}),Object.defineProperty(this,dl,{value:bl}),Object.defineProperty(this,ll,{writable:!0,value:void 0}),Object.defineProperty(this,cl,{writable:!0,value:void 0}),Object.defineProperty(this,ul,{writable:!0,value:void 0}),Object.defineProperty(this,hl,{writable:!0,value:(e,t)=>{let{key:n,uploadId:r}=t;const o=this.uppy.getFile(e.id);null!=o&&this.uppy.setFileState(e.id,{s3Multipart:{...o.s3Multipart,key:n,uploadId:r}})}}),Object.defineProperty(this,pl,{writable:!0,value:e=>this.uppy.getFile(e.id)||e}),Object.defineProperty(this,ml,{writable:!0,value:async e=>{if(0===e.length)return;const t=function(e){return e.filter(e=>!(e=>"error"in e&&!!e.error)(e))}(this.uppy.getFilesByIds(e)),n=function(e){return e.filter(e=>{var t;return!(null!=(t=e.progress)&&t.uploadStarted&&e.isRestored)})}(t);this.uppy.emit("upload-start",n);const r=t.map(e=>{if(e.isRemote){const t=()=>this.requests;tl(this,yl)[yl](!1);const n=new AbortController,r=t=>{t.id===e.id&&n.abort()};this.uppy.on("file-removed",r);const o=this.uppy.getRequestClientForFile(e).uploadRemoteFile(e,tl(this,fl)[fl](e),{signal:n.signal,getQueue:t});return this.requests.wrapSyncFunction(()=>{this.uppy.off("file-removed",r)},{priority:-1})(),o}return tl(this,_l)[_l](e)}),o=await Promise.all(r);return tl(this,yl)[yl](!0),o}}),Object.defineProperty(this,gl,{writable:!0,value:()=>{tl(this,cl)[cl].setCompanionHeaders(this.opts.companionHeaders)}}),Object.defineProperty(this,yl,{writable:!0,value:e=>{const{capabilities:t}=this.uppy.getState();this.uppy.setState({capabilities:{...t,resumableUploads:e}})}}),Object.defineProperty(this,vl,{writable:!0,value:()=>{tl(this,yl)[yl](!0)}}),this.type="uploader",this.id=this.opts.id||"AwsS3Multipart",this.title="AWS S3 Multipart",tl(this,cl)[cl]=new ms(e,t);const r={createMultipartUpload:this.createMultipartUpload,listParts:this.listParts,abortMultipartUpload:this.abortMultipartUpload,completeMultipartUpload:this.completeMultipartUpload,signPart:null!=t&&t.getTemporarySecurityCredentials?this.createSignedURL:this.signPart,getUploadParameters:null!=t&&t.getTemporarySecurityCredentials?this.createSignedURL:this.getUploadParameters};for(const e of Object.keys(r))null==this.opts[e]&&(this.opts[e]=r[e].bind(this));null!=(null==t?void 0:t.prepareUploadParts)&&null==t.signPart&&(this.opts.signPart=async(e,n)=>{let{uploadId:r,key:o,partNumber:i,body:s,signal:a}=n;const{presignedUrls:l,headers:c}=await t.prepareUploadParts(e,{uploadId:r,key:o,parts:[{number:i,chunk:s}],signal:a});return{url:null==l?void 0:l[i],headers:null==c?void 0:c[i]}}),this.requests=null!=(n=this.opts.rateLimitedQueue)?n:new qs(this.opts.limit),tl(this,ll)[ll]=new Xa(this.requests,this.opts,tl(this,hl)[hl],tl(this,pl)[pl]),this.uploaders=Object.create(null),this.uploaderEvents=Object.create(null),this.uploaderSockets=Object.create(null)}[el](){return tl(this,cl)[cl]}setOptions(e){tl(this,ll)[ll].setOptions(e),super.setOptions(e),tl(this,gl)[gl]()}resetUploaderReferences(e,t){this.uploaders[e]&&(this.uploaders[e].abort({really:(null==t?void 0:t.abort)||!1}),this.uploaders[e]=null),this.uploaderEvents[e]&&(this.uploaderEvents[e].remove(),this.uploaderEvents[e]=null),this.uploaderSockets[e]&&(this.uploaderSockets[e].close(),this.uploaderSockets[e]=null)}assertHost(e){if(!this.opts.companionUrl)throw new Error(`Expected a \`companionUrl\` option containing a Companion address, or if you are not using Companion, a custom \`${e}\` implementation.`)}createMultipartUpload(e,t){this.assertHost("createMultipartUpload"),ka(t);const n=sl({meta:e.meta,allowedMetaFields:this.opts.allowedMetaFields});return tl(this,cl)[cl].post("s3/multipart",{filename:e.name,type:e.type,metadata:n},{signal:t}).then(ol)}listParts(e,t,n){let{key:r,uploadId:o,signal:i}=t;null!=i||(i=n),this.assertHost("listParts"),ka(i);const s=encodeURIComponent(r);return tl(this,cl)[cl].get(`s3/multipart/${o}?key=${s}`,{signal:i}).then(ol)}completeMultipartUpload(e,t,n){let{key:r,uploadId:o,parts:i,signal:s}=t;null!=s||(s=n),this.assertHost("completeMultipartUpload"),ka(s);const a=encodeURIComponent(r),l=encodeURIComponent(o);return tl(this,cl)[cl].post(`s3/multipart/${l}/complete?key=${a}`,{parts:i},{signal:s}).then(ol)}async createSignedURL(e,t){const n=await tl(this,dl)[dl](t),r=il(n.credentials)||604800,{uploadId:o,key:i,partNumber:s}=t;return{method:"PUT",expires:r,fields:{},url:`${await Ra({accountKey:n.credentials.AccessKeyId,accountSecret:n.credentials.SecretAccessKey,sessionToken:n.credentials.SessionToken,expires:r,bucketName:n.bucket,Region:n.region,Key:null!=i?i:`${crypto.randomUUID()}-${e.name}`,uploadId:o,partNumber:s})}`,headers:{"Content-Type":e.type}}}signPart(e,t){let{uploadId:n,key:r,partNumber:o,signal:i}=t;if(this.assertHost("signPart"),ka(i),null==n||null==r||null==o)throw new Error("Cannot sign without a key, an uploadId, and a partNumber");const s=encodeURIComponent(r);return tl(this,cl)[cl].get(`s3/multipart/${n}/${o}?key=${s}`,{signal:i}).then(ol)}abortMultipartUpload(e,t,n){let{key:r,uploadId:o,signal:i}=t;null!=i||(i=n),this.assertHost("abortMultipartUpload");const s=encodeURIComponent(r),a=encodeURIComponent(o);return tl(this,cl)[cl].delete(`s3/multipart/${a}?key=${s}`,void 0,{signal:i}).then(ol)}getUploadParameters(e,t){const{meta:n}=e,{type:r,name:o}=n,i=sl({meta:n,allowedMetaFields:this.opts.allowedMetaFields,querify:!0}),s=new URLSearchParams({filename:o,type:r,...i});return tl(this,cl)[cl].get(`s3/params?${s}`,t)}static async uploadPartBytes(e){let{signature:{url:t,expires:n,headers:r,method:o="PUT"},body:i,size:s=i.size,onProgress:a,onComplete:l,signal:c}=e;if(ka(c),null==t)throw new Error("Cannot upload to an undefined URL");return new Promise((e,u)=>{const d=new XMLHttpRequest;function h(){d.abort()}function p(){null==c||c.removeEventListener("abort",h)}d.open(o,t,!0),r&&Object.keys(r).forEach(e=>{d.setRequestHeader(e,r[e])}),d.responseType="text","number"==typeof n&&(d.timeout=1e3*n),null==c||c.addEventListener("abort",h),d.upload.addEventListener("progress",e=>{a(e)}),d.addEventListener("abort",()=>{p(),u(Js())}),d.addEventListener("timeout",()=>{p();const e=new Error("Request has expired");e.source={status:403},u(e)}),d.addEventListener("load",()=>{if(p(),403===d.status&&d.responseText.includes("<Message>Request has expired</Message>")){const e=new Error("Request has expired");return e.source=d,void u(e)}if(d.status<200||d.status>=300){const e=new Error("Non 2xx");return e.source=d,void u(e)}null==a||a({loaded:s,lengthComputable:!0});const t=d.getAllResponseHeaders().trim().split(/[\r\n]+/),n={__proto__:null};for(const e of t){const t=e.split(": "),r=t.shift(),o=t.join(": ");n[r]=o}const{etag:r,location:i}=n;"POST"===o.toUpperCase()&&null===i&&console.warn("AwsS3/Multipart: Could not read the Location header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3-multipart#S3-Bucket-Configuration for instructions."),null!==r?(null==l||l(r),e({...n,ETag:r})):u(new Error("AwsS3/Multipart: Could not read the ETag header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3-multipart#S3-Bucket-Configuration for instructions."))}),d.addEventListener("error",e=>{p();const t=new Error("Unknown error");t.source=e.target,u(t)}),d.send(i)})}install(){tl(this,yl)[yl](!0),this.uppy.addPreProcessor(tl(this,gl)[gl]),this.uppy.addUploader(tl(this,ml)[ml]),this.uppy.on("cancel-all",tl(this,vl)[vl])}uninstall(){this.uppy.removePreProcessor(tl(this,gl)[gl]),this.uppy.removeUploader(tl(this,ml)[ml]),this.uppy.off("cancel-all",tl(this,vl)[vl])}}async function bl(e){return ka(null==e?void 0:e.signal),null==tl(this,ul)[ul]&&(!0===this.opts.getTemporarySecurityCredentials?(this.assertHost("getTemporarySecurityCredentials"),tl(this,ul)[ul]=tl(this,cl)[cl].get("s3/sts",e).then(ol)):tl(this,ul)[ul]=this.opts.getTemporarySecurityCredentials(e),tl(this,ul)[ul]=await tl(this,ul)[ul],setTimeout(()=>{tl(this,ul)[ul]=null},500*(il(tl(this,ul)[ul].credentials)||0))),tl(this,ul)[ul]}function Sl(e){var t=this;return new Promise((n,r)=>{const o=new ba(e.data,{companionComm:tl(this,ll)[ll],log:function(){return t.uppy.log(...arguments)},getChunkSize:this.opts.getChunkSize?this.opts.getChunkSize.bind(this):null,onProgress:(t,n)=>{this.uppy.emit("upload-progress",this.uppy.getFile(e.id),{uploader:this,bytesUploaded:t,bytesTotal:n})},onError:t=>{this.uppy.log(t),this.uppy.emit("upload-error",e,t),this.resetUploaderReferences(e.id),r(t)},onSuccess:t=>{const r={body:{...t},status:200,uploadURL:t.location};this.resetUploaderReferences(e.id),this.uppy.emit("upload-success",tl(this,pl)[pl](e),r),t.location&&this.uppy.log(`Download ${e.name} from ${t.location}`),n()},onPartComplete:t=>{this.uppy.emit("s3-multipart:part-uploaded",tl(this,pl)[pl](e),t)},file:e,shouldUseMultipart:this.opts.shouldUseMultipart,...e.s3Multipart});this.uploaders[e.id]=o;const i=new Ps(this.uppy);this.uploaderEvents[e.id]=i,i.onFileRemove(e.id,t=>{o.abort(),this.resetUploaderReferences(e.id,{abort:!0}),n(`upload ${t} was removed`)}),i.onCancelAll(e.id,t=>{"user"===(null==t?void 0:t.reason)&&(o.abort(),this.resetUploaderReferences(e.id,{abort:!0})),n(`upload ${e.id} was canceled`)}),i.onFilePause(e.id,e=>{e?o.pause():o.start()}),i.onPauseAll(e.id,()=>{o.pause()}),i.onResumeAll(e.id,()=>{o.start()}),o.start()})}function El(e){var t;return{...null==(t=e.remote)?void 0:t.body,protocol:"s3-multipart",size:e.data.size,metadata:e.meta}}wl.VERSION="3.12.0";var Pl,Tl,kl,xl,Cl,Ol=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function s(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){e.done?o(e.value):function(e){return e instanceof n?e:new n(function(t){t(e)})}(e.value).then(s,a)}l((r=r.apply(e,t||[])).next())})},jl=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},Rl=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)},Al=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n};class Nl{constructor(e,t=tr.PROD){Pl.add(this),Tl.set(this,void 0),kl.set(this,void 0),xl.set(this,void 0),jl(this,kl,e,"f"),jl(this,xl,t,"f")}uploadFileFrontend(e){return Ol(this,arguments,void 0,function*({file:e,arrayMetaData:t,scanId:n,email:r,callBack:o}){if(!or(e,t,n,r))throw new Error(Xn);if(!cr(r.trim()))throw new Error(Zn);if(!ir(t))throw new Error(Qn);return t=ar(t,n,r),Rl(this,Pl,"m",Cl).call(this,{callBack:o,arrayMetaData:t,scanId:n,email:r,file:e})})}faceScanFileUploader(e){return Ol(this,arguments,void 0,function*({file:e,arrayMetaData:t,objectKey:n,email:r,callBack:o}){if(!or(e,t,n,r))throw new Error(Xn);if(!cr(r.trim()))throw new Error(Zn);if(!sr(t,Jn))throw new Error(Qn);return t.push({email:r}),Rl(this,Pl,"m",Cl).call(this,{callBack:o,arrayMetaData:t,objectKey:n,email:r,file:e})})}uploadFile(e){return Ol(this,arguments,void 0,function*({file:e,arrayMetaData:t,scanId:n,email:r}){if(!or(e,t,n,r))throw new Error(Xn);if(!cr(r.trim()))throw new Error(Zn);if(!ir(t))throw new Error(Qn);return t=ar(t,n,r),new Promise((n,r)=>Ol(this,void 0,void 0,function*(){var o;try{const r=yield rr({path:kn,apiKey:Rl(this,kl,"f"),urlType:Rl(this,xl,"f"),body:{objectKey:e.name,contentType:e.type,objectMetadata:t},throwError:!0}),i=function(e,t=5242880){const n=e.size,r=[];let o=0;for(;o<n;)r.push(e.slice(o,o+t)),o+=t;return r}(e),s=[];for(let t=0;t<i.length;t++){const n=yield rr({path:Cn,apiKey:Rl(this,kl,"f"),urlType:Rl(this,xl,"f"),body:{objectKey:null==r?void 0:r.key,uploadId:null==r?void 0:r.uploadId,partNumber:t+1},throwError:!0}),a=yield ln.put(null==n?void 0:n.url,i[t],{headers:{"Content-Type":e.type,"X-Api-Key":Rl(this,kl,"f")}});s.push({PartNumber:t+1,ETag:null===(o=null==a?void 0:a.headers)||void 0===o?void 0:o.etag})}const a=yield rr({path:xn,apiKey:Rl(this,kl,"f"),urlType:Rl(this,xl,"f"),body:{uploadId:null==r?void 0:r.uploadId,objectKey:null==r?void 0:r.key,parts:s,originalFileName:e.name},throwError:!0});n({message:"successfully uploaded",data:a})}catch(e){r(e)}}))})}setDeviceInfo(e){return Ol(this,void 0,void 0,function*(){const{scanId:t}=e,n=Al(e,["scanId"]);if(!1===or(t))throw new Error(Xn);return ln.post(`${lr({urlName:On,urlType:Rl(this,xl,"f")})}${Kn}/${t}`,{device_info:Object.assign({},n)},{headers:{"X-Api-Key":Rl(this,kl,"f")}})})}}Tl=new WeakMap,kl=new WeakMap,xl=new WeakMap,Pl=new WeakSet,Cl=function({callBack:e,arrayMetaData:t,scanId:n,email:r,file:o,objectKey:i}){return new Promise((s,a)=>{Rl(this,Tl,"f")&&Rl(this,Tl,"f").close(),jl(this,Tl,new ki({autoProceed:!0}),"f"),Rl(this,Tl,"f").use(wl,{limit:10,retryDelays:[0,1e3,3e3,5e3],companionUrl:lr({urlName:On,urlType:Rl(this,xl,"f")}),getChunkSize:()=>er,createMultipartUpload:o=>{const s=Math.ceil(o.size/er);null==e||e({eventName:"uploading_start",message:`File ${o.name} will be divided into ${s} chunks`,scanId:n,email:r,objectKey:i});const a=`${n||i}.${o.extension}`;return rr({path:kn,apiKey:Rl(this,kl,"f"),urlType:Rl(this,xl,"f"),body:{objectKey:a,contentType:o.type,objectMetadata:t}})},completeMultipartUpload:(t,{uploadId:o,key:s,parts:a})=>(null==e||e({eventName:"uploading_complete_start",message:`${a.length} chunks of file, uploaded`,scanId:n,email:r,objectKey:i}),rr({path:xn,apiKey:Rl(this,kl,"f"),urlType:Rl(this,xl,"f"),body:{uploadId:o,objectKey:s,parts:a,originalFileName:t.name}}).then(t=>(null==e||e({eventName:"uploading_complete_end",message:"Multipart upload completed successfully",scanId:n,email:r,objectKey:i}),t))),signPart:(e,t)=>rr({path:Cn,urlType:Rl(this,xl,"f"),apiKey:Rl(this,kl,"f"),body:{objectKey:t.key,uploadId:t.uploadId,partNumber:t.partNumber}})}),Rl(this,Tl,"f").addFile({source:"manual",name:o.name,type:o.type,data:o}),Rl(this,Tl,"f").on("upload-error",(e,t,n)=>{t.isNetworkError?Rl(this,Tl,"f").retryUpload(e.id):a(t)}),Rl(this,Tl,"f").on("upload-success",()=>{s({message:"file uploaded successfully"})}),Rl(this,Tl,"f").on("complete",e=>{Rl(this,Tl,"f")&&Rl(this,Tl,"f").close()})})};var Fl,Il,Ml,Ul,Ll,zl,Dl,Bl,$l,ql,Wl,Hl,Vl=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function s(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){e.done?o(e.value):function(e){return e instanceof n?e:new n(function(t){t(e)})}(e.value).then(s,a)}l((r=r.apply(e,t||[])).next())})},Kl=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},Yl=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class Gl{constructor(e,t=tr.PROD){Fl.add(this),Il.set(this,{}),Ml.set(this,{}),Ul.set(this,{}),Ll.set(this,{}),zl.set(this,void 0),Dl.set(this,void 0),Kl(this,zl,e,"f"),Kl(this,Dl,t,"f")}getMeasurementResult(e){if(!or(e))throw new Error(Xn);const t=`${lr({urlName:On,urlType:Yl(this,Dl,"f")})}/measurements?scanId=${e}`;return ln.get(t,{headers:{"X-Api-Key":Yl(this,zl,"f")}})}getMeasurementRecommendation({scanId:e,shopDomain:t,productName:n}){if(!or(e,t,n))throw new Error(Xn);return ln.get(`${lr({urlName:On,urlType:Yl(this,Dl,"f")})}${Hn}/scan/${e}/shop/${t}/product/${n}`,{headers:{"X-Api-Key":Yl(this,zl,"f")}})}handleMeasurementSocket(e){const{scanId:t,onError:n,onSuccess:r,onClose:o,onOpen:i}=e;if(!or(t))throw new Error(Xn);Yl(this,Fl,"m",Hl).call(this,{onOpen:i,scanId:t,onSuccess:r,onError:n,onClose:o,paramsKey:"scanId",isFallback:!0,delay:5e3})}handlFaceScaneSocket(e){const{faceScanId:t,onError:n,onSuccess:r,onClose:o,onOpen:i}=e;if(!or(t))throw new Error(Xn);Yl(this,Fl,"m",Hl).call(this,{onOpen:i,faceScanId:t,onSuccess:r,onError:n,onClose:o,paramsKey:"faceScanId",isFallback:!1,delay:1e3})}}Il=new WeakMap,Ml=new WeakMap,Ul=new WeakMap,Ll=new WeakMap,zl=new WeakMap,Dl=new WeakMap,Fl=new WeakSet,Bl=function(e){var t;null===(t=Yl(this,Il,"f")[e])||void 0===t||t.close(),Yl(this,Il,"f")[e]=null,Yl(this,Ml,"f")[e]&&(clearTimeout(Yl(this,Ml,"f")[e]),Yl(this,Ml,"f")[e]=null)},$l=function(e,t){const{scanId:n,onSuccess:r,onError:o}=e;Yl(this,Ll,"f")[t]=1,Yl(this,Ml,"f")[t]=setTimeout(()=>{Yl(this,Fl,"m",ql).call(this,{scanId:n,onSuccess:r,onError:o},t),Yl(this,Fl,"m",Bl).call(this,t)},9e4)},ql=function(e,t){const{scanId:n,onSuccess:r,onError:o}=e;Yl(this,Ul,"f")[t]&&clearTimeout(Yl(this,Ul,"f")[t]),Yl(this,Ul,"f")[t]=setTimeout(()=>{Yl(this,Fl,"m",Wl).call(this,{scanId:n,onSuccess:r,onError:o},t)},5e3*(Yl(this,Ll,"f")[t]||1))},Wl=function(e,t){return Vl(this,void 0,void 0,function*(){var n;const{scanId:r,onSuccess:o,onError:i}=e;try{const e=yield this.getMeasurementResult(r);(null==e?void 0:e.data)&&!0===(null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.isMeasured)?(null==o||o(e.data),clearInterval(Yl(this,Ul,"f")[t])):(Yl(this,Ll,"f")[t]||1)<8?(Yl(this,Ll,"f")[t]=(Yl(this,Ll,"f")[t]||1)+1,Yl(this,Fl,"m",ql).call(this,{scanId:r,onSuccess:o,onError:i},t)):(Yl(this,Ll,"f")[t]=1,clearInterval(Yl(this,Ul,"f")[t]),null==i||i({scanStatus:"failed",message:"Scan not found",isMeasured:!1}))}catch(e){clearInterval(Yl(this,Ul,"f")[t]),null==i||i(e)}})},Hl=function({onOpen:e,isFallback:t,scanId:n,onSuccess:r,onError:o,onClose:i,paramsKey:s,faceScanId:a,delay:l}){const c=t?`measurement-${n}`:`faceScan-${a}`;setTimeout(()=>{Yl(this,Fl,"m",Bl).call(this,c);const l=`${lr({urlName:jn,urlType:Yl(this,Dl,"f")})}${Wn}?${s}=${n||a}`,u=new WebSocket(l);Yl(this,Il,"f")[c]=u,u.onopen=()=>{null==e||e(),t&&n&&Yl(this,Fl,"m",$l).call(this,{scanId:n,onSuccess:r,onError:o},c)},u.onmessage=e=>{const t=JSON.parse(e.data);200===(null==t?void 0:t.code)&&"success"===(null==t?void 0:t.scanStatus)?null==r||r(t):(clearTimeout(Yl(this,Ml,"f")[c]),null==o||o(t)),200===(null==t?void 0:t.code)&&"success"===(null==t?void 0:t.scanStatus)&&"final"===(null==t?void 0:t.resultType)&&clearTimeout(Yl(this,Ml,"f")[c])},u.onclose=()=>null==i?void 0:i(),u.onerror=()=>{t||null==o||o(new Error("An error occurred in the WebSocket connection."))}},l)};const Jl=Object.create(null);Jl.open="0",Jl.close="1",Jl.ping="2",Jl.pong="3",Jl.message="4",Jl.upgrade="5",Jl.noop="6";const Xl=Object.create(null);Object.keys(Jl).forEach(e=>{Xl[Jl[e]]=e});const Ql={type:"error",data:"parser error"},Zl="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),ec="function"==typeof ArrayBuffer,tc=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,nc=({type:e,data:t},n,r)=>Zl&&t instanceof Blob?n?r(t):rc(t,r):ec&&(t instanceof ArrayBuffer||tc(t))?n?r(t):rc(new Blob([t]),r):r(Jl[e]+(t||"")),rc=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function oc(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ic;const sc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ac="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)ac[sc.charCodeAt(e)]=e;const lc="function"==typeof ArrayBuffer,cc=(e,t)=>{if("string"!=typeof e)return{type:"message",data:dc(e,t)};const n=e.charAt(0);if("b"===n)return{type:"message",data:uc(e.substring(1),t)};return Xl[n]?e.length>1?{type:Xl[n],data:e.substring(1)}:{type:Xl[n]}:Ql},uc=(e,t)=>{if(lc){const n=(e=>{let t,n,r,o,i,s=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);const c=new ArrayBuffer(s),u=new Uint8Array(c);for(t=0;t<a;t+=4)n=ac[e.charCodeAt(t)],r=ac[e.charCodeAt(t+1)],o=ac[e.charCodeAt(t+2)],i=ac[e.charCodeAt(t+3)],u[l++]=n<<2|r>>4,u[l++]=(15&r)<<4|o>>2,u[l++]=(3&o)<<6|63&i;return c})(e);return dc(n,t)}return{base64:!0,data:e}},dc=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,hc=String.fromCharCode(30);function pc(){return new TransformStream({transform(e,t){!function(e,t){Zl&&e.data instanceof Blob?e.data.arrayBuffer().then(oc).then(t):ec&&(e.data instanceof ArrayBuffer||tc(e.data))?t(oc(e.data)):nc(e,!1,e=>{ic||(ic=new TextEncoder),t(ic.encode(e))})}(e,n=>{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const e=new DataView(o.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{o=new Uint8Array(9);const e=new DataView(o.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let _c;function fc(e){return e.reduce((e,t)=>e+t.length,0)}function mc(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;o<t;o++)n[o]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function gc(e){if(e)return function(e){for(var t in gc.prototype)e[t]=gc.prototype[t];return e}(e)}gc.prototype.on=gc.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},gc.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},gc.prototype.off=gc.prototype.removeListener=gc.prototype.removeAllListeners=gc.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;o<r.length;o++)if((n=r[o])===t||n.fn===t){r.splice(o,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},gc.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var o=(n=n.slice(0)).length;r<o;++r)n[r].apply(this,t)}return this},gc.prototype.emitReserved=gc.prototype.emit,gc.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},gc.prototype.hasListeners=function(e){return!!this.listeners(e).length};const yc="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),vc="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function wc(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const bc=vc.setTimeout,Sc=vc.clearTimeout;function Ec(e,t){t.useNativeTimers?(e.setTimeoutFn=bc.bind(vc),e.clearTimeoutFn=Sc.bind(vc)):(e.setTimeoutFn=vc.setTimeout.bind(vc),e.clearTimeoutFn=vc.clearTimeout.bind(vc))}function Pc(e){return"string"==typeof e?function(e){let t=0,n=0;for(let r=0,o=e.length;r<o;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}function Tc(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class kc extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class xc extends gc{constructor(e){super(),this.writable=!1,Ec(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new kc(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=cc(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class Cc extends xc{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(hc),r=[];for(let e=0;e<n.length;e++){const o=cc(n[e],t);if(r.push(o),"error"===o.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((e,i)=>{nc(e,!1,e=>{r[i]=e,++o===n&&t(r.join(hc))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Tc()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let Oc=!1;try{Oc="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}const jc=Oc;function Rc(){}class Ac extends Cc{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class Nc extends gc{constructor(e,t,n){super(),this.createRequest=e,Ec(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;const t=wc(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(e){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(e){return void this.setTimeoutFn(()=>{this._onError(e)},0)}"undefined"!=typeof document&&(this._index=Nc.requestsCount++,Nc.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Rc,e)try{this._xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Nc.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(Nc.requestsCount=0,Nc.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Fc);else if("function"==typeof addEventListener){addEventListener("onpagehide"in vc?"pagehide":"unload",Fc,!1)}function Fc(){for(let e in Nc.requests)Nc.requests.hasOwnProperty(e)&&Nc.requests[e].abort()}const Ic=function(){const e=Mc({xdomain:!1});return e&&null!==e.responseType}();function Mc(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||jc))return new XMLHttpRequest}catch(e){}if(!t)try{return new(vc[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}const Uc="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Lc extends xc{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Uc?{}:wc(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;nc(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(e){}r&&yc(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Tc()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const zc=vc.WebSocket||vc.MozWebSocket;const Dc={websocket:class extends Lc{createSocket(e,t,n){return Uc?new zc(e,t,n):t?new zc(e,t):new zc(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends xc{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){_c||(_c=new TextDecoder);const n=[];let r=0,o=-1,i=!1;return new TransformStream({transform(s,a){for(n.push(s);;){if(0===r){if(fc(n)<1)break;const e=mc(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(fc(n)<2)break;const e=mc(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(fc(n)<8)break;const e=mc(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){a.enqueue(Ql);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(fc(n)<o)break;const e=mc(n,o);a.enqueue(cc(i?e:_c.decode(e),t)),r=0}if(0===o||o>e){a.enqueue(Ql);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=pc();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const o=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),o())}).catch(e=>{})};o();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this._writer.write(i).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&yc(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Ac{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Ic&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Nc(Mc,this.uri(),e)}}},Bc=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,$c=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function qc(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");-1!=n&&-1!=r&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=Bc.exec(e||""),i={},s=14;for(;s--;)i[$c[s]]=o[s]||"";return-1!=n&&-1!=r&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||r.splice(0,1);"/"==t.slice(-1)&&r.splice(r.length-1,1);return r}(0,i.path),i.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}(0,i.query),i}const Wc="function"==typeof addEventListener&&"function"==typeof removeEventListener,Hc=[];Wc&&addEventListener("offline",()=>{Hc.forEach(e=>e())},!1);class Vc extends gc{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=qc(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=qc(t.host).host);Ec(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,r=n.length;e<r;e++){let r=n[e].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}(this.opts.query)),Wc&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Hc.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Vc.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Vc.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=Pc(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,yc(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const o={type:e,data:t,options:n};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Vc.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Wc&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Hc.indexOf(this._offlineEventListener);-1!==e&&Hc.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Vc.protocol=4;class Kc extends Vc{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Vc.priorWebsocketSuccess=!1;const r=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Vc.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function o(){n||(n=!0,c(),t.close(),t=null)}const i=e=>{const n=new Error("probe error: "+e);n.transport=t.name,o(),this.emitReserved("upgradeError",n)};function s(){i("transport closed")}function a(){i("socket closed")}function l(e){t&&e.name!==t.name&&o()}const c=()=>{t.removeListener("open",r),t.removeListener("error",i),t.removeListener("close",s),this.off("close",a),this.off("upgrading",l)};t.once("open",r),t.once("error",i),t.once("close",s),this.once("close",a),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let Yc=class extends Kc{constructor(e,t={}){const n="object"==typeof e?e:t;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(e=>Dc[e]).filter(e=>!!e)),super(e,n)}};const Gc="function"==typeof ArrayBuffer,Jc=Object.prototype.toString,Xc="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Jc.call(Blob),Qc="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Jc.call(File);function Zc(e){return Gc&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Xc&&e instanceof Blob||Qc&&e instanceof File}function eu(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(eu(e[t]))return!0;return!1}if(Zc(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return eu(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&eu(e[t]))return!0;return!1}function tu(e){const t=[],n=e.data,r=e;return r.data=nu(n,t),r.attachments=t.length,{packet:r,buffers:t}}function nu(e,t){if(!e)return e;if(Zc(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=nu(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=nu(e[r],t));return n}return e}function ru(e,t){return e.data=ou(e.data,t),delete e.attachments,e}function ou(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=ou(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ou(e[n],t));return e}const iu=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var su;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(su||(su={}));function au(e){return"[object Object]"===Object.prototype.toString.call(e)}class lu extends gc{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===su.BINARY_EVENT;n||t.type===su.BINARY_ACK?(t.type=n?su.EVENT:su.ACK,this.reconstructor=new cu(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Zc(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===su[n.type])throw new Error("unknown packet type "+n.type);if(n.type===su.BINARY_EVENT||n.type===su.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const o=e.substring(r,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(o)}if("/"===e.charAt(t+1)){const r=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}n.nsp=e.substring(r,t)}else n.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!lu.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case su.CONNECT:return au(t);case su.DISCONNECT:return void 0===t;case su.CONNECT_ERROR:return"string"==typeof t||au(t);case su.EVENT:case su.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===iu.indexOf(t[0]));case su.ACK:case su.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class cu{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=ru(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var uu=Object.freeze({__proto__:null,Decoder:lu,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==su.EVENT&&e.type!==su.ACK||!eu(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===su.EVENT?su.BINARY_EVENT:su.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==su.BINARY_EVENT&&e.type!==su.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=tu(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return su},protocol:5});function du(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const hu=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class pu extends gc{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[du(e,"open",this.onopen.bind(this)),du(e,"packet",this.onpacket.bind(this)),du(e,"error",this.onerror.bind(this)),du(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,r,o;if(hu.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:su.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),i.id=e}const s=null===(r=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===r?void 0:r.writable,a=this.connected&&!(null===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const o=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r),i=(...e)=>{this.io.clearTimeoutFn(o),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{const o=(e,t)=>e?r(e):n(t);o.withError=!0,t.push(o),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>{if(n!==this._queue[0])return;return null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:su.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case su.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case su.EVENT:case su.BINARY_EVENT:this.onevent(e);break;case su.ACK:case su.BINARY_ACK:this.onack(e);break;case su.DISCONNECT:this.ondisconnect();break;case su.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,t.packet({type:su.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:su.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function _u(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}_u.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},_u.prototype.reset=function(){this.attempts=0},_u.prototype.setMin=function(e){this.ms=e},_u.prototype.setMax=function(e){this.max=e},_u.prototype.setJitter=function(e){this.jitter=e};class fu extends gc{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,Ec(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new _u({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||uu;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Yc(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=du(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=du(t,"error",o);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{r(),o(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(du(e,"ping",this.onping.bind(this)),du(e,"data",this.ondata.bind(this)),du(e,"error",this.onerror.bind(this)),du(e,"close",this.onclose.bind(this)),du(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){yc(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new pu(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const mu={};function gu(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),r=qc(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const o=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port+t,r.href=r.protocol+"://"+o+(n&&n.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=mu[o]&&i in mu[o].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new fu(r,t):(mu[o]||(mu[o]=new fu(r,t)),a=mu[o]),n.query&&!t.query&&(t.query=n.queryKey),a.socket(n.path,t)}Object.assign(gu,{Manager:fu,Socket:pu,io:gu,connect:gu});var yu,vu,wu,bu=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},Su=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class Eu{constructor(e,t=tr.PROD){yu.set(this,null),vu.set(this,void 0),wu.set(this,void 0),bu(this,vu,e,"f"),bu(this,wu,t,"f")}connect(){return new Promise((e,t)=>{bu(this,yu,gu(lr({urlName:"APP_POSE_DETECTION_WEBSOCKET_URL",urlType:Su(this,wu,"f")})),"f"),Su(this,yu,"f").on("connect",()=>{var n;const r=null===(n=Su(this,yu,"f"))||void 0===n?void 0:n.id;r?e(r):t("Failed to obtain socket ID.")}),Su(this,yu,"f").on("connect_error",e=>{t(e)})})}videoEmit({image:e,scanId:t}){if(!Su(this,yu,"f"))throw new Error("Socket is not connected");Su(this,yu,"f").emit("video",{image:e,user_unique_key:t})}disconnect(){var e;null===(e=Su(this,yu,"f"))||void 0===e||e.disconnect()}poseStatus(e){if(!Su(this,yu,"f"))throw new Error("Socket is not connected");Su(this,yu,"f").on("pose_status",t=>{null==e||e(t)})}connected(){var e;return!!(null===(e=Su(this,yu,"f"))||void 0===e?void 0:e.connected)}}yu=new WeakMap,vu=new WeakMap,wu=new WeakMap;var Pu,Tu,ku,xu,Cu,Ou,ju,Ru,Au,Nu,Fu=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function s(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){e.done?o(e.value):function(e){return e instanceof n?e:new n(function(t){t(e)})}(e.value).then(s,a)}l((r=r.apply(e,t||[])).next())})},Iu=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},Mu=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class Uu{constructor(e,t=tr.PROD){Pu.add(this),Tu.set(this,new Map),ku.set(this,new Map),xu.set(this,void 0),Cu.set(this,void 0),Ru.set(this,e=>{if(e){const t=Mu(this,Tu,"f").get(e),n=Mu(this,ku,"f").get(e);null==t||t.close(),n&&clearTimeout(n),Mu(this,Tu,"f").delete(e),Mu(this,ku,"f").delete(e)}else Mu(this,Tu,"f").forEach(e=>e.close()),Mu(this,ku,"f").forEach(e=>clearTimeout(e)),Mu(this,Tu,"f").clear(),Mu(this,ku,"f").clear()}),Au.set(this,({onSuccess:e,onError:t,tryonId:n})=>{const r=setTimeout(()=>{Mu(this,Nu,"f").call(this,{onSuccess:e,onError:t,tryonId:n}),Mu(this,Ru,"f").call(this,n)},3e5);Mu(this,ku,"f").set(n,r)}),this.handleTryOnWebSocket=({tryonId:e,onError:t,onSuccess:n,onClose:r,onOpen:o})=>{if(!1===or(e))throw new Error(Xn);Mu(this,Ru,"f").call(this,e);const i=`${lr({urlName:jn,urlType:Mu(this,Cu,"f")})}${$n}?tryonId=${e}`,s=new WebSocket(i);Mu(this,Tu,"f").set(e,s),s.onopen=()=>{null==o||o(),Mu(this,Au,"f").call(this,{onSuccess:n,onError:t,tryonId:e})},s.onmessage=r=>{let o;try{o=JSON.parse(r.data)}catch(e){return void console.log("Invalid JSON:",r.data)}"success"===(null==o?void 0:o.status)?null==n||n(o):null==t||t(o);const i=Mu(this,ku,"f").get(e);i&&clearTimeout(i),Mu(this,ku,"f").delete(e)},s.onclose=()=>{null==r||r()},s.onerror=e=>{null==t||t(e)}},Nu.set(this,e=>Fu(this,[e],void 0,function*({onSuccess:e,onError:t,tryonId:n}){try{const t=yield this.getTryOnResult({tryonId:n});null==e||e(t.data)}catch(e){null==t||t(e)}})),this.getTryOnResult=({tryonId:e})=>{if(!1===or(e))throw new Error(Xn);const t=`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${Bn}/${e}`;return ln.post(t,null,{headers:{"X-Api-Key":Mu(this,xu,"f")}})},Iu(this,xu,e,"f"),Iu(this,Cu,t,"f")}uploadFile(e){return Fu(this,arguments,void 0,function*({files:e,userEmail:t,fileNoLimit:n=2}){if(!1===or(e,t))throw new Error(Xn);if(!cr(t.trim()))throw new Error(Zn);if(n<=0)throw new Error(`Provide valid file number limit ${n}.`);if((null==e?void 0:e.length)>n)throw new Error(`Cannot allow more than ${n} files.`);try{const n={userEmail:t,userImages:[]};null==e||e.forEach(e=>{n.userImages.push(e.name)});const r=yield Mu(this,Pu,"m",Ou).call(this,n);for(const t of e)yield Mu(this,Pu,"m",ju).call(this,r.data.uploadUrls[t.name].url,t);return"uploaded successfully!"}catch(e){throw e}})}getUploadedFiles(e){if(!1===or(e))throw new Error(Xn);if(!cr(e.trim()))throw new Error(Zn);const t={userEmail:e};return ln.post(`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${zn}`,t,{headers:{"X-Api-Key":Mu(this,xu,"f")}})}deleteImage({userEmail:e,fileName:t}){if(!1===or(e,t))throw new Error(Xn);if(!cr(e.trim()))throw new Error(Zn);const n={userEmail:e,file:t};return ln.delete(`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${Dn}`,{headers:{"X-Api-Key":Mu(this,xu,"f")},data:n})}handleTryOnSubmit({shopDomain:e,products:t,selectedUserImages:n,requestSource:r,callbackUrl:o,openTryonId:i,selectedProductImageUrl:s,token:a}){if(!1===or(e,t,a))throw new Error(Xn);const l=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({products:t,customerStoreUrl:e},null!=n&&{selectedUserImages:n}),null!=r&&{requestSource:r}),null!=o&&{callbackUrl:o}),null!=i&&{openTryonId:i}),null!=s&&{selectedProductImageUrl:s}),c=`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${$n}`,u={"X-Api-Key":Mu(this,xu,"f")};return a&&(u.Authorization=`Bearer ${a}`),ln.post(c,l,{headers:u})}getShareLink(e){return ln.post(`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${Vn}`,{tryonId:e},{headers:{"X-Api-Key":Mu(this,xu,"f")}})}getProductImageEligibility({storeUrl:e,productHandle:t,imageURL:n,productDescription:r}){if(!1===or(e,t,n))throw new Error(Xn);const o={storeUrl:e,productHandle:t,imageURL:n,productDescription:null!=r?r:null},i=`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${Yn}`;return ln.post(i,o,{headers:{"X-Api-Key":Mu(this,xu,"f")}})}}Tu=new WeakMap,ku=new WeakMap,xu=new WeakMap,Cu=new WeakMap,Ru=new WeakMap,Au=new WeakMap,Nu=new WeakMap,Pu=new WeakSet,Ou=function(e){if(!1===or(e))throw new Error(Xn);return ln.post(`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${Ln}`,e,{headers:{"Content-Type":"application/json","X-Api-Key":Mu(this,xu,"f")}})},ju=function(e,t){if(!1===or(e,t))throw new Error(Xn);return ln.put(e,t,{headers:{"Content-Type":t.type}})};var Lu,zu,Du,Bu=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},$u=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};Lu=new WeakMap,zu=new WeakMap,function(e){e.DEV="dev",e.STAGING="staging",e.PROD="prod"}(Du||(Du={}));const qu=new class{constructor(e,t=tr.PROD){Lu.set(this,void 0),zu.set(this,void 0),Bu(this,Lu,e,"f"),Bu(this,zu,t,"f"),this.auth=new fr($u(this,Lu,"f"),$u(this,zu,"f")),this.custom=new wr($u(this,Lu,"f"),$u(this,zu,"f")),this.fileUpload=new Nl($u(this,Lu,"f"),$u(this,zu,"f")),this.measurement=new Gl($u(this,Lu,"f"),$u(this,zu,"f")),this.poseDetection=new Eu($u(this,Lu,"f"),$u(this,zu,"f")),this.tryOn=new Uu($u(this,Lu,"f"),$u(this,zu,"f"))}}("8e35dfd4-010c-40ca-ad79-fc72dc307efb",Du.STAGING);let Wu,Hu=null,Vu=null;var Ku=t.memo(function({setIsScanLocked:o,resetDetector:i,scanID:s,setIsVideoUploaded:a,setScanFailsError:l,setScanStartTime:c,setScanUniqueKey:u,userDetails:d,config:h}){const{gender:p,heightInCm:_,email:f,shopDomain:m}=d,g=t.useRef(null),y=t.useRef(null),[v,w]=t.useState([]),[b,S]=t.useState(!0),[E,P]=t.useState(!1),[T,k]=t.useState(!1),[x,C]=t.useState(!0),[O,j]=t.useState(!1),R=t.useRef(null),[A,N]=t.useState(""),[F,I]=t.useState([]),[M,U]=t.useState(""),[L,z]=t.useState(!1),[D,B]=t.useState(!1),[$,q]=t.useState(!1),[W,H]=t.useState([]),[V,K]=t.useState(!1),Y=t.useRef(!0),G=t.useRef(!0),J=t.useRef(!1);let X=0;const{setStartGyro:Q,handleFileUpload:ne,setUploadLoading:re}=t.useContext(ee),oe=()=>{J.current=!1,clearTimeout(Wu),R.current&&clearTimeout(R.current),u(r.generateUuid()),l(""),re?.(!1),w([]),S(!0),P(!1),k(!1),C(!0),j(!1),R.current=null,N(""),I([]),U(""),z(!L),Q(!1),te.stopAudio(),B(!1),q(!1),X=0,null!==y.current&&y.current.stop(),W.forEach(e=>{y.current&&y.current.removeEventListener("dataavailable",e)}),H([]),Y.current=!0,K(!1),a(!1)},ie=t.useCallback(()=>{setTimeout(()=>{S(!1)},1e3)},[]),se=t.useCallback(()=>{r.rescanSupportCaptureEvent({eventName:`${m}/rescan`,email:f,scanID:s,height:_,gender:p,status:!1}),Y.current=!1,oe(),me()},[oe,s,f]),ae=t.useCallback(()=>{Y.current=!1,q(!0),K(!1),R.current&&clearTimeout(R.current),y.current&&y.current.pause(),te.stopAudio(),qu.poseDetection.disconnect(),X=0,y.current&&y.current.stop(),W.forEach(e=>{y.current&&y.current.removeEventListener("dataavailable",e)}),H([]),clearTimeout(Wu)},[y,W,te,Y]),le=n.videoTypes.filter(e=>MediaRecorder.isTypeSupported(e)),ce=t.useCallback(async()=>{Y.current=!0,await te.playAudio(`${n.voiceOverAssetsPath}SpotOn.mp3`),q(!1),K(!1),R.current&&clearTimeout(R.current),P(!1)},[R,te]),ue=t.useCallback(async()=>{try{Hu=await qu.poseDetection.connect(),r.qo.capture(`${m}/pose_detection_connected`,{scanID:s,email:f,id:Hu})}catch(e){console.log(e,"while connecting websocket")}},[s,m,f]),de=t.useCallback(({data:e})=>{e&&e.size>0&&Y.current&&(w(t=>t.concat(e)),!J.current&&g.current&&(J.current=!0))},[ce,r.handleScanTimeCapture,m,s,f,g]),he=t.useCallback(async()=>{F.length>0&&Y.current&&(await te.playAudio(n.voiceOverAssetsPath+F[F.length-1]),Y.current&&(Wu=setTimeout(he,2e3)))},[F,Y]),pe=t.useCallback(()=>{y&&y.current&&y.current.stop(),P(!0);try{if(g&&g.current&&g.current.stream){const e={mimeType:le[0]};y.current=new MediaRecorder(g.current.stream,e),y.current.addEventListener("dataavailable",de),H([...W,de]),y.current.start(1e3),C(!1)}}catch(e){console.log("error while using media recorder",e)}},[g,le,de,W]),_e=t.useCallback(async()=>{R.current&&clearTimeout(R.current),pe(),Y.current&&(R.current=setTimeout(async()=>{Y.current&&(await te.playAudio(`${n.voiceOverAssetsPath}SpotOn.mp3`),P(!1))},15e3)),k(!0),Y.current&&await te.playAudio(`${n.voiceOverAssetsPath}Spin.mp3`)},[pe,Y,te]),fe=t.useCallback(({data:e})=>{e.size>0&&qu.poseDetection.connected()&&(qu.poseDetection.poseStatus(async e=>{if(e&&e.audio&&e.audio.length>0){const t=document.querySelector("#audioElement");!0===e.status&&e.sid===Hu?X<2?(0===X&&t?.paused&&await te.playAudio(n.voiceOverAssetsPath+e.audio),X+=1):(U(e.audio),clearTimeout(Wu),qu.poseDetection.disconnect(),setTimeout(_e,1e3)):(X=0,!t?.paused||Vu&&Vu?.audioName===e.audio?Vu?.audioName===e.audio&&t?.paused&&(Vu&&Vu.no_of_times_skipped>=Vu.skipCount?(Vu.no_of_times_skipped=0,te.playAudio(n.voiceOverAssetsPath+e.audio)):Vu&&(Vu.no_of_times_skipped+=1)):(Vu={skipCount:2,no_of_times_skipped:0,audioName:e.audio},te.playAudio(n.voiceOverAssetsPath+e.audio)))}}),g?.current&&null!==g.current.getScreenshot()&&qu.poseDetection.videoEmit({image:g.current.getScreenshot()||"",scanId:s}))},[g,s,qu,Hu,X,_e,te]),me=t.useCallback(async()=>{j(!0),Q(!0),G.current&&(G.current=!1,r.handleScanTimeCapture({eventName:"scan started",scanID:s,status:"success",email:f})),c(r.getCurrentTimeInSeconds()),S(!0),Y.current&&await te.playAudio(`${n.voiceOverAssetsPath}StartScan.mp3`),Y.current&&await te.playAudio(`${n.voiceOverAssetsPath}LiftArmsAndHoldAtHip.mp3`),Y.current&&(j(!1),P(!0),B(!0),K(!0),ie());try{if(g&&g.current&&g.current.stream&&Y.current){const e={mimeType:le[0]};Y.current&&(y.current=new MediaRecorder(g.current.stream,e)),Y.current&&y.current&&y.current.addEventListener("dataavailable",fe),H([...W,fe]),y.current&&y.current.start(1e3),C(!1),Y.current&&(Wu=setTimeout(he,2e3))}}catch(e){console.log("error ----------",e)}},[g,le,fe,W,he,Y]);return t.useEffect(()=>(m&&(o(!0),ue()),()=>{Hu&&(qu.poseDetection.disconnect(),r.qo.capture(`${m}/pose_detection_disconnected`,{scanID:s,email:f,id:Hu})),W.forEach(e=>{y?.current?.removeEventListener("dataavailable",e)})}),[L,m]),t.useEffect(()=>{F.push(A)},[A]),t.useEffect(()=>{I([])},[M]),t.useEffect(()=>{const e=v.length&&v.length>0;x||!e||E||!Y.current||$||y&&y.current&&(E||(y.current.stop(),C(!0)))},[x,E,v,$]),t.useEffect(()=>{const e=v.length&&v.length>0;if(x||!e||E)console.log("No video found to upload");else if(y&&y.current&&Y.current&&!$&&!E){const e=new File(v,`${s}.webm`,{type:"video/webm"});re?.(!0),l(""),ne?.(e)}},[x,E,v,$,y,Y]),t.useEffect(()=>{oe()},[]),e.jsx(Z,{resetDetector:i,handleShowStreamCamera:oe,loadingCam:b,handlePause:ae,showRestart:D,pause:$,handleReScan:se,recordingStarted:E,isScanning:O,startSendingVideoFrames:me,faceDone:T,stopRecording:ce,showPause:V,webcamRef:g,handleUserMedia:ie,config:h})});function Yu({scanID:n,userDetails:r,setIsVideoUploaded:o,setScanFailsError:i,setScanStartTime:s,setScanUniqueKey:a,config:l}){const[c,u]=t.useState(90),[d,h]=t.useState(0),[p,_]=t.useState(null),[f,m]=t.useState(!1),[g,y]=t.useState(0),v=t.useRef([]),[w,b]=t.useState(!1),S=c-d,E=S>=80&&S<=95;t.useEffect(()=>{if("undefined"!=typeof window&&window.DeviceOrientationEvent){const e=e=>{if(null!==e.beta){let t=Math.abs(e.beta);null!==e.gamma&&(t*=Math.cos(e.gamma*Math.PI/180)),t=Math.max(0,Math.min(180,t)),u(t)}},t=async()=>{const t=DeviceOrientationEvent;if(t&&"function"==typeof t.requestPermission)try{"granted"===await t.requestPermission()&&window.addEventListener("deviceorientation",e)}catch(e){console.error("Permission error",e)}else window.addEventListener("deviceorientation",e);return()=>{e&&window.removeEventListener("deviceorientation",e)}};document.addEventListener("click",t,{once:!0})}},[]),t.useEffect(()=>{if(v.current=[...v.current.slice(-4),S],v.current.length>=5){const e=Math.max(...v.current)-Math.min(...v.current);y(E&&e<2?e=>Math.min(100,e+10):e=>Math.max(0,e-20))}E||null===p&&!f||T()},[S,E,p,f]),t.useEffect(()=>{g>=100&&null===p&&!f&&P(),g<50&&null!==p&&T()},[g,p,f]);const P=()=>{_(3);const e=setInterval(()=>{_(t=>null===t||t<=1?(clearInterval(e),m(!0),null):t-1)},1e3)},T=()=>{_(null),w||m(!1)};return e.jsx(A,{angle:S,countdown:p,isScanning:f,isInTargetRange:E,stabilityScore:g,config:l,children:f&&e.jsx(Ku,{setIsScanLocked:b,resetDetector:()=>{u(90),h(0),_(null),m(!1),y(0),b(!1),v.current=[]},scanID:n,userDetails:r,setIsVideoUploaded:o,setScanFailsError:i,setScanStartTime:s,setScanUniqueKey:a,config:l})})}function Gu({message:o,config:i}){const[s]=t.useState(!0),{translate:a}=t.useContext(X)||{};return e.jsx(v,{open:s,className:"confirm-modal",children:e.jsx("div",{className:"modal-main",children:e.jsx("div",{className:"text-center",children:o?e.jsxs(e.Fragment,{children:[e.jsx("h2",{style:{fontFamily:i?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:i?.style?.heading?.headingFontSize||"32px",color:i?.style?.heading?.headingColor||"#000",fontWeight:i?.style?.heading?.headingFontWeight||"normal"},children:"Seems camera already in use"}),e.jsxs("p",{className:"mt-[0.5rem] text-sm",style:{fontFamily:i?.style?.base?.baseFontFamily||"Inter, sans-serif",fontSize:i?.style?.base?.baseFontSize||"16px",color:i?.style?.base?.baseTextColor||"#000"},children:["Can you try closing the browser/app that is using the camera and try again here."," "]})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{style:{fontFamily:i?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:i?.style?.heading?.headingFontSize||"32px",color:i?.style?.heading?.headingColor||"#000",fontWeight:i?.style?.heading?.headingFontWeight||"normal"},children:a?.(n.LanguageKeys.Please_check_your_setting_for_camera_permission)}),e.jsx("p",{className:"mt-[0.5rem] text-sm",style:{fontFamily:i?.style?.base?.baseFontFamily||"Inter, sans-serif",fontSize:i?.style?.base?.baseFontSize||"16px",color:i?.style?.base?.baseTextColor||"#000"},children:`${a?.(n.LanguageKeys.Settings)} > ${r.getBrowserName()} > ${a?.(n.LanguageKeys.Enable_the_camera_permissions)}`})]})})})})}function Ju({setShowDrawer:i,config:s,loader:a}){const[l,c]=t.useState({disabled:!1,message:""}),[u,d]=t.useState(!0),h=t.useRef(null),p=t.useCallback(async()=>{const e=await r.checkCameraPermission();c(e),d(!1)},[]);return t.useEffect(()=>{p()},[]),u?e.jsx(o.LoadingScreen,{url:a}):l?.disabled?e.jsx(Gu,{config:s,message:l?.message}):e.jsx(M,{audio:!1,ref:h,screenshotQuality:1,videoConstraints:n.videoConstraints,mirrored:!0,onUserMedia:()=>i?.(!0),screenshotFormat:"image/jpeg",style:{position:"relative",top:0,bottom:0,zIndex:0,width:"100%",height:"100%",objectFit:"cover"}})}function Xu({link:r,onReady:o,wrapperClassName:s="[&_video]:rounded-t-[20px] w-full h-full"}){const a=t.useRef(null),l=t.useRef(null);let c={autoplay:!0,controls:!1,responsive:!0,fluid:!0,muted:!0,navigationUI:"hide",preload:"metadata",poster:n.videoPoster};return t.useEffect(()=>{if(!l.current&&r&&a?.current){const e=i(a.current,{...c});e.ready(()=>{l.current=e;const t={...c,sources:[{src:r,type:"application/x-mpegURL"}]};e.autoplay(t.autoplay),e.src(t.sources),o?.(e)})}},[r,a]),t.useEffect(()=>{const e=l.current;return()=>{e&&!e.isDisposed()&&(e.dispose(),l.current=null)}},[l]),e.jsx("div",{className:s,children:e.jsx("video",{ref:a,muted:!0,className:"video-js",playsInline:!0,onDrag:e=>e.preventDefault()})})}function Qu({scanFailsError:o,serverAtCapacity:i=!1,onNext:s,gender:a,setScanUniqueKey:l,resolvedConfig:c,setIsVideoUploaded:u}){const{translate:d}=t.useContext(X)||{},[h,p]=t.useState(!1),_=()=>{p(!h)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col h-full max-w-[28rem] mx-auto w-full rounded-t-[20px] overflow-y-auto",style:{background:c?.style?.base?.backgroundColor},children:[e.jsx("div",{className:"w-full max-w-[28rem] mx-auto pt-[1rem] px-[1rem]",children:e.jsx(n.Header,{noTitle:!0,resolvedConfig:c})}),e.jsxs("div",{className:"flex-1",children:[o&&e.jsxs("div",{className:"px-[1rem]",children:[e.jsx("h2",{className:"text-center",style:{fontFamily:c?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:c?.style?.heading?.headingFontSize||"32px",color:c?.style?.heading?.headingColor||"#000",fontWeight:c?.style?.heading?.headingFontWeight||"normal"},children:"There was an issue with your scan"}),e.jsx("p",{style:{fontFamily:c?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:"Reason:"}),e.jsx("p",{style:{fontFamily:c?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:r.handleErrorMessage(o)}),e.jsx("img",{className:"my-[0.5rem] aspect-[2/1.4] w-full object-cover",onClick:_,src:n.VIDEO_POSTER_GENDER_BASED[a],alt:"icon"})]}),i&&e.jsxs("div",{className:"p-[1rem] text-center",children:[e.jsxs("h3",{style:{fontFamily:c?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:c?.style?.heading?.headingFontSize||"32px",color:c?.style?.heading?.headingColor||"#000",fontWeight:c?.style?.heading?.headingFontWeight||"normal"},children:[d?.(n.LanguageKeys.Scan_s)," ",e.jsx("span",{children:d?.(n.LanguageKeys.vision_model)})," ",d?.(n.LanguageKeys.is_at_capacity)]}),e.jsx("p",{className:"text-base mt-[0.5rem]",style:{fontFamily:c?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:d?.(n.LanguageKeys.We_are_sorry_about_this_We_are_working_hard_to_add_capacity_Please_try_again_soon)})]})]}),o&&e.jsx("div",{className:"p-[1rem] flex gap-[0.5rem]",children:e.jsx(n.SpecificButton,{disabled:!1,buttonText:"Scan again",className:"!shadow-none",buttonFunc:()=>{s?s?.():l(r.generateUuid()),u(!1)},resolvedConfig:c})})]}),h&&e.jsxs(v,{className:"w-screen h-screen video-modal",onClose:_,open:h,children:[e.jsx("div",{className:"flex justifyEnd ",children:e.jsx("span",{className:"closeBtn",onClick:_,children:e.jsx(U,{className:"absolute right-[8px] top-[8px] text-white z-[9]"})})}),e.jsx("div",{className:"aspect-video object-cover rounded-[20px] ",children:e.jsx(Xu,{link:a?n.GENDER[a].PRE_LINK:n.GENDER.male.PRE_LINK,wrapperClassName:"w-screen h-screen fixed top-[0] left-[0]"})})]})]})}function Zu({scanId:o,userDetails:i,config:s,isFaceScan:a,isVideoUploadedCorrect:l,isMeasurementAvailable:c,onComplete:u,isSuccess:h}){const{gender:p,shopDomain:_,heightInCm:f,deviceFocalLength:m,userName:g,email:y,scanType:v}=i,w=[n.CLOTHING_CUSTOM_SCAN,n.CLOTHING_BANNER_SCAN,n.CLOTHING_CUSTOM_FIT_SCAN].includes(v),[b,S]=t.useState(!0),E=t.useCallback(async()=>{try{w&&await qu.auth.addUser({scanId:o,email:y,name:g,gender:p,height:f}),r.qo.capture(_,{scanID:o,email:y,height:f,focalLength:m,clothesFit:"0",gender:p})}catch(e){console.log(e)}},[w]);t.useEffect(()=>{l&&E()},[l]);const P=h||(a?c&&l:l||c);return e.jsx(d,{className:"flex h-full w-full flex-col ",children:e.jsxs("div",{className:"h-full w-full flex-col items-center justify-center flex",children:[e.jsx(Ju,{loader:s?.loader,setShowDrawer:S}),e.jsx(O,{open:b,onClose:(e,t)=>{},className:"camera-drawer",anchor:"bottom",children:e.jsx("div",{className:"max-w-[28rem] mx-auto w-full h-full flex text-center flex-col justify-between items-center bg-primary rounded-t-[30px] p-[1rem]",style:{background:s?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"w-full h-full flex flex-col",children:[e.jsx(n.Header,{title:"Your measurements are being taken",resolvedConfig:s}),e.jsx("div",{className:"flex items-center justify-center flex-1",children:e.jsx("video",{className:"max-h-[calc(100vh-450px)] mx-auto w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:p===r.GenderType.Male?n.maleMeasurementProgress:n.measurementProgress,type:"video/mp4"})})}),P&&e.jsx(n.SpecificButton,{resolvedConfig:s,className:"!w-[180px] mx-auto",buttonText:"Next",buttonFunc:u&&u})]})})})]})})}exports.BodyScan=({userDetails:i,language:s=r.PreferredLanguage.English,config:a,onRetry:l,onScanSuccess:c,onComplete:u,onScanError:d,isError:h,isSuccess:p})=>{const{gender:_,scanType:f,shopDomain:m,heightInCm:g,email:y,deviceFocalLength:v,deviceModelName:w,callbackUrl:b}=i,[S,E]=t.useState(!1),[P,T]=t.useState(!1),[k,x]=t.useState(!1),[C,j]=t.useState({disabled:!1,message:""}),[R,A]=t.useState(""),[N,F]=t.useState(!1),[I,M]=t.useState(!0),[U,L]=t.useState(!1),[z,D]=t.useState(""),[B,q]=t.useState(r.getCurrentTimeInSeconds()),{gyroData:W}=function(e){const[n,r]=t.useState([]),[o,i]=t.useState(!1),s=t.useCallback(e=>{try{const{alpha:t,beta:n,gamma:o}=e;r(e=>[...e,{alpha:t?.toString()||void 0,beta:n?.toString()||void 0,gamma:o?.toString()||void 0,timestamp:(new Date).toISOString()}])}catch(e){console.log(e)}},[]),a=t.useCallback(async()=>{const e=DeviceOrientationEvent;if(void 0!==e&&"function"==typeof e.requestPermission)try{"granted"===await e.requestPermission()?i(!0):console.warn("Device orientation permission denied.")}catch(e){console.error("Error requesting device orientation permission:",e)}else i(!0)},[]);return t.useEffect(()=>(e&&o?window.addEventListener("deviceorientation",s):r([]),()=>{window.removeEventListener("deviceorientation",s)}),[e,o,s]),t.useEffect(()=>{e&&a()},[e,a]),{gyroData:n}}(U),{setPreferredLanguage:H}=t.useContext(X)||{},V=n.useLocalConfig(a),K=t.useCallback(()=>{D(r.generateUuid()),A(""),E(!1),F(!1)},[]),Y=e=>{d({...e,message:r.handleErrorMessage(e)}),G(),x(!1),A(e),T(!1),r.handleScanTimeCapture({eventName:`${m}/measurement_failed/fit-view`,scanID:z,status:"failed",email:y,message:r.handleErrorMessage(e)}),B&&r.handleScanTimeCapture({eventName:`${m}/scan_completion_time`,scanID:z,status:"failed",completionTime:r.getCurrentTimeInSeconds()-B,email:y})},G=()=>{q(null),D("")},J=t.useCallback(async e=>{if(e&&"success"===e?.scanStatus&&"intermediate"===e?.resultType&&200===e?.code)return r.handleScanTimeCapture({eventName:`${m}/measurement_success/intermediate`,scanID:z,status:"success",email:y}),void c?.(e);G();const t=z;x(!0),r.handleScanTimeCapture({eventName:`${m}/measurement_success/fit-view`,scanID:t,status:"success",email:y}),B&&r.handleScanTimeCapture({eventName:`${m}/scan_completion_time`,scanID:t,status:"success",completionTime:r.getCurrentTimeInSeconds()-B,email:y})},[f,m,z]),Z=e=>{x(!1),A(""),T(!1),qu.measurement.handleMeasurementSocket({scanId:e||z,onOpen:()=>{r.handleWebSocketCapture({eventName:`${m}/webSocket`,scanID:z,connection:"open",type:"measurement_recommendation",email:y})},onClose:()=>r.handleWebSocketCapture({eventName:`${m}/webSocket`,scanID:z,connection:"close",type:"measurement_recommendation",email:y}),onError:e=>{Y(e),r.handleWebSocketCapture({eventName:`${m}/webSocket`,scanID:z,connection:"error",type:"measurement_recommendation",email:y})},onSuccess:e=>{r.handleWebSocketCapture({eventName:`${m}/webSocket`,scanID:z,connection:"success",type:"measurement_recommendation",email:y}),J(e)}})},te=t.useCallback(async e=>{const t=r.createObjectMetadataArray({gender:_,focal_length:`${v}`,height:`${g}`,customer_store_url:m,clothes_fit:"0",scan_type:f,callback_url:b||"https://example.com/webhook"});r.handleScanTimeCapture({eventName:`${m}/body_scan_meta_data`,scanID:z,email:y,data:JSON.stringify(t)});try{await qu.fileUpload.uploadFileFrontend({file:e,arrayMetaData:t,scanId:z,email:y}),await qu.fileUpload.setDeviceInfo({model:w,detection:"manual",gyro:W,scanId:z}),console.log("video successfully uploaded"),F(!1),r.handleScanTimeCapture({eventName:`${m}/scan_success`,scanID:z,status:"success",email:y,data:JSON.stringify(t)}),r.handleScanTimeCapture({eventName:"scan finished",scanID:z,status:"success",email:y}),q(r.getCurrentTimeInSeconds()),setTimeout(()=>{F(!0)},3e3)}catch(e){r.handleScanTimeCapture({eventName:"scan finished",scanID:z,status:"failed",email:y,message:r.handleErrorMessage(e)}),r.handleScanTimeCapture({eventName:`${m}/scan_failed`,scanID:z,status:"failed",email:y,message:r.handleErrorMessage(e),data:JSON.stringify(t)}),A(r.handleErrorMessage(e)),F(!1),console.log(e,"video upload failed")}finally{L(!1)}},[z,W]),ne=t.useCallback(async e=>{try{const t=await qu.measurement.getMeasurementResult(e),n=t?.data?.isMeasured,o=B||r.getCurrentTimeInSeconds(),i=r.getCurrentTimeInSeconds(),s=300;if(M(!1),!1===n)return G(),void D(r.generateUuid());E(!0),!0===n?await J(null):null===n&&o>i+s?Y(t?.data?.error):Z(e)}catch(e){console.log(e),G(),D(r.generateUuid()),E(!1)}},[Y,J,D]),re=t.useCallback(async()=>{if(+g<152.4||+g>213.36)return void d({message:"Height must be between 152.4cm (5ft) and 213.36cm (7ft)"});const e=await r.checkCameraPermission();if(e.disabled)r.handleScanTimeCapture({eventName:`${m}/camera_activation`,scanID:z,status:"failed",email:y}),M(!1);else{z?ne(z):M(!1),r.handleScanTimeCapture({eventName:`${m}/camera_activation`,scanID:z,status:"success",email:y})}j(e),A(""),F(!1)},[ne,y,z,D,m]);return t.useEffect(()=>{H?.(s),r.qo.init(n.posthogPublicKey,{api_host:n.posthogPublicHost}),r.qo.capture("$pageview")},[]),t.useEffect(()=>{h||p||m&&re()},[m,g,h,p]),t.useEffect(()=>{h||p||N&&m&&z&&Z()},[N,m,z,h,p]),h?e.jsxs(Q,{children:[e.jsx(Ju,{}),e.jsx(O,{anchor:"bottom",open:!0,className:"camera-drawer",onClose:(e,t)=>{},children:e.jsx(Qu,{scanFailsError:R||h,onNext:()=>{},setScanUniqueKey:D,gender:_,resolvedConfig:V,setIsVideoUploaded:F})})]}):p?e.jsx(Zu,{isFaceScan:!1,scanId:z,isMeasurementAvailable:k,userDetails:i,isVideoUploadedCorrect:P,config:V,isSuccess:p}):I?e.jsx("div",{className:"flex top-0 !mt-0 left-0 z-[999] bg-opacity-80 bg-[#1b1b1b] absolute justify-center items-center w-full h-full",children:e.jsx(o.LoadingScreen,{url:V?.loader})}):C.disabled?e.jsx(Q,{children:e.jsx(Gu,{})}):S||R?!S&&!k||R?e.jsxs(Q,{children:[e.jsx(Ju,{}),e.jsx(O,{anchor:"bottom",open:!0,className:"camera-drawer",onClose:(e,t)=>{},children:e.jsx(Qu,{scanFailsError:R,onNext:()=>{l?.(),K()},setScanUniqueKey:D,gender:_,resolvedConfig:V,setIsVideoUploaded:F})})]}):e.jsx(Zu,{isFaceScan:!1,scanId:z,isMeasurementAvailable:k,userDetails:i,onComplete:u,isVideoUploadedCorrect:P,config:V}):e.jsx(ee.Provider,{value:{setStartGyro:L,handleFileUpload:te,setUploadLoading:E},children:e.jsx($,{children:e.jsx(Q,{children:e.jsx(Yu,{config:V,scanID:z,userDetails:i,setIsVideoUploaded:F,setScanFailsError:A,setScanStartTime:q,setScanUniqueKey:D})})})})};
19
+ */function Tr(e,t){const n=/\$/g;let r=[e];if(null==t)return r;for(const e of Object.keys(t))if("_"!==e){let o=t[e];"string"==typeof o&&(o=n[Symbol.replace](o,"$$$$")),r=Pr(r,new RegExp(`%\\{${e}\\}`,"g"),o)}return r}const kr=e=>{throw new Error(`missing string: ${e}`)};var xr,Cr,Or=Er("onMissingKey"),jr=Er("apply");class Rr{constructor(e,t){let{onMissingKey:n=kr}=void 0===t?{}:t;Object.defineProperty(this,jr,{value:Ar}),Object.defineProperty(this,Or,{writable:!0,value:void 0}),this.locale={strings:{},pluralize:e=>1===e?0:1},Array.isArray(e)?e.forEach(br(this,jr)[jr],this):br(this,jr)[jr](e),br(this,Or)[Or]=n}translate(e,t){return this.translateArray(e,t).join("")}translateArray(e,t){let n=this.locale.strings[e];null==n&&(br(this,Or)[Or](e),n=e);if("object"==typeof n){if(t&&void 0!==t.smart_count){return Tr(n[this.locale.pluralize(t.smart_count)],t)}throw new Error("Attempted to use a string with plural forms, but no value was given for %{smart_count}")}if("string"!=typeof n)throw new Error("string was not a string");return Tr(n,t)}}function Ar(e){if(null==e||!e.strings)return;const t=this.locale;Object.assign(this.locale,{strings:{...t.strings,...e.strings},pluralize:e.pluralize||t.pluralize})}var Nr=(Cr||(Cr=1,xr=function(){var e={},t=e._fns={};return e.emit=function(e,n,r,o,i,s,a){var l=function(e){for(var n=t[e]?t[e]:[],r=e.indexOf(":"),o=-1===r?[e]:[e.substring(0,r),e.substring(r+1)],i=Object.keys(t),s=0,a=i.length;s<a;s++){var l=i[s];if("*"===l&&(n=n.concat(t[l])),2===o.length&&o[0]===l){n=n.concat(t[l]);break}}return n}(e);l.length&&function(e,t,n){for(var r=0,o=t.length;r<o&&t[r];r++)t[r].event=e,t[r].apply(t[r],n)}(e,l,[n,r,o,i,s,a])},e.on=function(e,n){t[e]||(t[e]=[]),t[e].push(n)},e.once=function(t,n){this.on(t,function r(){n.apply(this,arguments),e.off(t,r)})},e.off=function(e,t){var n=[];if(e&&t)for(var r=this._fns[e],o=0,i=r?r.length:0;o<i;o++)r[o]!==t&&n.push(r[o]);n.length?this._fns[e]=n:delete this._fns[e]},e}),xr),Fr=r.getDefaultExportFromCjs(Nr);var Ir,Mr,Ur,Lr,zr,Dr,Br,$r,qr,Wr,Hr,Vr,Kr,Yr,Gr,Jr,Xr,Qr,Zr,eo,to,no,ro,oo,io,so,ao,lo,co,uo;function ho(){if(Mr)return Ir;return Mr=1,Ir=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},Ir}function po(){if(Dr)return zr;Dr=1;var e=function(){if(Lr)return Ur;Lr=1;var e="object"==typeof r.commonjsGlobal&&r.commonjsGlobal&&r.commonjsGlobal.Object===Object&&r.commonjsGlobal;return Ur=e}(),t="object"==typeof self&&self&&self.Object===Object&&self,n=e||t||Function("return this")();return zr=n}function _o(){if(Vr)return Hr;Vr=1;var e=function(){if(Wr)return qr;Wr=1;var e=/\s/;return qr=function(t){for(var n=t.length;n--&&e.test(t.charAt(n)););return n}}(),t=/^\s+/;return Hr=function(n){return n?n.slice(0,e(n)+1).replace(t,""):n}}function fo(){if(Yr)return Kr;Yr=1;var e=po().Symbol;return Kr=e}function mo(){if(eo)return Zr;eo=1;var e=fo(),t=function(){if(Jr)return Gr;Jr=1;var e=fo(),t=Object.prototype,n=t.hasOwnProperty,r=t.toString,o=e?e.toStringTag:void 0;return Gr=function(e){var t=n.call(e,o),i=e[o];try{e[o]=void 0;var s=!0}catch(e){}var a=r.call(e);return s&&(t?e[o]=i:delete e[o]),a},Gr}(),n=function(){if(Qr)return Xr;Qr=1;var e=Object.prototype.toString;return Xr=function(t){return e.call(t)},Xr}(),r=e?e.toStringTag:void 0;return Zr=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":r&&r in Object(e)?t(e):n(e)},Zr}function go(){if(oo)return ro;oo=1;var e=mo(),t=(no||(no=1,to=function(e){return null!=e&&"object"==typeof e}),to);return ro=function(n){return"symbol"==typeof n||t(n)&&"[object Symbol]"==e(n)},ro}function yo(){if(lo)return ao;lo=1;var e=ho(),t=function(){if($r)return Br;$r=1;var e=po();return Br=function(){return e.Date.now()}}(),n=function(){if(so)return io;so=1;var e=_o(),t=ho(),n=go(),r=/^[-+]0x[0-9a-f]+$/i,o=/^0b[01]+$/i,i=/^0o[0-7]+$/i,s=parseInt;return io=function(a){if("number"==typeof a)return a;if(n(a))return NaN;if(t(a)){var l="function"==typeof a.valueOf?a.valueOf():a;a=t(l)?l+"":l}if("string"!=typeof a)return 0===a?a:+a;a=e(a);var c=o.test(a);return c||i.test(a)?s(a.slice(2),c?2:8):r.test(a)?NaN:+a},io}(),r=Math.max,o=Math.min;return ao=function(i,s,a){var l,c,u,d,h,p,_=0,f=!1,m=!1,g=!0;if("function"!=typeof i)throw new TypeError("Expected a function");function y(e){var t=l,n=c;return l=c=void 0,_=e,d=i.apply(n,t)}function v(e){var t=e-p;return void 0===p||t>=s||t<0||m&&e-_>=u}function w(){var e=t();if(v(e))return b(e);h=setTimeout(w,function(e){var t=s-(e-p);return m?o(t,u-(e-_)):t}(e))}function b(e){return h=void 0,g&&l?y(e):(l=c=void 0,d)}function S(){var e=t(),n=v(e);if(l=arguments,c=this,p=e,n){if(void 0===h)return function(e){return _=e,h=setTimeout(w,s),f?y(e):d}(p);if(m)return clearTimeout(h),h=setTimeout(w,s),y(p)}return void 0===h&&(h=setTimeout(w,s)),d}return s=n(s)||0,e(a)&&(f=!!a.leading,u=(m="maxWait"in a)?r(n(a.maxWait)||0,s):u,g="trailing"in a?!!a.trailing:g),S.cancel=function(){void 0!==h&&clearTimeout(h),_=0,l=p=c=h=void 0},S.flush=function(){return void 0===h?d:b(t())},S},ao}var vo=function(){if(uo)return co;uo=1;var e=yo(),t=ho();return co=function(n,r,o){var i=!0,s=!0;if("function"!=typeof n)throw new TypeError("Expected a function");return t(o)&&(i="leading"in o?!!o.leading:i,s="trailing"in o?!!o.trailing:s),e(n,r,{leading:i,maxWait:r,trailing:s})}}(),wo=r.getDefaultExportFromCjs(vo);function bo(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var So=0;function Eo(e){return"__private_"+So+++"_"+e}var Po=Eo("callbacks"),To=Eo("publish");class ko{constructor(){Object.defineProperty(this,To,{value:xo}),this.state={},Object.defineProperty(this,Po,{writable:!0,value:new Set})}getState(){return this.state}setState(e){const t={...this.state},n={...this.state,...e};this.state=n,bo(this,To)[To](t,n,e)}subscribe(e){return bo(this,Po)[Po].add(e),()=>{bo(this,Po)[Po].delete(e)}}}function xo(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];bo(this,Po)[Po].forEach(e=>{e(...t)})}function Co(e){const t=e.lastIndexOf(".");return-1===t||t===e.length-1?{name:e,extension:void 0}:{name:e.slice(0,t),extension:e.slice(t+1)}}ko.VERSION="3.2.2";var Oo={__proto__:null,md:"text/markdown",markdown:"text/markdown",mp4:"video/mp4",mp3:"audio/mp3",svg:"image/svg+xml",jpg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",heic:"image/heic",heif:"image/heif",yaml:"text/yaml",yml:"text/yaml",csv:"text/csv",tsv:"text/tab-separated-values",tab:"text/tab-separated-values",avi:"video/x-msvideo",mks:"video/x-matroska",mkv:"video/x-matroska",mov:"video/quicktime",dicom:"application/dicom",doc:"application/msword",docm:"application/vnd.ms-word.document.macroenabled.12",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",dot:"application/msword",dotm:"application/vnd.ms-word.template.macroenabled.12",dotx:"application/vnd.openxmlformats-officedocument.wordprocessingml.template",xla:"application/vnd.ms-excel",xlam:"application/vnd.ms-excel.addin.macroenabled.12",xlc:"application/vnd.ms-excel",xlf:"application/x-xliff+xml",xlm:"application/vnd.ms-excel",xls:"application/vnd.ms-excel",xlsb:"application/vnd.ms-excel.sheet.binary.macroenabled.12",xlsm:"application/vnd.ms-excel.sheet.macroenabled.12",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xlt:"application/vnd.ms-excel",xltm:"application/vnd.ms-excel.template.macroenabled.12",xltx:"application/vnd.openxmlformats-officedocument.spreadsheetml.template",xlw:"application/vnd.ms-excel",txt:"text/plain",text:"text/plain",conf:"text/plain",log:"text/plain",pdf:"application/pdf",zip:"application/zip","7z":"application/x-7z-compressed",rar:"application/x-rar-compressed",tar:"application/x-tar",gz:"application/gzip",dmg:"application/x-apple-diskimage"};function jo(e){var t;if(e.type)return e.type;const n=e.name?null==(t=Co(e.name).extension)?void 0:t.toLowerCase():null;return n&&n in Oo?Oo[n]:"application/octet-stream"}function Ro(e){let t="";return e.replace(/[^A-Z0-9]/gi,e=>(t+=`-${function(e){return e.charCodeAt(0).toString(32)}(e)}`,"/"))+t}function Ao(e,t){if(function(e){return!(!e.isRemote||!e.remote)&&new Set(["box","dropbox","drive","facebook","unsplash"]).has(e.remote.provider)}(e))return e.id;const n=jo(e);return function(e,t){let n=t||"uppy";return"string"==typeof e.name&&(n+=`-${Ro(e.name.toLowerCase())}`),void 0!==e.type&&(n+=`-${e.type}`),e.meta&&"string"==typeof e.meta.relativePath&&(n+=`-${Ro(e.meta.relativePath.toLowerCase())}`),void 0!==e.data.size&&(n+=`-${e.data.size}`),void 0!==e.data.lastModified&&(n+=`-${e.data.lastModified}`),n}({...e,type:n},t)}function No(e){if(null==e&&"undefined"!=typeof navigator&&(e=navigator.userAgent),!e)return!0;const t=/Edge\/(\d+\.\d+)/.exec(e);if(!t)return!0;const n=t[1].split(".",2),r=parseInt(n[0],10),o=parseInt(n[1],10);return r<15||15===r&&o<15063||(r>18||18===r&&o>=18218)}function Fo(e){return e<10?`0${e}`:e.toString()}function Io(){const e=new Date;return`${Fo(e.getHours())}:${Fo(e.getMinutes())}:${Fo(e.getSeconds())}`}const Mo={debug:()=>{},warn:()=>{},error:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return console.error(`[Uppy] [${Io()}]`,...t)}},Uo={debug:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return console.debug(`[Uppy] [${Io()}]`,...t)},warn:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return console.warn(`[Uppy] [${Io()}]`,...t)},error:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return console.error(`[Uppy] [${Io()}]`,...t)}};var Lo,zo;var Do,Bo,$o,qo,Wo=(zo||(zo=1,Lo=function(e){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("Expected a number, got "+typeof e);const t=e<0;let n=Math.abs(e);if(t&&(n=-n),0===n)return"0 B";const r=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],o=Math.min(Math.floor(Math.log(n)/Math.log(1024)),r.length-1),i=Number(n/1024**o),s=r[o];return`${i>=10||i%1==0?Math.round(i):i.toFixed(1)} ${s}`}),Lo),Ho=r.getDefaultExportFromCjs(Wo);function Vo(){if(Bo)return Do;function e(e,t){this.text=e=e||"",this.hasWild=~e.indexOf("*"),this.separator=t,this.parts=e.split(t)}return Bo=1,e.prototype.match=function(e){var t,n,r=!0,o=this.parts,i=o.length;if("string"==typeof e||e instanceof String)if(this.hasWild||this.text==e){for(n=(e||"").split(this.separator),t=0;r&&t<i;t++)"*"!==o[t]&&(r=t<n.length&&o[t]===n[t]);r=r&&n}else r=!1;else if("function"==typeof e.splice)for(r=[],t=e.length;t--;)this.match(e[t])&&(r[r.length]=e[t]);else if("object"==typeof e)for(var s in r={},e)this.match(s)&&(r[s]=e[s]);return r},Do=function(t,n,r){var o=new e(t,r||/[\/\.]/);return void 0!==n?o.match(n):o},Do}var Ko=function(){if(qo)return $o;qo=1;var e=Vo(),t=/[\/\+\.]/;return $o=function(n,r){function o(r){var o=e(r,n,t);return o&&o.length>=2}return r?o(r.split(";")[0]):o},$o}(),Yo=r.getDefaultExportFromCjs(Ko);const Go={maxFileSize:null,minFileSize:null,maxTotalFileSize:null,maxNumberOfFiles:null,minNumberOfFiles:null,allowedFileTypes:null,requiredMetaFields:[]};class Jo extends Error{constructor(e,t){var n;super(e),this.isRestriction=!0,this.isUserFacing=null==(n=null==t?void 0:t.isUserFacing)||n,null!=t&&t.file&&(this.file=t.file)}}class Xo{constructor(e,t){this.getI18n=t,this.getOpts=()=>{var t;const n=e();if(null!=(null==(t=n.restrictions)?void 0:t.allowedFileTypes)&&!Array.isArray(n.restrictions.allowedFileTypes))throw new TypeError("`restrictions.allowedFileTypes` must be an array");return n}}validateAggregateRestrictions(e,t){const{maxTotalFileSize:n,maxNumberOfFiles:r}=this.getOpts().restrictions;if(r){if(e.filter(e=>!e.isGhost).length+t.length>r)throw new Jo(`${this.getI18n()("youCanOnlyUploadX",{smart_count:r})}`)}if(n){const r=[...e,...t].reduce((e,t)=>{var n;return e+(null!=(n=t.size)?n:0)},0);if(r>n)throw new Jo(this.getI18n()("aggregateExceedsSize",{sizeAllowed:Ho(n),size:Ho(r)}))}}validateSingleFile(e){const{maxFileSize:t,minFileSize:n,allowedFileTypes:r}=this.getOpts().restrictions;if(r){if(!r.some(t=>t.includes("/")?!!e.type&&Yo(e.type.replace(/;.*?$/,""),t):!("."!==t[0]||!e.extension)&&e.extension.toLowerCase()===t.slice(1).toLowerCase())){const t=r.join(", ");throw new Jo(this.getI18n()("youCanOnlyUploadFileTypes",{types:t}),{file:e})}}if(t&&null!=e.size&&e.size>t)throw new Jo(this.getI18n()("exceedsSize",{size:Ho(t),file:e.name}),{file:e});if(n&&null!=e.size&&e.size<n)throw new Jo(this.getI18n()("inferiorSize",{size:Ho(n)}),{file:e})}validate(e,t){t.forEach(e=>{this.validateSingleFile(e)}),this.validateAggregateRestrictions(e,t)}validateMinNumberOfFiles(e){const{minNumberOfFiles:t}=this.getOpts().restrictions;if(t&&Object.keys(e).length<t)throw new Jo(this.getI18n()("youHaveToAtLeastSelectX",{smart_count:t}))}getMissingRequiredMetaFields(e){const t=new Jo(this.getI18n()("missingRequiredMetaFieldOnFile",{fileName:e.name})),{requiredMetaFields:n}=this.getOpts().restrictions,r=[];for(const t of n)Object.hasOwn(e.meta,t)&&""!==e.meta[t]||r.push(t);return{missingFields:r,error:t}}}var Qo={strings:{addBulkFilesFailed:{0:"Failed to add %{smart_count} file due to an internal error",1:"Failed to add %{smart_count} files due to internal errors"},youCanOnlyUploadX:{0:"You can only upload %{smart_count} file",1:"You can only upload %{smart_count} files"},youHaveToAtLeastSelectX:{0:"You have to select at least %{smart_count} file",1:"You have to select at least %{smart_count} files"},aggregateExceedsSize:"You selected %{size} of files, but maximum allowed size is %{sizeAllowed}",exceedsSize:"%{file} exceeds maximum allowed size of %{size}",missingRequiredMetaField:"Missing required meta fields",missingRequiredMetaFieldOnFile:"Missing required meta fields in %{fileName}",inferiorSize:"This file is smaller than the allowed size of %{size}",youCanOnlyUploadFileTypes:"You can only upload: %{types}",noMoreFilesAllowed:"Cannot add more files",noDuplicates:"Cannot add the duplicate file '%{fileName}', it already exists",companionError:"Connection with Companion failed",authAborted:"Authentication aborted",companionUnauthorizeHint:"To unauthorize to your %{provider} account, please go to %{url}",failedToUpload:"Failed to upload %{file}",noInternetConnection:"No Internet connection",connectedToInternet:"Connected to the Internet",noFilesFound:"You have no files or folders here",noSearchResults:"Unfortunately, there are no results for this search",selectX:{0:"Select %{smart_count}",1:"Select %{smart_count}"},allFilesFromFolderNamed:"All files from folder %{name}",openFolderNamed:"Open folder %{name}",cancel:"Cancel",logOut:"Log out",filter:"Filter",resetFilter:"Reset filter",loading:"Loading...",loadedXFiles:"Loaded %{numFiles} files",authenticateWithTitle:"Please authenticate with %{pluginName} to select files",authenticateWith:"Connect to %{pluginName}",signInWithGoogle:"Sign in with Google",searchImages:"Search for images",enterTextToSearch:"Enter text to search for images",search:"Search",resetSearch:"Reset search",emptyFolderAdded:"No files were added from empty folder",addedNumFiles:"Added %{numFiles} file(s)",folderAlreadyAdded:'The folder "%{folder}" was already added',folderAdded:{0:"Added %{smart_count} file from %{folder}",1:"Added %{smart_count} files from %{folder}"},additionalRestrictionsFailed:"%{count} additional restrictions were not fulfilled",unnamed:"Unnamed"}};let Zo,ei;function ti(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var ni=0;function ri(e){return"__private_"+ni+++"_"+e}const oi={totalProgress:0,allowNewUpload:!0,error:null,recoveredState:null};var ii=ri("plugins"),si=ri("restricter"),ai=ri("storeUnsubscribe"),li=ri("emitter"),ci=ri("preProcessors"),ui=ri("uploaders"),di=ri("postProcessors"),hi=ri("informAndEmit"),pi=ri("checkRequiredMetaFieldsOnFile"),_i=ri("checkRequiredMetaFields"),fi=ri("assertNewUploadAllowed"),mi=ri("transformFile"),gi=ri("startIfAutoProceed"),yi=ri("checkAndUpdateFileState"),vi=ri("addListeners"),wi=ri("updateOnlineStatus"),bi=ri("requestClientById"),Si=ri("createUpload"),Ei=ri("getUpload"),Pi=ri("removeUpload"),Ti=ri("runUpload");Zo=Symbol.for("uppy test: getPlugins"),ei=Symbol.for("uppy test: createUpload");class ki{constructor(e){Object.defineProperty(this,Ti,{value:Li}),Object.defineProperty(this,Pi,{value:Ui}),Object.defineProperty(this,Ei,{value:Mi}),Object.defineProperty(this,Si,{value:Ii}),Object.defineProperty(this,vi,{value:Fi}),Object.defineProperty(this,yi,{value:Ni}),Object.defineProperty(this,gi,{value:Ai}),Object.defineProperty(this,mi,{value:Ri}),Object.defineProperty(this,fi,{value:ji}),Object.defineProperty(this,_i,{value:Oi}),Object.defineProperty(this,pi,{value:Ci}),Object.defineProperty(this,hi,{value:xi}),Object.defineProperty(this,ii,{writable:!0,value:Object.create(null)}),Object.defineProperty(this,si,{writable:!0,value:void 0}),Object.defineProperty(this,ai,{writable:!0,value:void 0}),Object.defineProperty(this,li,{writable:!0,value:Fr()}),Object.defineProperty(this,ci,{writable:!0,value:new Set}),Object.defineProperty(this,ui,{writable:!0,value:new Set}),Object.defineProperty(this,di,{writable:!0,value:new Set}),this.scheduledAutoProceed=null,this.wasOffline=!1,this.calculateProgress=wo((e,t)=>{const n=this.getFile(null==e?void 0:e.id);if(null==e||!n)return void this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`);if(100===n.progress.percentage)return void this.log(`Not setting progress for a file that has been already uploaded: ${e.id}`);const r=Number.isFinite(t.bytesTotal)&&t.bytesTotal>0;this.setFileState(e.id,{progress:{...n.progress,bytesUploaded:t.bytesUploaded,bytesTotal:t.bytesTotal,percentage:r?Math.round(t.bytesUploaded/t.bytesTotal*100):0}}),this.calculateTotalProgress()},500,{leading:!0,trailing:!0}),Object.defineProperty(this,wi,{writable:!0,value:this.updateOnlineStatus.bind(this)}),Object.defineProperty(this,bi,{writable:!0,value:new Map}),this.defaultLocale=Qo;const t={id:"uppy",autoProceed:!1,allowMultipleUploadBatches:!0,debug:!1,restrictions:Go,meta:{},onBeforeFileAdded:(e,t)=>!Object.hasOwn(t,e.id),onBeforeUpload:e=>e,store:new ko,logger:Mo,infoTimeout:5e3},n={...t,...e};this.opts={...n,restrictions:{...t.restrictions,...e&&e.restrictions}},e&&e.logger&&e.debug?this.log("You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.","warning"):e&&e.debug&&(this.opts.logger=Uo),this.log(`Using Core v${ki.VERSION}`),this.i18nInit(),this.store=this.opts.store,this.setState({...oi,plugins:{},files:{},currentUploads:{},capabilities:{uploadProgress:No(),individualCancellation:!0,resumableUploads:!1},meta:{...this.opts.meta},info:[]}),ti(this,si)[si]=new Xo(()=>this.opts,()=>this.i18n),ti(this,ai)[ai]=this.store.subscribe((e,t,n)=>{this.emit("state-update",e,t,n),this.updateAll(t)}),this.opts.debug&&"undefined"!=typeof window&&(window[this.opts.id]=this),ti(this,vi)[vi]()}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];ti(this,li)[li].emit(e,...n)}on(e,t){return ti(this,li)[li].on(e,t),this}once(e,t){return ti(this,li)[li].once(e,t),this}off(e,t){return ti(this,li)[li].off(e,t),this}updateAll(e){this.iteratePlugins(t=>{t.update(e)})}setState(e){this.store.setState(e)}getState(){return this.store.getState()}patchFilesState(e){const t=this.getState().files;this.setState({files:{...t,...Object.fromEntries(Object.entries(e).map(e=>{let[n,r]=e;return[n,{...t[n],...r}]}))}})}setFileState(e,t){if(!this.getState().files[e])throw new Error(`Can’t set state for ${e} (the file could have been removed)`);this.patchFilesState({[e]:t})}i18nInit(){const e=new Rr([this.defaultLocale,this.opts.locale],{onMissingKey:e=>this.log(`Missing i18n string: ${e}`,"error")});this.i18n=e.translate.bind(e),this.i18nArray=e.translateArray.bind(e),this.locale=e.locale}setOptions(e){this.opts={...this.opts,...e,restrictions:{...this.opts.restrictions,...null==e?void 0:e.restrictions}},e.meta&&this.setMeta(e.meta),this.i18nInit(),e.locale&&this.iteratePlugins(t=>{t.setOptions(e)}),this.setState(void 0)}resetProgress(){const e={percentage:0,bytesUploaded:0,uploadComplete:!1,uploadStarted:null},t={...this.getState().files},n={};Object.keys(t).forEach(r=>{n[r]={...t[r],progress:{...t[r].progress,...e}}}),this.setState({files:n,...oi}),this.emit("reset-progress")}clearUploadedFiles(){const{capabilities:e,currentUploads:t}=this.getState();if(Object.keys(t).length>0&&!e.individualCancellation)throw new Error("The installed uploader plugin does not allow removing files during an upload.");this.setState({...oi,files:{}})}addPreProcessor(e){ti(this,ci)[ci].add(e)}removePreProcessor(e){return ti(this,ci)[ci].delete(e)}addPostProcessor(e){ti(this,di)[di].add(e)}removePostProcessor(e){return ti(this,di)[di].delete(e)}addUploader(e){ti(this,ui)[ui].add(e)}removeUploader(e){return ti(this,ui)[ui].delete(e)}setMeta(e){const t={...this.getState().meta,...e},n={...this.getState().files};Object.keys(n).forEach(t=>{n[t]={...n[t],meta:{...n[t].meta,...e}}}),this.log("Adding metadata:"),this.log(e),this.setState({meta:t,files:n})}setFileMeta(e,t){const n={...this.getState().files};if(!n[e])return void this.log("Was trying to set metadata for a file that has been removed: ",e);const r={...n[e].meta,...t};n[e]={...n[e],meta:r},this.setState({files:n})}getFile(e){return this.getState().files[e]}getFiles(){const{files:e}=this.getState();return Object.values(e)}getFilesByIds(e){return e.map(e=>this.getFile(e))}getObjectOfFilesPerState(){const{files:e,totalProgress:t,error:n}=this.getState(),r=Object.values(e),o=[],i=[],s=[],a=[],l=[],c=[],u=[],d=[],h=[];for(const e of r){const{progress:t}=e;!t.uploadComplete&&t.uploadStarted&&(o.push(e),e.isPaused||d.push(e)),t.uploadStarted||i.push(e),(t.uploadStarted||t.preprocess||t.postprocess)&&s.push(e),t.uploadStarted&&a.push(e),e.isPaused&&l.push(e),t.uploadComplete&&c.push(e),e.error&&u.push(e),(t.preprocess||t.postprocess)&&h.push(e)}return{newFiles:i,startedFiles:s,uploadStartedFiles:a,pausedFiles:l,completeFiles:c,erroredFiles:u,inProgressFiles:o,inProgressNotPausedFiles:d,processingFiles:h,isUploadStarted:a.length>0,isAllComplete:100===t&&c.length===r.length&&0===h.length,isAllErrored:!!n&&u.length===r.length,isAllPaused:0!==o.length&&l.length===o.length,isUploadInProgress:o.length>0,isSomeGhost:r.some(e=>e.isGhost)}}validateRestrictions(e,t){void 0===t&&(t=this.getFiles());try{ti(this,si)[si].validate(t,[e])}catch(e){return e}return null}checkIfFileAlreadyExists(e){const{files:t}=this.getState();return!(!t[e]||t[e].isGhost)}addFile(e){ti(this,fi)[fi](e);const{nextFilesState:t,validFilesToAdd:n,errors:r}=ti(this,yi)[yi]([e]),o=r.filter(e=>e.isRestriction);if(ti(this,hi)[hi](o),r.length>0)throw r[0];this.setState({files:t});const[i]=n;return this.emit("file-added",i),this.emit("files-added",n),this.log(`Added file: ${i.name}, ${i.id}, mime type: ${i.type}`),ti(this,gi)[gi](),i.id}addFiles(e){ti(this,fi)[fi]();const{nextFilesState:t,validFilesToAdd:n,errors:r}=ti(this,yi)[yi](e),o=r.filter(e=>e.isRestriction);ti(this,hi)[hi](o);const i=r.filter(e=>!e.isRestriction);if(i.length>0){let e="Multiple errors occurred while adding files:\n";if(i.forEach(t=>{e+=`\n * ${t.message}`}),this.info({message:this.i18n("addBulkFilesFailed",{smart_count:i.length}),details:e},"error",this.opts.infoTimeout),"function"==typeof AggregateError)throw new AggregateError(i,e);{const t=new Error(e);throw t.errors=i,t}}this.setState({files:t}),n.forEach(e=>{this.emit("file-added",e)}),this.emit("files-added",n),n.length>5?this.log(`Added batch of ${n.length} files`):Object.values(n).forEach(e=>{this.log(`Added file: ${e.name}\n id: ${e.id}\n type: ${e.type}`)}),n.length>0&&ti(this,gi)[gi]()}removeFiles(e,t){const{files:n,currentUploads:r}=this.getState(),o={...n},i={...r},s=Object.create(null);function a(e){return void 0===s[e]}e.forEach(e=>{n[e]&&(s[e]=n[e],delete o[e])}),Object.keys(i).forEach(e=>{const t=r[e].fileIDs.filter(a);if(0===t.length)return void delete i[e];const{capabilities:n}=this.getState();if(t.length!==r[e].fileIDs.length&&!n.individualCancellation)throw new Error("The installed uploader plugin does not allow removing files during an upload.");i[e]={...r[e],fileIDs:t}});const l={currentUploads:i,files:o};0===Object.keys(o).length&&(l.allowNewUpload=!0,l.error=null,l.recoveredState=null),this.setState(l),this.calculateTotalProgress();const c=Object.keys(s);c.forEach(e=>{this.emit("file-removed",s[e],t)}),c.length>5?this.log(`Removed ${c.length} files`):this.log(`Removed files: ${c.join(", ")}`)}removeFile(e,t){this.removeFiles([e],t)}pauseResume(e){if(!this.getState().capabilities.resumableUploads||this.getFile(e).progress.uploadComplete)return;const t=!(this.getFile(e).isPaused||!1);return this.setFileState(e,{isPaused:t}),this.emit("upload-pause",e,t),t}pauseAll(){const e={...this.getState().files};Object.keys(e).filter(t=>!e[t].progress.uploadComplete&&e[t].progress.uploadStarted).forEach(t=>{const n={...e[t],isPaused:!0};e[t]=n}),this.setState({files:e}),this.emit("pause-all")}resumeAll(){const e={...this.getState().files};Object.keys(e).filter(t=>!e[t].progress.uploadComplete&&e[t].progress.uploadStarted).forEach(t=>{const n={...e[t],isPaused:!1,error:null};e[t]=n}),this.setState({files:e}),this.emit("resume-all")}retryAll(){const e={...this.getState().files},t=Object.keys(e).filter(t=>e[t].error);if(t.forEach(t=>{const n={...e[t],isPaused:!1,error:null};e[t]=n}),this.setState({files:e,error:null}),this.emit("retry-all",t),0===t.length)return Promise.resolve({successful:[],failed:[]});const n=ti(this,Si)[Si](t,{forceAllowNewUpload:!0});return ti(this,Ti)[Ti](n)}cancelAll(e){let{reason:t="user"}=void 0===e?{}:e;if(this.emit("cancel-all",{reason:t}),"user"===t){const{files:e}=this.getState(),t=Object.keys(e);t.length&&this.removeFiles(t,"cancel-all"),this.setState(oi)}}retryUpload(e){this.setFileState(e,{error:null,isPaused:!1}),this.emit("upload-retry",e);const t=ti(this,Si)[Si]([e],{forceAllowNewUpload:!0});return ti(this,Ti)[Ti](t)}logout(){this.iteratePlugins(e=>{var t;null==(t=e.provider)||null==t.logout||t.logout()})}calculateTotalProgress(){const e=this.getFiles().filter(e=>e.progress.uploadStarted||e.progress.preprocess||e.progress.postprocess);if(0===e.length)return this.emit("progress",0),void this.setState({totalProgress:0});const t=e.filter(e=>null!=e.progress.bytesTotal),n=e.filter(e=>null==e.progress.bytesTotal);if(0===t.length){const t=100*e.length,r=n.reduce((e,t)=>e+t.progress.percentage,0),o=Math.round(r/t*100);return void this.setState({totalProgress:o})}let r=t.reduce((e,t)=>{var n;return e+(null!=(n=t.progress.bytesTotal)?n:0)},0);const o=r/t.length;r+=o*n.length;let i=0;t.forEach(e=>{i+=e.progress.bytesUploaded}),n.forEach(e=>{i+=o*(e.progress.percentage||0)/100});let s=0===r?0:Math.round(i/r*100);s>100&&(s=100),this.setState({totalProgress:s}),this.emit("progress",s)}updateOnlineStatus(){var e;null==(e=window.navigator.onLine)||e?(this.emit("is-online"),this.wasOffline&&(this.emit("back-online"),this.info(this.i18n("connectedToInternet"),"success",3e3),this.wasOffline=!1)):(this.emit("is-offline"),this.info(this.i18n("noInternetConnection"),"error",0),this.wasOffline=!0)}getID(){return this.opts.id}use(e,t){if("function"!=typeof e){throw new TypeError(`Expected a plugin class, but got ${null===e?"null":typeof e}. Please verify that the plugin was imported and spelled correctly.`)}const n=new e(this,t),r=n.id;if(!r)throw new Error("Your plugin must have an id");if(!n.type)throw new Error("Your plugin must have a type");const o=this.getPlugin(r);if(o){const e=`Already found a plugin named '${o.id}'. Tried to use: '${r}'.\nUppy plugins must have unique \`id\` options. See https://uppy.io/docs/plugins/#id.`;throw new Error(e)}return e.VERSION&&this.log(`Using ${r} v${e.VERSION}`),n.type in ti(this,ii)[ii]?ti(this,ii)[ii][n.type].push(n):ti(this,ii)[ii][n.type]=[n],n.install(),this.emit("plugin-added",n),this}getPlugin(e){for(const t of Object.values(ti(this,ii)[ii])){const n=t.find(t=>t.id===e);if(null!=n)return n}}[Zo](e){return ti(this,ii)[ii][e]}iteratePlugins(e){Object.values(ti(this,ii)[ii]).flat(1).forEach(e)}removePlugin(e){this.log(`Removing plugin ${e.id}`),this.emit("plugin-remove",e),e.uninstall&&e.uninstall();const t=ti(this,ii)[ii][e.type],n=t.findIndex(t=>t.id===e.id);-1!==n&&t.splice(n,1);const r={plugins:{...this.getState().plugins,[e.id]:void 0}};this.setState(r)}close(e){let{reason:t}=void 0===e?{}:e;this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`),this.cancelAll({reason:t}),ti(this,ai)[ai](),this.iteratePlugins(e=>{this.removePlugin(e)}),"undefined"!=typeof window&&window.removeEventListener&&(window.removeEventListener("online",ti(this,wi)[wi]),window.removeEventListener("offline",ti(this,wi)[wi]))}hideInfo(){const{info:e}=this.getState();this.setState({info:e.slice(1)}),this.emit("info-hidden")}info(e,t,n){void 0===t&&(t="info"),void 0===n&&(n=3e3);const r="object"==typeof e;this.setState({info:[...this.getState().info,{type:t,message:r?e.message:e,details:r?e.details:null}]}),setTimeout(()=>this.hideInfo(),n),this.emit("info-visible")}log(e,t){const{logger:n}=this.opts;switch(t){case"error":n.error(e);break;case"warning":n.warn(e);break;default:n.debug(e)}}registerRequestClient(e,t){ti(this,bi)[bi].set(e,t)}getRequestClientForFile(e){if(!e.remote)throw new Error(`Tried to get RequestClient for a non-remote file ${e.id}`);const t=ti(this,bi)[bi].get(e.remote.requestClientId);if(null==t)throw new Error(`requestClientId "${e.remote.requestClientId}" not registered for file "${e.id}"`);return t}restore(e){return this.log(`Core: attempting to restore upload "${e}"`),this.getState().currentUploads[e]?ti(this,Ti)[Ti](e):(ti(this,Pi)[Pi](e),Promise.reject(new Error("Nonexistent upload")))}[ei](){return ti(this,Si)[Si](...arguments)}addResultData(e,t){if(!ti(this,Ei)[Ei](e))return void this.log(`Not setting result for an upload that has been removed: ${e}`);const{currentUploads:n}=this.getState(),r={...n[e],result:{...n[e].result,...t}};this.setState({currentUploads:{...n,[e]:r}})}upload(){var e;null!=(e=ti(this,ii)[ii].uploader)&&e.length||this.log("No uploader type plugins are used","warning");let{files:t}=this.getState();const n=this.opts.onBeforeUpload(t);return!1===n?Promise.reject(new Error("Not starting the upload because onBeforeUpload returned false")):(n&&"object"==typeof n&&(t=n,this.setState({files:t})),Promise.resolve().then(()=>ti(this,si)[si].validateMinNumberOfFiles(t)).catch(e=>{throw ti(this,hi)[hi]([e]),e}).then(()=>{if(!ti(this,_i)[_i](t))throw new Jo(this.i18n("missingRequiredMetaField"))}).catch(e=>{throw e}).then(()=>{const{currentUploads:e}=this.getState(),n=Object.values(e).flatMap(e=>e.fileIDs),r=[];Object.keys(t).forEach(e=>{const t=this.getFile(e);t.progress.uploadStarted||-1!==n.indexOf(e)||r.push(t.id)});const o=ti(this,Si)[Si](r);return ti(this,Ti)[Ti](o)}).catch(e=>{throw this.emit("error",e),this.log(e,"error"),e}))}}function xi(e){for(const t of e)t.isRestriction?this.emit("restriction-failed",t.file,t):this.emit("error",t,t.file),this.log(t,"warning");const t=e.filter(e=>e.isUserFacing),n=t.slice(0,4),r=t.slice(4);n.forEach(e=>{let{message:t,details:n=""}=e;this.info({message:t,details:n},"error",this.opts.infoTimeout)}),r.length>0&&this.info({message:this.i18n("additionalRestrictionsFailed",{count:r.length})})}function Ci(e){const{missingFields:t,error:n}=ti(this,si)[si].getMissingRequiredMetaFields(e);return!(t.length>0)||(this.setFileState(e.id,{missingRequiredMetaFields:t}),this.log(n.message),this.emit("restriction-failed",e,n),!1)}function Oi(e){let t=!0;for(const n of Object.values(e))ti(this,pi)[pi](n)||(t=!1);return t}function ji(e){const{allowNewUpload:t}=this.getState();if(!1===t){const t=new Jo(this.i18n("noMoreFilesAllowed"),{file:e});throw ti(this,hi)[hi]([t]),t}}function Ri(e){const t=e instanceof File?{name:e.name,type:e.type,size:e.size,data:e}:e,n=jo(t),r=function(e,t){return t.name?t.name:"image"===e.split("/")[0]?`${e.split("/")[0]}.${e.split("/")[1]}`:"noname"}(n,t),o=Co(r).extension,i=Ao(t,this.getID()),s=t.meta||{};s.name=r,s.type=n;const a=Number.isFinite(t.data.size)?t.data.size:null;return{source:t.source||"",id:i,name:r,extension:o||"",meta:{...this.getState().meta,...s},type:n,data:t.data,progress:{percentage:0,bytesUploaded:0,bytesTotal:a,uploadComplete:!1,uploadStarted:null},size:a,isGhost:!1,isRemote:t.isRemote||!1,remote:t.remote||"",preview:t.preview}}function Ai(){this.opts.autoProceed&&!this.scheduledAutoProceed&&(this.scheduledAutoProceed=setTimeout(()=>{this.scheduledAutoProceed=null,this.upload().catch(e=>{e.isRestriction||this.log(e.stack||e.message||e)})},4))}function Ni(e){const{files:t}=this.getState(),n={...t},r=[],o=[];for(const s of e)try{var i;let e=ti(this,mi)[mi](s);const o=null==(i=t[e.id])?void 0:i.isGhost;if(o){e={...t[e.id],isGhost:!1,data:s.data},this.log(`Replaced the blob in the restored ghost file: ${e.name}, ${e.id}`)}const a=this.opts.onBeforeFileAdded(e,n);if(!a&&this.checkIfFileAlreadyExists(e.id))throw new Jo(this.i18n("noDuplicates",{fileName:e.name}),{file:s});if(!1===a&&!o)throw new Jo("Cannot add the file because onBeforeFileAdded returned false.",{isUserFacing:!1,file:s});"object"==typeof a&&null!==a&&(e=a),ti(this,si)[si].validateSingleFile(e),n[e.id]=e,r.push(e)}catch(e){o.push(e)}try{ti(this,si)[si].validateAggregateRestrictions(Object.values(t),r)}catch(e){return o.push(e),{nextFilesState:t,validFilesToAdd:[],errors:o}}return{nextFilesState:n,validFilesToAdd:r,errors:o}}function Fi(){const e=(e,t,n)=>{let r=e.message||"Unknown error";e.details&&(r+=` ${e.details}`),this.setState({error:r}),null!=t&&t.id in this.getState().files&&this.setFileState(t.id,{error:r,response:n})};this.on("error",e),this.on("upload-error",(t,n,r)=>{if(e(n,t,r),"object"==typeof n&&n.message){var o;this.log(n.message,"error");const e=new Error(this.i18n("failedToUpload",{file:null!=(o=null==t?void 0:t.name)?o:""}));e.isUserFacing=!0,e.details=n.message,n.details&&(e.details+=` ${n.details}`),ti(this,hi)[hi]([e])}else ti(this,hi)[hi]([n])});let t=null;this.on("upload-stalled",(e,n)=>{const{message:r}=e,o=n.map(e=>e.meta.name).join(", ");t||(this.info({message:r,details:o},"warning",this.opts.infoTimeout),t=setTimeout(()=>{t=null},this.opts.infoTimeout)),this.log(`${r} ${o}`.trim(),"warning")}),this.on("upload",()=>{this.setState({error:null})});const n=e=>{const t=e.filter(e=>{const t=null!=e&&this.getFile(e.id);return t||this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`),t}),n=Object.fromEntries(t.map(e=>[e.id,{progress:{uploadStarted:Date.now(),uploadComplete:!1,percentage:0,bytesUploaded:0,bytesTotal:e.size}}]));this.patchFilesState(n)};this.on("upload-start",e=>{e.forEach(e=>{this.emit("upload-started",e)}),n(e)}),this.on("upload-progress",this.calculateProgress),this.on("upload-success",(e,t)=>{if(null==e||!this.getFile(e.id))return void this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`);const n=this.getFile(e.id).progress;this.setFileState(e.id,{progress:{...n,postprocess:ti(this,di)[di].size>0?{mode:"indeterminate"}:void 0,uploadComplete:!0,percentage:100,bytesUploaded:n.bytesTotal},response:t,uploadURL:t.uploadURL,isPaused:!1}),null==e.size&&this.setFileState(e.id,{size:t.bytesUploaded||n.bytesTotal}),this.calculateTotalProgress()}),this.on("preprocess-progress",(e,t)=>{null!=e&&this.getFile(e.id)?this.setFileState(e.id,{progress:{...this.getFile(e.id).progress,preprocess:t}}):this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`)}),this.on("preprocess-complete",e=>{if(null==e||!this.getFile(e.id))return void this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`);const t={...this.getState().files};t[e.id]={...t[e.id],progress:{...t[e.id].progress}},delete t[e.id].progress.preprocess,this.setState({files:t})}),this.on("postprocess-progress",(e,t)=>{null!=e&&this.getFile(e.id)?this.setFileState(e.id,{progress:{...this.getState().files[e.id].progress,postprocess:t}}):this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`)}),this.on("postprocess-complete",e=>{if(null==e||!this.getFile(e.id))return void this.log(`Not setting progress for a file that has been removed: ${null==e?void 0:e.id}`);const t={...this.getState().files};t[e.id]={...t[e.id],progress:{...t[e.id].progress}},delete t[e.id].progress.postprocess,this.setState({files:t})}),this.on("restored",()=>{this.calculateTotalProgress()}),this.on("dashboard:file-edit-complete",e=>{e&&ti(this,pi)[pi](e)}),"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("online",ti(this,wi)[wi]),window.addEventListener("offline",ti(this,wi)[wi]),setTimeout(ti(this,wi)[wi],3e3))}function Ii(e,t){void 0===t&&(t={});const{forceAllowNewUpload:n=!1}=t,{allowNewUpload:r,currentUploads:o}=this.getState();if(!r&&!n)throw new Error("Cannot create a new upload: already uploading.");const i=((e=21)=>{let t="",n=e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t})();return this.emit("upload",{id:i,fileIDs:e}),this.setState({allowNewUpload:!1!==this.opts.allowMultipleUploadBatches&&!1!==this.opts.allowMultipleUploads,currentUploads:{...o,[i]:{fileIDs:e,step:0,result:{}}}}),i}function Mi(e){const{currentUploads:t}=this.getState();return t[e]}function Ui(e){const t={...this.getState().currentUploads};delete t[e],this.setState({currentUploads:t})}async function Li(e){const t=()=>{const{currentUploads:t}=this.getState();return t[e]};let n=t();const r=[...ti(this,ci)[ci],...ti(this,ui)[ui],...ti(this,di)[di]];try{for(let o=n.step||0;o<r.length&&n;o++){const i=r[o];this.setState({currentUploads:{...this.getState().currentUploads,[e]:{...n,step:o}}});const{fileIDs:s}=n;await i(s,e),n=t()}}catch(t){throw ti(this,Pi)[Pi](e),t}if(n){n.fileIDs.forEach(e=>{const t=this.getFile(e);t&&t.progress.postprocess&&this.emit("postprocess-complete",t)});const r=n.fileIDs.map(e=>this.getFile(e)),o=r.filter(e=>!e.error),i=r.filter(e=>e.error);this.addResultData(e,{successful:o,failed:i,uploadID:e}),n=t()}let o;return n&&(o=n.result,this.emit("complete",o),ti(this,Pi)[Pi](e)),null==o&&this.log(`Not setting result for an upload that has been removed: ${e}`),o}ki.VERSION="3.13.1";class zi{constructor(e,t){this.uppy=e,this.opts=null!=t?t:{}}getPluginState(){const{plugins:e}=this.uppy.getState();return(null==e?void 0:e[this.id])||{}}setPluginState(e){const{plugins:t}=this.uppy.getState();this.uppy.setState({plugins:{...t,[this.id]:{...t[this.id],...e}}})}setOptions(e){this.opts={...this.opts,...e},this.setPluginState(void 0),this.i18nInit()}i18nInit(){const e=new Rr([this.defaultLocale,this.uppy.locale,this.opts.locale]);this.i18n=e.translate.bind(e),this.i18nArray=e.translateArray.bind(e),this.setPluginState(void 0)}addTarget(e){throw new Error("Extend the addTarget method to add your plugin to another plugin's target")}install(){}uninstall(){}update(e){}afterUpdate(){}}class Di extends Error{constructor(){super(...arguments),this.name="UserFacingApiError"}}var Bi,$i,qi,Wi,Hi,Vi={};function Ki(){return qi||(qi=1,e=Vi,t=function(){if($i)return Bi;function e(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return $i=1,Bi=e,e.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},e.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},e.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(void 0===n){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1)}var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0},e.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},e.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},e.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},e.prototype.start=e.prototype.try,e.prototype.errors=function(){return this._errors},e.prototype.attempts=function(){return this._attempts},e.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var o=this._errors[r],i=o.message,s=(e[i]||0)+1;e[i]=s,s>=n&&(t=o,n=s)}return t},Bi}(),e.operation=function(n){var r=e.timeouts(n);return new t(r,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],o=0;o<t.retries;o++)r.push(this.createTimeout(o,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(o,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return r=Math.min(r,t.maxTimeout)},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var o in r=[],t)"function"==typeof t[o]&&r.push(o);for(var i=0;i<r.length;i++){var s=r[i],a=t[s];t[s]=function(r){var o=e.operation(n),i=Array.prototype.slice.call(arguments,1),s=i.pop();i.push(function(e){o.retry(e)||(e&&(arguments[0]=o.mainError()),s.apply(this,arguments))}),o.attempt(function(){r.apply(t,i)})}.bind(t,a),t[s].options=n}}),Vi;var e,t}var Yi=Hi?Wi:(Hi=1,Wi=Ki()),Gi=r.getDefaultExportFromCjs(Yi);const Ji=Object.prototype.toString,Xi=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Qi(e){const t=e&&(e=>"[object Error]"===Ji.call(e))(e)&&"TypeError"===e.name&&"string"==typeof e.message;if(!t)return!1;const{message:n,stack:r}=e;return"Load failed"===n?void 0===r||"__sentry_captured__"in e:!!n.startsWith("error sending request for url")||Xi.has(n)}class Zi extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const es=(e,t,n)=>{const r=n.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=r,e};async function ts(e,t){return new Promise((n,r)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const o=Gi.operation(t),i=()=>{o.stop(),r(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",i,{once:!0});const s=()=>{t.signal?.removeEventListener("abort",i),o.stop()};o.attempt(async i=>{try{const t=await e(i);s(),n(t)}catch(e){try{if(!(e instanceof Error))throw new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(e instanceof Zi)throw e.originalError;if(e instanceof TypeError&&!Qi(e))throw e;if(es(e,i,t),await t.shouldRetry(e)||(o.stop(),r(e)),await t.onFailedAttempt(e),!o.retry(e))throw o.mainError()}catch(e){es(e,i,t),s(),r(e)}}})})}class ns extends Error{constructor(e,t){void 0===t&&(t=null),super("This looks like a network error, the endpoint might be blocked by an internet provider or a firewall."),this.cause=e,this.isNetworkError=!0,this.request=t}}function rs(e,t){return Object.prototype.hasOwnProperty.call(e,t)}class os extends Error{constructor(e,t){super(e),this.cause=null==t?void 0:t.cause,this.cause&&rs(this.cause,"isNetworkError")?this.isNetworkError=this.cause.isNetworkError:this.isNetworkError=!1}}var is=wo(function(e,t,n){const{progress:r,bytesUploaded:o,bytesTotal:i}=t;r&&(e.uppy.log(`Upload progress: ${r}`),e.uppy.emit("upload-progress",n,{uploader:e,bytesUploaded:o,bytesTotal:i}))},300,{leading:!0,trailing:!0});class ss extends Error{constructor(){super("Authorization required"),this.name="AuthError",this.isAuthError=!0}}let as;function ls(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var cs=0;function us(e){return"__private_"+cs+++"_"+e}class ds extends Error{constructor(e){let{statusCode:t,message:n}=e;super(n),this.name="HttpError",this.statusCode=t}}var hs=us("companionHeaders"),ps=us("getUrl"),_s=us("requestSocketToken"),fs=us("awaitRemoteFileUpload");as=Symbol.for("uppy test: getCompanionHeaders");class ms{constructor(e,t){Object.defineProperty(this,fs,{value:ys}),Object.defineProperty(this,ps,{value:gs}),Object.defineProperty(this,hs,{writable:!0,value:void 0}),Object.defineProperty(this,_s,{writable:!0,value:async e=>{var t;let{file:n,postBody:r,signal:o}=e;if(null==(null==(t=n.remote)?void 0:t.url))throw new Error("Cannot connect to an undefined URL");return(await this.post(n.remote.url,{...n.remote.body,...r},{signal:o})).token}}),this.uppy=e,this.opts=t,this.onReceiveResponse=this.onReceiveResponse.bind(this),ls(this,hs)[hs]=null==t?void 0:t.companionHeaders}setCompanionHeaders(e){ls(this,hs)[hs]=e}[as](){return ls(this,hs)[hs]}get hostname(){const{companion:e}=this.uppy.getState(),t=this.opts.companionUrl;return function(e){return e.replace(/\/$/,"")}(e&&e[t]?e[t]:t)}async headers(e){void 0===e&&(e=!1);return{...{Accept:"application/json",...e?void 0:{"Content-Type":"application/json"}},...ls(this,hs)[hs]}}onReceiveResponse(e){const{headers:t}=e,n=this.uppy.getState().companion||{},r=this.opts.companionUrl;t.has("i-am")&&t.get("i-am")!==n[r]&&this.uppy.setState({companion:{...n,[r]:t.get("i-am")}})}async request(e){let{path:t,method:n="GET",data:r,skipPostResponse:o,signal:i}=e;try{const e=await this.headers(!r),s=await function(){return fetch(...arguments).catch(e=>{throw"AbortError"===e.name?e:new ns(e)})}(ls(this,ps)[ps](t),{method:n,signal:i,headers:e,credentials:this.opts.companionCookiesRule||"same-origin",body:r?JSON.stringify(r):null});return o||this.onReceiveResponse(s),await async function(e){if(401===e.status)throw new ss;if(e.ok)return e.json();let t,n=`Failed request with status: ${e.status}. ${e.statusText}`;try{t=await e.json(),t.message&&(n=`${n} message: ${t.message}`),t.requestId&&(n=`${n} request-Id: ${t.requestId}`)}catch(e){throw new Error(n,{cause:e})}if(e.status>=400&&e.status<=499&&t.message)throw new Di(t.message);throw new ds({statusCode:e.status,message:n})}(s)}catch(e){if(e.isAuthError||"UserFacingApiError"===e.name||"AbortError"===e.name)throw e;throw new os(`Could not ${n} ${ls(this,ps)[ps](t)}`,{cause:e})}}async get(e,t){return"boolean"==typeof t&&(t={skipPostResponse:t}),this.request({...t,path:e})}async post(e,t,n){return"boolean"==typeof n&&(n={skipPostResponse:n}),this.request({...n,path:e,method:"POST",data:t})}async delete(e,t,n){return"boolean"==typeof n&&(n={skipPostResponse:n}),this.request({...n,path:e,method:"DELETE",data:t})}async uploadRemoteFile(e,t,n){var r=this;try{const{signal:o,getQueue:i}=n||{};return await ts(async()=>{var n;const s=null==(n=this.uppy.getFile(e.id))?void 0:n.serverToken;if(null!=s)return this.uppy.log(`Connecting to exiting websocket ${s}`),ls(this,fs)[fs]({file:e,queue:i(),signal:o});const a=i().wrapPromiseFunction(async function(){try{return await ls(r,_s)[_s](...arguments)}catch(e){if(e.isAuthError)throw new Zi(e);if(null==e.cause)throw e;const t=e.cause,n=()=>[408,409,429,418,423].includes(t.statusCode)||t.statusCode>=500&&t.statusCode<=599&&![501,505].includes(t.statusCode);if("HttpError"===t.name&&!n())throw new Zi(t);throw t}},{priority:-1}),l=await a({file:e,postBody:t,signal:o}).abortOn(o);return this.uppy.getFile(e.id)?(this.uppy.setFileState(e.id,{serverToken:l}),ls(this,fs)[fs]({file:this.uppy.getFile(e.id),queue:i(),signal:o})):void 0},{retries:10,signal:o,onFailedAttempt:e=>this.uppy.log(`Retrying upload due to: ${e.message}`,"warning")})}catch(t){if("AbortError"===t.name)return;throw this.uppy.emit("upload-error",e,t),t}}}function gs(e){return/^(https?:|)\/\//.test(e)?e:`${this.hostname}/${e}`}async function ys(e){let t,{file:n,queue:r,signal:o}=e;const{capabilities:i}=this.uppy.getState();try{return await new Promise((e,s)=>{const a=n.serverToken,l=function(e){var t;const n=null==(t=/^(?:https?:\/\/|\/\/)?(?:[^@\n]+@)?(?:www\.)?([^\n]+)/i.exec(e))?void 0:t[1];return`${/^http:\/\//i.test(e)?"ws":"wss"}://${n}`}(n.remote.companionUrl);let c,u,d,{isPaused:h}=n;const p=(e,t)=>{var r;null!=c&&c.readyState===c.OPEN?c.send(JSON.stringify({action:e,payload:null!=t?t:{}})):this.uppy.log(`Cannot send "${e}" to socket ${n.id} because the socket state was ${String(null==(r=c)?void 0:r.readyState)}`,"warning")};function _(){i.resumableUploads&&p(h?"pause":"resume")}const f=async()=>{u&&u.abort(),u=new AbortController;const t=e=>{var t;this.uppy.setFileState(n.id,{serverToken:null}),null==(t=u)||null==t.abort||t.abort(),s(e)};function o(){clearTimeout(d),h||(d=setTimeout(()=>t(new Error("Timeout waiting for message from Companion socket")),3e5))}try{await r.wrapPromiseFunction(async()=>{await ts(async()=>new Promise((r,i)=>{c=new WebSocket(`${l}/api/${a}`),o(),c.addEventListener("close",()=>{c=void 0,i(new Error("Socket closed unexpectedly"))}),c.addEventListener("error",e=>{var t;this.uppy.log(`Companion socket error ${JSON.stringify(e)}, closing socket`,"warning"),null==(t=c)||t.close()}),c.addEventListener("open",()=>{_()}),c.addEventListener("message",r=>{o();try{const{action:t,payload:o}=JSON.parse(r.data);switch(t){case"progress":is(this,o,this.uppy.getFile(n.id));break;case"success":{var i,s,a,l;const t=null==(i=o.response)?void 0:i.responseText;this.uppy.emit("upload-success",this.uppy.getFile(n.id),{uploadURL:o.url,status:null!=(s=null==(a=o.response)?void 0:a.status)?s:200,body:t?JSON.parse(t):void 0}),null==(l=u)||null==l.abort||l.abort(),e();break}case"error":{const{message:e}=o.error;throw Object.assign(new Error(e),{cause:o.error})}default:this.uppy.log(`Companion socket unknown action ${t}`,"warning")}}catch(e){t(e)}});const s=()=>{this.uppy.log(`Closing socket ${n.id}`,"info"),clearTimeout(d),c&&c.close(),c=void 0};u.signal.addEventListener("abort",()=>{s()})}),{retries:10,signal:u.signal,onFailedAttempt:()=>{u.signal.aborted||this.uppy.log(`Retrying websocket ${n.id}`,"info")}})})().abortOn(u.signal)}catch(e){if(u.signal.aborted)return;t(e)}},m=e=>{var t;i.resumableUploads&&(h=e,c&&_(),e?null==(t=u)||null==t.abort||t.abort():f())},g=t=>{var r;i.individualCancellation&&t.id===n.id&&(p("cancel"),null==(r=u)||null==r.abort||r.abort(),this.uppy.log(`upload ${n.id} was removed`,"info"),e())},y=t=>{var r;let{reason:o}=t;"user"===o&&p("cancel"),null==(r=u)||null==r.abort||r.abort(),this.uppy.log(`upload ${n.id} was canceled`,"info"),e()},v=(e,t)=>{e===n.id&&m(t)},w=()=>m(!0),b=()=>m(!1);this.uppy.on("file-removed",g),this.uppy.on("cancel-all",y),this.uppy.on("upload-pause",v),this.uppy.on("pause-all",w),this.uppy.on("resume-all",b),t=()=>{this.uppy.off("file-removed",g),this.uppy.off("cancel-all",y),this.uppy.off("upload-pause",v),this.uppy.off("pause-all",w),this.uppy.off("resume-all",b)},o.addEventListener("abort",()=>{var e;null==(e=u)||e.abort()}),f()})}finally{null==t||t()}}function vs(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}ms.VERSION="3.8.2";var ws=0;function bs(e){return"__private_"+ws+++"_"+e}var Ss=bs("uppy"),Es=bs("events");class Ps{constructor(e){Object.defineProperty(this,Ss,{writable:!0,value:void 0}),Object.defineProperty(this,Es,{writable:!0,value:[]}),vs(this,Ss)[Ss]=e}on(e,t){return vs(this,Es)[Es].push([e,t]),vs(this,Ss)[Ss].on(e,t)}remove(){for(const[e,t]of vs(this,Es)[Es].splice(0))vs(this,Ss)[Ss].off(e,t)}onFilePause(e,t){this.on("upload-pause",(n,r)=>{e===n&&t(r)})}onFileRemove(e,t){this.on("file-removed",n=>{e===n.id&&t(n.id)})}onPause(e,t){this.on("upload-pause",(n,r)=>{e===n&&t(r)})}onRetry(e,t){this.on("upload-retry",n=>{e===n&&t()})}onRetryAll(e,t){this.on("retry-all",()=>{vs(this,Ss)[Ss].getFile(e)&&t()})}onPauseAll(e,t){this.on("pause-all",()=>{vs(this,Ss)[Ss].getFile(e)&&t()})}onCancelAll(e,t){var n=this;this.on("cancel-all",function(){vs(n,Ss)[Ss].getFile(e)&&t(...arguments)})}onResumeAll(e,t){this.on("resume-all",()=>{vs(this,Ss)[Ss].getFile(e)&&t()})}}function Ts(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var ks=0;function xs(e){return"__private_"+ks+++"_"+e}function Cs(e){if(null!=e){var t;const n=()=>this.abort(e.reason);e.addEventListener("abort",n,{once:!0});const r=()=>{e.removeEventListener("abort",n)};null==(t=this.then)||t.call(this,r,r)}return this}var Os=xs("activeRequests"),js=xs("queuedHandlers"),Rs=xs("paused"),As=xs("pauseTimer"),Ns=xs("downLimit"),Fs=xs("upperLimit"),Is=xs("rateLimitingTimer"),Ms=xs("call"),Us=xs("queueNext"),Ls=xs("next"),zs=xs("queue"),Ds=xs("dequeue"),Bs=xs("resume"),$s=xs("increaseLimit");class qs{constructor(e){Object.defineProperty(this,Ds,{value:Ys}),Object.defineProperty(this,zs,{value:Ks}),Object.defineProperty(this,Ls,{value:Vs}),Object.defineProperty(this,Us,{value:Hs}),Object.defineProperty(this,Ms,{value:Ws}),Object.defineProperty(this,Os,{writable:!0,value:0}),Object.defineProperty(this,js,{writable:!0,value:[]}),Object.defineProperty(this,Rs,{writable:!0,value:!1}),Object.defineProperty(this,As,{writable:!0,value:void 0}),Object.defineProperty(this,Ns,{writable:!0,value:1}),Object.defineProperty(this,Fs,{writable:!0,value:void 0}),Object.defineProperty(this,Is,{writable:!0,value:void 0}),Object.defineProperty(this,Bs,{writable:!0,value:()=>this.resume()}),Object.defineProperty(this,$s,{writable:!0,value:()=>{if(Ts(this,Rs)[Rs])Ts(this,Is)[Is]=setTimeout(Ts(this,$s)[$s],0);else{Ts(this,Ns)[Ns]=this.limit,this.limit=Math.ceil((Ts(this,Fs)[Fs]+Ts(this,Ns)[Ns])/2);for(let e=Ts(this,Ns)[Ns];e<=this.limit;e++)Ts(this,Us)[Us]();Ts(this,Fs)[Fs]-Ts(this,Ns)[Ns]>3?Ts(this,Is)[Is]=setTimeout(Ts(this,$s)[$s],2e3):Ts(this,Ns)[Ns]=Math.floor(Ts(this,Ns)[Ns]/2)}}}),this.limit="number"!=typeof e||0===e?1/0:e}run(e,t){return!Ts(this,Rs)[Rs]&&Ts(this,Os)[Os]<this.limit?Ts(this,Ms)[Ms](e):Ts(this,zs)[zs](e,t)}wrapSyncFunction(e,t){var n=this;return function(){for(var r=arguments.length,o=new Array(r),i=0;i<r;i++)o[i]=arguments[i];const s=n.run(()=>(e(...o),queueMicrotask(()=>s.done()),()=>{}),t);return{abortOn:Cs,abort(){s.abort()}}}}wrapPromiseFunction(e,t){var n=this;return function(){for(var r=arguments.length,o=new Array(r),i=0;i<r;i++)o[i]=arguments[i];let s;const a=new Promise((r,i)=>{s=n.run(()=>{let t,n;try{n=Promise.resolve(e(...o))}catch(e){n=Promise.reject(e)}return n.then(e=>{t?i(t):(s.done(),r(e))},e=>{t?i(t):(s.done(),i(e))}),e=>{t=function(e){return new Error("Cancelled",{cause:e})}(e)}},t)});return a.abort=e=>{s.abort(e)},a.abortOn=Cs,a}}resume(){Ts(this,Rs)[Rs]=!1,clearTimeout(Ts(this,As)[As]);for(let e=0;e<this.limit;e++)Ts(this,Us)[Us]()}pause(e){void 0===e&&(e=null),Ts(this,Rs)[Rs]=!0,clearTimeout(Ts(this,As)[As]),null!=e&&(Ts(this,As)[As]=setTimeout(Ts(this,Bs)[Bs],e))}rateLimit(e){clearTimeout(Ts(this,Is)[Is]),this.pause(e),this.limit>1&&Number.isFinite(this.limit)&&(Ts(this,Fs)[Fs]=this.limit-1,this.limit=Ts(this,Ns)[Ns],Ts(this,Is)[Is]=setTimeout(Ts(this,$s)[$s],e))}get isPaused(){return Ts(this,Rs)[Rs]}}function Ws(e){Ts(this,Os)[Os]+=1;let t,n=!1;try{t=e()}catch(e){throw Ts(this,Os)[Os]-=1,e}return{abort:e=>{n||(n=!0,Ts(this,Os)[Os]-=1,null==t||t(e),Ts(this,Us)[Us]())},done:()=>{n||(n=!0,Ts(this,Os)[Os]-=1,Ts(this,Us)[Us]())}}}function Hs(){queueMicrotask(()=>Ts(this,Ls)[Ls]())}function Vs(){if(Ts(this,Rs)[Rs]||Ts(this,Os)[Os]>=this.limit)return;if(0===Ts(this,js)[js].length)return;const e=Ts(this,js)[js].shift();if(null==e)throw new Error("Invariant violation: next is null");const t=Ts(this,Ms)[Ms](e.fn);e.abort=t.abort,e.done=t.done}function Ks(e,t){const n={fn:e,priority:(null==t?void 0:t.priority)||0,abort:()=>{Ts(this,Ds)[Ds](n)},done:()=>{throw new Error("Cannot mark a queued request as done: this indicates a bug")}},r=Ts(this,js)[js].findIndex(e=>n.priority>e.priority);return-1===r?Ts(this,js)[js].push(n):Ts(this,js)[js].splice(r,0,n),n}function Ys(e){const t=Ts(this,js)[js].indexOf(e);-1!==t&&Ts(this,js)[js].splice(t,1)}const{AbortController:Gs}=globalThis,Js=function(e,t){void 0===e&&(e="Aborted");const n=new DOMException(e,"AbortError");return null!=t&&rs(t,"cause")&&Object.defineProperty(n,"cause",{__proto__:null,configurable:!0,writable:!0,value:t.cause}),n};function Xs(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var Qs=0;function Zs(e){return"__private_"+Qs+++"_"+e}const ea={getChunkSize:e=>Math.ceil(e.size/1e4),onProgress(){},onPartComplete(){},onSuccess(){},onError(e){throw e}};const ta=Symbol("pausing upload, not an actual error");var na=Zs("abortController"),ra=Zs("chunks"),oa=Zs("chunkState"),ia=Zs("data"),sa=Zs("file"),aa=Zs("uploadHasStarted"),la=Zs("onError"),ca=Zs("onSuccess"),ua=Zs("shouldUseMultipart"),da=Zs("isRestoring"),ha=Zs("onReject"),pa=Zs("maxMultipartParts"),_a=Zs("minPartSize"),fa=Zs("initChunks"),ma=Zs("createUpload"),ga=Zs("resumeUpload"),ya=Zs("onPartProgress"),va=Zs("onPartComplete"),wa=Zs("abortUpload");class ba{constructor(e,t){var n;Object.defineProperty(this,wa,{value:Ta}),Object.defineProperty(this,ga,{value:Pa}),Object.defineProperty(this,ma,{value:Ea}),Object.defineProperty(this,fa,{value:Sa}),Object.defineProperty(this,na,{writable:!0,value:new Gs}),Object.defineProperty(this,ra,{writable:!0,value:void 0}),Object.defineProperty(this,oa,{writable:!0,value:void 0}),Object.defineProperty(this,ia,{writable:!0,value:void 0}),Object.defineProperty(this,sa,{writable:!0,value:void 0}),Object.defineProperty(this,aa,{writable:!0,value:!1}),Object.defineProperty(this,la,{writable:!0,value:void 0}),Object.defineProperty(this,ca,{writable:!0,value:void 0}),Object.defineProperty(this,ua,{writable:!0,value:void 0}),Object.defineProperty(this,da,{writable:!0,value:void 0}),Object.defineProperty(this,ha,{writable:!0,value:e=>(null==e?void 0:e.cause)===ta?null:Xs(this,la)[la](e)}),Object.defineProperty(this,pa,{writable:!0,value:1e4}),Object.defineProperty(this,_a,{writable:!0,value:5242880}),Object.defineProperty(this,ya,{writable:!0,value:e=>t=>{if(!t.lengthComputable)return;Xs(this,oa)[oa][e].uploaded=function(e){if("string"==typeof e)return parseInt(e,10);if("number"==typeof e)return e;throw new TypeError("Expected a number")}(t.loaded);const n=Xs(this,oa)[oa].reduce((e,t)=>e+t.uploaded,0);this.options.onProgress(n,Xs(this,ia)[ia].size)}}),Object.defineProperty(this,va,{writable:!0,value:e=>t=>{Xs(this,ra)[ra][e]=null,Xs(this,oa)[oa][e].etag=t,Xs(this,oa)[oa][e].done=!0;const n={PartNumber:e+1,ETag:t};this.options.onPartComplete(n)}}),this.options={...ea,...t},null!=(n=this.options).getChunkSize||(n.getChunkSize=ea.getChunkSize),Xs(this,ia)[ia]=e,Xs(this,sa)[sa]=t.file,Xs(this,ca)[ca]=this.options.onSuccess,Xs(this,la)[la]=this.options.onError,Xs(this,ua)[ua]=this.options.shouldUseMultipart,Xs(this,da)[da]=t.uploadId&&t.key,Xs(this,fa)[fa]()}start(){Xs(this,aa)[aa]?(Xs(this,na)[na].signal.aborted||Xs(this,na)[na].abort(ta),Xs(this,na)[na]=new Gs,Xs(this,ga)[ga]()):Xs(this,da)[da]?(this.options.companionComm.restoreUploadFile(Xs(this,sa)[sa],{uploadId:this.options.uploadId,key:this.options.key}),Xs(this,ga)[ga]()):Xs(this,ma)[ma]()}pause(){Xs(this,na)[na].abort(ta),Xs(this,na)[na]=new Gs}abort(e){null!=e&&e.really?Xs(this,wa)[wa]():this.pause()}get chunkState(){return Xs(this,oa)[oa]}}function Sa(){const e=Xs(this,ia)[ia].size,t="function"==typeof Xs(this,ua)[ua]?Xs(this,ua)[ua](Xs(this,sa)[sa]):Boolean(Xs(this,ua)[ua]);if(t&&e>Xs(this,_a)[_a]){let n=Math.max(this.options.getChunkSize(Xs(this,ia)[ia]),Xs(this,_a)[_a]),r=Math.floor(e/n);r>Xs(this,pa)[pa]&&(r=Xs(this,pa)[pa],n=e/Xs(this,pa)[pa]),Xs(this,ra)[ra]=Array(r);for(let r=0,o=0;r<e;r+=n,o++){const i=Math.min(e,r+n),s=()=>{const e=r;return Xs(this,ia)[ia].slice(e,i)};if(Xs(this,ra)[ra][o]={getData:s,onProgress:Xs(this,ya)[ya](o),onComplete:Xs(this,va)[va](o),shouldUseMultipart:t},Xs(this,da)[da]){const t=r+n>e?e-r:n;Xs(this,ra)[ra][o].setAsUploaded=()=>{Xs(this,ra)[ra][o]=null,Xs(this,oa)[oa][o].uploaded=t}}}}else Xs(this,ra)[ra]=[{getData:()=>Xs(this,ia)[ia],onProgress:Xs(this,ya)[ya](0),onComplete:Xs(this,va)[va](0),shouldUseMultipart:t}];Xs(this,oa)[oa]=Xs(this,ra)[ra].map(()=>({uploaded:0}))}function Ea(){this.options.companionComm.uploadFile(Xs(this,sa)[sa],Xs(this,ra)[ra],Xs(this,na)[na].signal).then(Xs(this,ca)[ca],Xs(this,ha)[ha]),Xs(this,aa)[aa]=!0}function Pa(){this.options.companionComm.resumeUploadFile(Xs(this,sa)[sa],Xs(this,ra)[ra],Xs(this,na)[na].signal).then(Xs(this,ca)[ca],Xs(this,ha)[ha])}function Ta(){Xs(this,na)[na].abort(),this.options.companionComm.abortFileUpload(Xs(this,sa)[sa]).catch(e=>this.options.log(e))}function ka(e){if(null!=e&&e.aborted)throw Js("The operation was aborted",{cause:e.reason})}const xa=new TextEncoder,Ca={name:"HMAC",hash:"SHA-256"};function Oa(e){const t=new Uint8Array(e);let n="";for(let e=0;e<t.length;e++)n+=t[e].toString(16).padStart(2,"0");return n}async function ja(e,t){const{subtle:n}=globalThis.crypto;return n.sign(Ca,await async function(e){const{subtle:t}=globalThis.crypto;return t.importKey("raw","string"==typeof e?xa.encode(e):e,Ca,!1,["sign"])}(e),xa.encode(t))}async function Ra(e){let{accountKey:t,accountSecret:n,sessionToken:r,bucketName:o,Key:i,Region:s,expires:a,uploadId:l,partNumber:c}=e;const u="s3",d=`${o}.${u}.${s}.amazonaws.com`,h=`/${encodeURI(i).replace(/[;?:@&=+$,#!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}`,p="UNSIGNED-PAYLOAD",_=(new Date).toISOString().replace(/[-:]|\.\d+/g,""),f=_.slice(0,8),m=`${f}/${s}/${u}/aws4_request`,g=new URL(`https://${d}${h}`);g.searchParams.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),g.searchParams.set("X-Amz-Content-Sha256",p),g.searchParams.set("X-Amz-Credential",`${t}/${m}`),g.searchParams.set("X-Amz-Date",_),g.searchParams.set("X-Amz-Expires",a),g.searchParams.set("X-Amz-Security-Token",r),g.searchParams.set("X-Amz-SignedHeaders","host"),c&&g.searchParams.set("partNumber",c),l&&g.searchParams.set("uploadId",l),g.searchParams.set("x-id",c&&l?"UploadPart":"PutObject");const y=function(e){let{method:t="PUT",CanonicalUri:n="/",CanonicalQueryString:r="",SignedHeaders:o,HashedPayload:i}=e;const s=Object.keys(o).map(e=>e.toLowerCase()).sort();return[t,n,r,...s.map(e=>`${e}:${o[e]}`),"",s.join(";"),i].join("\n")}({CanonicalUri:h,CanonicalQueryString:g.search.slice(1),SignedHeaders:{host:d},HashedPayload:p}),v=["AWS4-HMAC-SHA256",_,m,Oa(await async function(e){const{subtle:t}=globalThis.crypto;return t.digest(Ca.hash,xa.encode(e))}(y))].join("\n"),w=await ja(`AWS4${n}`,f),b=await ja(w,s),S=await ja(b,u),E=await ja(S,"aws4_request"),P=Oa(await ja(E,v));return g.searchParams.set("X-Amz-Signature",P),g}function Aa(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var Na=0;function Fa(e){return"__private_"+Na+++"_"+e}function Ia(e){const t=new URL(e);return t.search="",t.hash="",t.href}var Ma=Fa("abortMultipartUpload"),Ua=Fa("cache"),La=Fa("createMultipartUpload"),za=Fa("fetchSignature"),Da=Fa("getUploadParameters"),Ba=Fa("listParts"),$a=Fa("previousRetryDelay"),qa=Fa("requests"),Wa=Fa("retryDelays"),Ha=Fa("sendCompletionRequest"),Va=Fa("setS3MultipartState"),Ka=Fa("uploadPartBytes"),Ya=Fa("getFile"),Ga=Fa("shouldRetry"),Ja=Fa("nonMultipartUpload");class Xa{constructor(e,t,n,r){Object.defineProperty(this,Ja,{value:Za}),Object.defineProperty(this,Ga,{value:Qa}),Object.defineProperty(this,Ma,{writable:!0,value:void 0}),Object.defineProperty(this,Ua,{writable:!0,value:new WeakMap}),Object.defineProperty(this,La,{writable:!0,value:void 0}),Object.defineProperty(this,za,{writable:!0,value:void 0}),Object.defineProperty(this,Da,{writable:!0,value:void 0}),Object.defineProperty(this,Ba,{writable:!0,value:void 0}),Object.defineProperty(this,$a,{writable:!0,value:void 0}),Object.defineProperty(this,qa,{writable:!0,value:void 0}),Object.defineProperty(this,Wa,{writable:!0,value:void 0}),Object.defineProperty(this,Ha,{writable:!0,value:void 0}),Object.defineProperty(this,Va,{writable:!0,value:void 0}),Object.defineProperty(this,Ka,{writable:!0,value:void 0}),Object.defineProperty(this,Ya,{writable:!0,value:void 0}),Aa(this,qa)[qa]=e,Aa(this,Va)[Va]=n,Aa(this,Ya)[Ya]=r,this.setOptions(t)}setOptions(e){const t=Aa(this,qa)[qa];var n;("abortMultipartUpload"in e&&(Aa(this,Ma)[Ma]=t.wrapPromiseFunction(e.abortMultipartUpload,{priority:1})),"createMultipartUpload"in e&&(Aa(this,La)[La]=t.wrapPromiseFunction(e.createMultipartUpload,{priority:-1})),"signPart"in e&&(Aa(this,za)[za]=t.wrapPromiseFunction(e.signPart)),"listParts"in e&&(Aa(this,Ba)[Ba]=t.wrapPromiseFunction(e.listParts)),"completeMultipartUpload"in e&&(Aa(this,Ha)[Ha]=t.wrapPromiseFunction(e.completeMultipartUpload,{priority:1})),"retryDelays"in e)&&(Aa(this,Wa)[Wa]=null!=(n=e.retryDelays)?n:[]);"uploadPartBytes"in e&&(Aa(this,Ka)[Ka]=t.wrapPromiseFunction(e.uploadPartBytes,{priority:1/0})),"getUploadParameters"in e&&(Aa(this,Da)[Da]=t.wrapPromiseFunction(e.getUploadParameters))}async getUploadId(e,t){let n;for(;null!=(n=Aa(this,Ua)[Ua].get(e.data));)try{return await n}catch{}const r=Aa(this,La)[La](Aa(this,Ya)[Ya](e),t),o=()=>{r.abort(t.reason),Aa(this,Ua)[Ua].delete(e.data)};return t.addEventListener("abort",o,{once:!0}),Aa(this,Ua)[Ua].set(e.data,r),r.then(async n=>{t.removeEventListener("abort",o),Aa(this,Va)[Va](e,n),Aa(this,Ua)[Ua].set(e.data,n)},()=>{t.removeEventListener("abort",o),Aa(this,Ua)[Ua].delete(e.data)}),r}async abortFileUpload(e){const t=Aa(this,Ua)[Ua].get(e.data);if(null==t)return;let n;Aa(this,Ua)[Ua].delete(e.data),Aa(this,Va)[Va](e,Object.create(null));try{n=await t}catch{return}await Aa(this,Ma)[Ma](Aa(this,Ya)[Ya](e),n)}async uploadFile(e,t,n){if(ka(n),1===t.length&&!t[0].shouldUseMultipart)return Aa(this,Ja)[Ja](e,t[0],n);const{uploadId:r,key:o}=await this.getUploadId(e,n);ka(n);try{const i=await Promise.all(t.map((t,r)=>this.uploadChunk(e,r+1,t,n)));return ka(n),await Aa(this,Ha)[Ha](Aa(this,Ya)[Ya](e),{key:o,uploadId:r,parts:i,signal:n},n).abortOn(n)}catch(t){throw(null==t?void 0:t.cause)!==ta&&"AbortError"!==(null==t?void 0:t.name)&&this.abortFileUpload(e),t}}restoreUploadFile(e,t){Aa(this,Ua)[Ua].set(e.data,t)}async resumeUploadFile(e,t,n){if(ka(n),1===t.length&&null!=t[0]&&!t[0].shouldUseMultipart)return Aa(this,Ja)[Ja](e,t[0],n);const{uploadId:r,key:o}=await this.getUploadId(e,n);ka(n);const i=await Aa(this,Ba)[Ba](Aa(this,Ya)[Ya](e),{uploadId:r,key:o,signal:n},n).abortOn(n);ka(n);const s=await Promise.all(t.map((t,r)=>{const o=r+1,s=i.find(e=>{let{PartNumber:t}=e;return t===o});return null==s?this.uploadChunk(e,o,t,n):(null==t||null==t.setAsUploaded||t.setAsUploaded(),{PartNumber:o,ETag:s.ETag})}));return ka(n),Aa(this,Ha)[Ha](Aa(this,Ya)[Ya](e),{key:o,uploadId:r,parts:s,signal:n},n).abortOn(n)}async uploadChunk(e,t,n,r){ka(r);const{uploadId:o,key:i}=await this.getUploadId(e,r),s=Aa(this,Wa)[Wa].values(),a=Aa(this,Wa)[Wa].values(),l=()=>{const e=s.next();return null==e||e.done?null:e.value};for(;;){ka(r);const s=n.getData(),{onProgress:c,onComplete:u}=n;let d;try{d=await Aa(this,za)[za](Aa(this,Ya)[Ya](e),{uploadId:o,key:i,partNumber:t,body:s,signal:r}).abortOn(r)}catch(e){const t=l();if(null==t||r.aborted)throw e;await new Promise(e=>setTimeout(e,t));continue}ka(r);try{return{PartNumber:t,...await Aa(this,Ka)[Ka]({signature:d,body:s,size:s.size,onProgress:c,onComplete:u,signal:r}).abortOn(r)}}catch(e){if(!await Aa(this,Ga)[Ga](e,a))throw e}}}}async function Qa(e,t){var n;const r=Aa(this,qa)[qa],o=null==e||null==(n=e.source)?void 0:n.status;if(null==o)return!1;if(403===o&&"Request has expired"===e.message){if(!r.isPaused){if(1===r.limit||null==Aa(this,$a)[$a]){const e=t.next();if(null==e||e.done)return!1;Aa(this,$a)[$a]=e.value}r.rateLimit(0),await new Promise(e=>setTimeout(e,Aa(this,$a)[$a]))}}else if(429===o){if(!r.isPaused){const e=t.next();if(null==e||e.done)return!1;r.rateLimit(e.value)}}else{if(o>400&&o<500&&409!==o)return!1;if("undefined"!=typeof navigator&&!1===navigator.onLine)r.isPaused||(r.pause(),window.addEventListener("online",()=>{r.resume()},{once:!0}));else{const e=t.next();if(null==e||e.done)return!1;await new Promise(t=>setTimeout(t,e.value))}}return!0}async function Za(e,t,n){const{method:r="POST",url:o,fields:i,headers:s}=await Aa(this,Da)[Da](Aa(this,Ya)[Ya](e),{signal:n}).abortOn(n);let a;const l=t.getData();if("POST"===r.toUpperCase()){const e=new FormData;Object.entries(i).forEach(t=>{let[n,r]=t;return e.set(n,r)}),e.set("file",l),a=e}else a=l;const{onProgress:c,onComplete:u}=t,d=await Aa(this,Ka)[Ka]({signature:{url:o,headers:s,method:r},body:a,size:l.size,onProgress:c,onComplete:u,signal:n}).abortOn(n);return"location"in d?d:{location:Ia(o),...d}}let el;function tl(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var nl=0;function rl(e){return"__private_"+nl+++"_"+e}function ol(e){if(null!=e&&e.error){const t=new Error(e.message);throw Object.assign(t,e.error),t}return e}function il(e){const t=e.Expiration;if(t){const e=Math.floor((new Date(t)-Date.now())/1e3);if(e>9)return e}}function sl(e){let{meta:t,allowedMetaFields:n,querify:r=!1}=e;const o=null!=n?n:Object.keys(t);return t?Object.fromEntries(o.filter(e=>null!=t[e]).map(e=>[r?`metadata[${e}]`:e,String(t[e])])):{}}const al={allowedMetaFields:null,limit:6,getTemporarySecurityCredentials:!1,shouldUseMultipart:e=>0!==e.size,retryDelays:[0,1e3,3e3,5e3],companionHeaders:{}};var ll=rl("companionCommunicationQueue"),cl=rl("client"),ul=rl("cachedTemporaryCredentials"),dl=rl("getTemporarySecurityCredentials"),hl=rl("setS3MultipartState"),pl=rl("getFile"),_l=rl("uploadLocalFile"),fl=rl("getCompanionClientArgs"),ml=rl("upload"),gl=rl("setCompanionHeaders"),yl=rl("setResumableUploadsCapability"),vl=rl("resetResumableCapability");el=Symbol.for("uppy test: getClient");class wl extends zi{constructor(e,t){var n;super(e,{...al,uploadPartBytes:wl.uploadPartBytes,createMultipartUpload:null,listParts:null,abortMultipartUpload:null,completeMultipartUpload:null,signPart:null,getUploadParameters:null,...t}),Object.defineProperty(this,fl,{value:El}),Object.defineProperty(this,_l,{value:Sl}),Object.defineProperty(this,dl,{value:bl}),Object.defineProperty(this,ll,{writable:!0,value:void 0}),Object.defineProperty(this,cl,{writable:!0,value:void 0}),Object.defineProperty(this,ul,{writable:!0,value:void 0}),Object.defineProperty(this,hl,{writable:!0,value:(e,t)=>{let{key:n,uploadId:r}=t;const o=this.uppy.getFile(e.id);null!=o&&this.uppy.setFileState(e.id,{s3Multipart:{...o.s3Multipart,key:n,uploadId:r}})}}),Object.defineProperty(this,pl,{writable:!0,value:e=>this.uppy.getFile(e.id)||e}),Object.defineProperty(this,ml,{writable:!0,value:async e=>{if(0===e.length)return;const t=function(e){return e.filter(e=>!(e=>"error"in e&&!!e.error)(e))}(this.uppy.getFilesByIds(e)),n=function(e){return e.filter(e=>{var t;return!(null!=(t=e.progress)&&t.uploadStarted&&e.isRestored)})}(t);this.uppy.emit("upload-start",n);const r=t.map(e=>{if(e.isRemote){const t=()=>this.requests;tl(this,yl)[yl](!1);const n=new AbortController,r=t=>{t.id===e.id&&n.abort()};this.uppy.on("file-removed",r);const o=this.uppy.getRequestClientForFile(e).uploadRemoteFile(e,tl(this,fl)[fl](e),{signal:n.signal,getQueue:t});return this.requests.wrapSyncFunction(()=>{this.uppy.off("file-removed",r)},{priority:-1})(),o}return tl(this,_l)[_l](e)}),o=await Promise.all(r);return tl(this,yl)[yl](!0),o}}),Object.defineProperty(this,gl,{writable:!0,value:()=>{tl(this,cl)[cl].setCompanionHeaders(this.opts.companionHeaders)}}),Object.defineProperty(this,yl,{writable:!0,value:e=>{const{capabilities:t}=this.uppy.getState();this.uppy.setState({capabilities:{...t,resumableUploads:e}})}}),Object.defineProperty(this,vl,{writable:!0,value:()=>{tl(this,yl)[yl](!0)}}),this.type="uploader",this.id=this.opts.id||"AwsS3Multipart",this.title="AWS S3 Multipart",tl(this,cl)[cl]=new ms(e,t);const r={createMultipartUpload:this.createMultipartUpload,listParts:this.listParts,abortMultipartUpload:this.abortMultipartUpload,completeMultipartUpload:this.completeMultipartUpload,signPart:null!=t&&t.getTemporarySecurityCredentials?this.createSignedURL:this.signPart,getUploadParameters:null!=t&&t.getTemporarySecurityCredentials?this.createSignedURL:this.getUploadParameters};for(const e of Object.keys(r))null==this.opts[e]&&(this.opts[e]=r[e].bind(this));null!=(null==t?void 0:t.prepareUploadParts)&&null==t.signPart&&(this.opts.signPart=async(e,n)=>{let{uploadId:r,key:o,partNumber:i,body:s,signal:a}=n;const{presignedUrls:l,headers:c}=await t.prepareUploadParts(e,{uploadId:r,key:o,parts:[{number:i,chunk:s}],signal:a});return{url:null==l?void 0:l[i],headers:null==c?void 0:c[i]}}),this.requests=null!=(n=this.opts.rateLimitedQueue)?n:new qs(this.opts.limit),tl(this,ll)[ll]=new Xa(this.requests,this.opts,tl(this,hl)[hl],tl(this,pl)[pl]),this.uploaders=Object.create(null),this.uploaderEvents=Object.create(null),this.uploaderSockets=Object.create(null)}[el](){return tl(this,cl)[cl]}setOptions(e){tl(this,ll)[ll].setOptions(e),super.setOptions(e),tl(this,gl)[gl]()}resetUploaderReferences(e,t){this.uploaders[e]&&(this.uploaders[e].abort({really:(null==t?void 0:t.abort)||!1}),this.uploaders[e]=null),this.uploaderEvents[e]&&(this.uploaderEvents[e].remove(),this.uploaderEvents[e]=null),this.uploaderSockets[e]&&(this.uploaderSockets[e].close(),this.uploaderSockets[e]=null)}assertHost(e){if(!this.opts.companionUrl)throw new Error(`Expected a \`companionUrl\` option containing a Companion address, or if you are not using Companion, a custom \`${e}\` implementation.`)}createMultipartUpload(e,t){this.assertHost("createMultipartUpload"),ka(t);const n=sl({meta:e.meta,allowedMetaFields:this.opts.allowedMetaFields});return tl(this,cl)[cl].post("s3/multipart",{filename:e.name,type:e.type,metadata:n},{signal:t}).then(ol)}listParts(e,t,n){let{key:r,uploadId:o,signal:i}=t;null!=i||(i=n),this.assertHost("listParts"),ka(i);const s=encodeURIComponent(r);return tl(this,cl)[cl].get(`s3/multipart/${o}?key=${s}`,{signal:i}).then(ol)}completeMultipartUpload(e,t,n){let{key:r,uploadId:o,parts:i,signal:s}=t;null!=s||(s=n),this.assertHost("completeMultipartUpload"),ka(s);const a=encodeURIComponent(r),l=encodeURIComponent(o);return tl(this,cl)[cl].post(`s3/multipart/${l}/complete?key=${a}`,{parts:i},{signal:s}).then(ol)}async createSignedURL(e,t){const n=await tl(this,dl)[dl](t),r=il(n.credentials)||604800,{uploadId:o,key:i,partNumber:s}=t;return{method:"PUT",expires:r,fields:{},url:`${await Ra({accountKey:n.credentials.AccessKeyId,accountSecret:n.credentials.SecretAccessKey,sessionToken:n.credentials.SessionToken,expires:r,bucketName:n.bucket,Region:n.region,Key:null!=i?i:`${crypto.randomUUID()}-${e.name}`,uploadId:o,partNumber:s})}`,headers:{"Content-Type":e.type}}}signPart(e,t){let{uploadId:n,key:r,partNumber:o,signal:i}=t;if(this.assertHost("signPart"),ka(i),null==n||null==r||null==o)throw new Error("Cannot sign without a key, an uploadId, and a partNumber");const s=encodeURIComponent(r);return tl(this,cl)[cl].get(`s3/multipart/${n}/${o}?key=${s}`,{signal:i}).then(ol)}abortMultipartUpload(e,t,n){let{key:r,uploadId:o,signal:i}=t;null!=i||(i=n),this.assertHost("abortMultipartUpload");const s=encodeURIComponent(r),a=encodeURIComponent(o);return tl(this,cl)[cl].delete(`s3/multipart/${a}?key=${s}`,void 0,{signal:i}).then(ol)}getUploadParameters(e,t){const{meta:n}=e,{type:r,name:o}=n,i=sl({meta:n,allowedMetaFields:this.opts.allowedMetaFields,querify:!0}),s=new URLSearchParams({filename:o,type:r,...i});return tl(this,cl)[cl].get(`s3/params?${s}`,t)}static async uploadPartBytes(e){let{signature:{url:t,expires:n,headers:r,method:o="PUT"},body:i,size:s=i.size,onProgress:a,onComplete:l,signal:c}=e;if(ka(c),null==t)throw new Error("Cannot upload to an undefined URL");return new Promise((e,u)=>{const d=new XMLHttpRequest;function h(){d.abort()}function p(){null==c||c.removeEventListener("abort",h)}d.open(o,t,!0),r&&Object.keys(r).forEach(e=>{d.setRequestHeader(e,r[e])}),d.responseType="text","number"==typeof n&&(d.timeout=1e3*n),null==c||c.addEventListener("abort",h),d.upload.addEventListener("progress",e=>{a(e)}),d.addEventListener("abort",()=>{p(),u(Js())}),d.addEventListener("timeout",()=>{p();const e=new Error("Request has expired");e.source={status:403},u(e)}),d.addEventListener("load",()=>{if(p(),403===d.status&&d.responseText.includes("<Message>Request has expired</Message>")){const e=new Error("Request has expired");return e.source=d,void u(e)}if(d.status<200||d.status>=300){const e=new Error("Non 2xx");return e.source=d,void u(e)}null==a||a({loaded:s,lengthComputable:!0});const t=d.getAllResponseHeaders().trim().split(/[\r\n]+/),n={__proto__:null};for(const e of t){const t=e.split(": "),r=t.shift(),o=t.join(": ");n[r]=o}const{etag:r,location:i}=n;"POST"===o.toUpperCase()&&null===i&&console.warn("AwsS3/Multipart: Could not read the Location header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3-multipart#S3-Bucket-Configuration for instructions."),null!==r?(null==l||l(r),e({...n,ETag:r})):u(new Error("AwsS3/Multipart: Could not read the ETag header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3-multipart#S3-Bucket-Configuration for instructions."))}),d.addEventListener("error",e=>{p();const t=new Error("Unknown error");t.source=e.target,u(t)}),d.send(i)})}install(){tl(this,yl)[yl](!0),this.uppy.addPreProcessor(tl(this,gl)[gl]),this.uppy.addUploader(tl(this,ml)[ml]),this.uppy.on("cancel-all",tl(this,vl)[vl])}uninstall(){this.uppy.removePreProcessor(tl(this,gl)[gl]),this.uppy.removeUploader(tl(this,ml)[ml]),this.uppy.off("cancel-all",tl(this,vl)[vl])}}async function bl(e){return ka(null==e?void 0:e.signal),null==tl(this,ul)[ul]&&(!0===this.opts.getTemporarySecurityCredentials?(this.assertHost("getTemporarySecurityCredentials"),tl(this,ul)[ul]=tl(this,cl)[cl].get("s3/sts",e).then(ol)):tl(this,ul)[ul]=this.opts.getTemporarySecurityCredentials(e),tl(this,ul)[ul]=await tl(this,ul)[ul],setTimeout(()=>{tl(this,ul)[ul]=null},500*(il(tl(this,ul)[ul].credentials)||0))),tl(this,ul)[ul]}function Sl(e){var t=this;return new Promise((n,r)=>{const o=new ba(e.data,{companionComm:tl(this,ll)[ll],log:function(){return t.uppy.log(...arguments)},getChunkSize:this.opts.getChunkSize?this.opts.getChunkSize.bind(this):null,onProgress:(t,n)=>{this.uppy.emit("upload-progress",this.uppy.getFile(e.id),{uploader:this,bytesUploaded:t,bytesTotal:n})},onError:t=>{this.uppy.log(t),this.uppy.emit("upload-error",e,t),this.resetUploaderReferences(e.id),r(t)},onSuccess:t=>{const r={body:{...t},status:200,uploadURL:t.location};this.resetUploaderReferences(e.id),this.uppy.emit("upload-success",tl(this,pl)[pl](e),r),t.location&&this.uppy.log(`Download ${e.name} from ${t.location}`),n()},onPartComplete:t=>{this.uppy.emit("s3-multipart:part-uploaded",tl(this,pl)[pl](e),t)},file:e,shouldUseMultipart:this.opts.shouldUseMultipart,...e.s3Multipart});this.uploaders[e.id]=o;const i=new Ps(this.uppy);this.uploaderEvents[e.id]=i,i.onFileRemove(e.id,t=>{o.abort(),this.resetUploaderReferences(e.id,{abort:!0}),n(`upload ${t} was removed`)}),i.onCancelAll(e.id,t=>{"user"===(null==t?void 0:t.reason)&&(o.abort(),this.resetUploaderReferences(e.id,{abort:!0})),n(`upload ${e.id} was canceled`)}),i.onFilePause(e.id,e=>{e?o.pause():o.start()}),i.onPauseAll(e.id,()=>{o.pause()}),i.onResumeAll(e.id,()=>{o.start()}),o.start()})}function El(e){var t;return{...null==(t=e.remote)?void 0:t.body,protocol:"s3-multipart",size:e.data.size,metadata:e.meta}}wl.VERSION="3.12.0";var Pl,Tl,kl,xl,Cl,Ol=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function s(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){e.done?o(e.value):function(e){return e instanceof n?e:new n(function(t){t(e)})}(e.value).then(s,a)}l((r=r.apply(e,t||[])).next())})},jl=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},Rl=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)},Al=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n};class Nl{constructor(e,t=tr.PROD){Pl.add(this),Tl.set(this,void 0),kl.set(this,void 0),xl.set(this,void 0),jl(this,kl,e,"f"),jl(this,xl,t,"f")}uploadFileFrontend(e){return Ol(this,arguments,void 0,function*({file:e,arrayMetaData:t,scanId:n,email:r,callBack:o}){if(!or(e,t,n,r))throw new Error(Xn);if(!cr(r.trim()))throw new Error(Zn);if(!ir(t))throw new Error(Qn);return t=ar(t,n,r),Rl(this,Pl,"m",Cl).call(this,{callBack:o,arrayMetaData:t,scanId:n,email:r,file:e})})}faceScanFileUploader(e){return Ol(this,arguments,void 0,function*({file:e,arrayMetaData:t,objectKey:n,email:r,callBack:o}){if(!or(e,t,n,r))throw new Error(Xn);if(!cr(r.trim()))throw new Error(Zn);if(!sr(t,Jn))throw new Error(Qn);return t.push({email:r}),Rl(this,Pl,"m",Cl).call(this,{callBack:o,arrayMetaData:t,objectKey:n,email:r,file:e})})}uploadFile(e){return Ol(this,arguments,void 0,function*({file:e,arrayMetaData:t,scanId:n,email:r}){if(!or(e,t,n,r))throw new Error(Xn);if(!cr(r.trim()))throw new Error(Zn);if(!ir(t))throw new Error(Qn);return t=ar(t,n,r),new Promise((n,r)=>Ol(this,void 0,void 0,function*(){var o;try{const r=yield rr({path:kn,apiKey:Rl(this,kl,"f"),urlType:Rl(this,xl,"f"),body:{objectKey:e.name,contentType:e.type,objectMetadata:t},throwError:!0}),i=function(e,t=5242880){const n=e.size,r=[];let o=0;for(;o<n;)r.push(e.slice(o,o+t)),o+=t;return r}(e),s=[];for(let t=0;t<i.length;t++){const n=yield rr({path:Cn,apiKey:Rl(this,kl,"f"),urlType:Rl(this,xl,"f"),body:{objectKey:null==r?void 0:r.key,uploadId:null==r?void 0:r.uploadId,partNumber:t+1},throwError:!0}),a=yield ln.put(null==n?void 0:n.url,i[t],{headers:{"Content-Type":e.type,"X-Api-Key":Rl(this,kl,"f")}});s.push({PartNumber:t+1,ETag:null===(o=null==a?void 0:a.headers)||void 0===o?void 0:o.etag})}const a=yield rr({path:xn,apiKey:Rl(this,kl,"f"),urlType:Rl(this,xl,"f"),body:{uploadId:null==r?void 0:r.uploadId,objectKey:null==r?void 0:r.key,parts:s,originalFileName:e.name},throwError:!0});n({message:"successfully uploaded",data:a})}catch(e){r(e)}}))})}setDeviceInfo(e){return Ol(this,void 0,void 0,function*(){const{scanId:t}=e,n=Al(e,["scanId"]);if(!1===or(t))throw new Error(Xn);return ln.post(`${lr({urlName:On,urlType:Rl(this,xl,"f")})}${Kn}/${t}`,{device_info:Object.assign({},n)},{headers:{"X-Api-Key":Rl(this,kl,"f")}})})}}Tl=new WeakMap,kl=new WeakMap,xl=new WeakMap,Pl=new WeakSet,Cl=function({callBack:e,arrayMetaData:t,scanId:n,email:r,file:o,objectKey:i}){return new Promise((s,a)=>{Rl(this,Tl,"f")&&Rl(this,Tl,"f").close(),jl(this,Tl,new ki({autoProceed:!0}),"f"),Rl(this,Tl,"f").use(wl,{limit:10,retryDelays:[0,1e3,3e3,5e3],companionUrl:lr({urlName:On,urlType:Rl(this,xl,"f")}),getChunkSize:()=>er,createMultipartUpload:o=>{const s=Math.ceil(o.size/er);null==e||e({eventName:"uploading_start",message:`File ${o.name} will be divided into ${s} chunks`,scanId:n,email:r,objectKey:i});const a=`${n||i}.${o.extension}`;return rr({path:kn,apiKey:Rl(this,kl,"f"),urlType:Rl(this,xl,"f"),body:{objectKey:a,contentType:o.type,objectMetadata:t}})},completeMultipartUpload:(t,{uploadId:o,key:s,parts:a})=>(null==e||e({eventName:"uploading_complete_start",message:`${a.length} chunks of file, uploaded`,scanId:n,email:r,objectKey:i}),rr({path:xn,apiKey:Rl(this,kl,"f"),urlType:Rl(this,xl,"f"),body:{uploadId:o,objectKey:s,parts:a,originalFileName:t.name}}).then(t=>(null==e||e({eventName:"uploading_complete_end",message:"Multipart upload completed successfully",scanId:n,email:r,objectKey:i}),t))),signPart:(e,t)=>rr({path:Cn,urlType:Rl(this,xl,"f"),apiKey:Rl(this,kl,"f"),body:{objectKey:t.key,uploadId:t.uploadId,partNumber:t.partNumber}})}),Rl(this,Tl,"f").addFile({source:"manual",name:o.name,type:o.type,data:o}),Rl(this,Tl,"f").on("upload-error",(e,t,n)=>{t.isNetworkError?Rl(this,Tl,"f").retryUpload(e.id):a(t)}),Rl(this,Tl,"f").on("upload-success",()=>{s({message:"file uploaded successfully"})}),Rl(this,Tl,"f").on("complete",e=>{Rl(this,Tl,"f")&&Rl(this,Tl,"f").close()})})};var Fl,Il,Ml,Ul,Ll,zl,Dl,Bl,$l,ql,Wl,Hl,Vl=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function s(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){e.done?o(e.value):function(e){return e instanceof n?e:new n(function(t){t(e)})}(e.value).then(s,a)}l((r=r.apply(e,t||[])).next())})},Kl=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},Yl=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class Gl{constructor(e,t=tr.PROD){Fl.add(this),Il.set(this,{}),Ml.set(this,{}),Ul.set(this,{}),Ll.set(this,{}),zl.set(this,void 0),Dl.set(this,void 0),Kl(this,zl,e,"f"),Kl(this,Dl,t,"f")}getMeasurementResult(e){if(!or(e))throw new Error(Xn);const t=`${lr({urlName:On,urlType:Yl(this,Dl,"f")})}/measurements?scanId=${e}`;return ln.get(t,{headers:{"X-Api-Key":Yl(this,zl,"f")}})}getMeasurementRecommendation({scanId:e,shopDomain:t,productName:n}){if(!or(e,t,n))throw new Error(Xn);return ln.get(`${lr({urlName:On,urlType:Yl(this,Dl,"f")})}${Hn}/scan/${e}/shop/${t}/product/${n}`,{headers:{"X-Api-Key":Yl(this,zl,"f")}})}handleMeasurementSocket(e){const{scanId:t,onError:n,onSuccess:r,onClose:o,onOpen:i}=e;if(!or(t))throw new Error(Xn);Yl(this,Fl,"m",Hl).call(this,{onOpen:i,scanId:t,onSuccess:r,onError:n,onClose:o,paramsKey:"scanId",isFallback:!0,delay:5e3})}handlFaceScaneSocket(e){const{faceScanId:t,onError:n,onSuccess:r,onClose:o,onOpen:i}=e;if(!or(t))throw new Error(Xn);Yl(this,Fl,"m",Hl).call(this,{onOpen:i,faceScanId:t,onSuccess:r,onError:n,onClose:o,paramsKey:"faceScanId",isFallback:!1,delay:1e3})}}Il=new WeakMap,Ml=new WeakMap,Ul=new WeakMap,Ll=new WeakMap,zl=new WeakMap,Dl=new WeakMap,Fl=new WeakSet,Bl=function(e){var t;null===(t=Yl(this,Il,"f")[e])||void 0===t||t.close(),Yl(this,Il,"f")[e]=null,Yl(this,Ml,"f")[e]&&(clearTimeout(Yl(this,Ml,"f")[e]),Yl(this,Ml,"f")[e]=null)},$l=function(e,t){const{scanId:n,onSuccess:r,onError:o}=e;Yl(this,Ll,"f")[t]=1,Yl(this,Ml,"f")[t]=setTimeout(()=>{Yl(this,Fl,"m",ql).call(this,{scanId:n,onSuccess:r,onError:o},t),Yl(this,Fl,"m",Bl).call(this,t)},9e4)},ql=function(e,t){const{scanId:n,onSuccess:r,onError:o}=e;Yl(this,Ul,"f")[t]&&clearTimeout(Yl(this,Ul,"f")[t]),Yl(this,Ul,"f")[t]=setTimeout(()=>{Yl(this,Fl,"m",Wl).call(this,{scanId:n,onSuccess:r,onError:o},t)},5e3*(Yl(this,Ll,"f")[t]||1))},Wl=function(e,t){return Vl(this,void 0,void 0,function*(){var n;const{scanId:r,onSuccess:o,onError:i}=e;try{const e=yield this.getMeasurementResult(r);(null==e?void 0:e.data)&&!0===(null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.isMeasured)?(null==o||o(e.data),clearInterval(Yl(this,Ul,"f")[t])):(Yl(this,Ll,"f")[t]||1)<8?(Yl(this,Ll,"f")[t]=(Yl(this,Ll,"f")[t]||1)+1,Yl(this,Fl,"m",ql).call(this,{scanId:r,onSuccess:o,onError:i},t)):(Yl(this,Ll,"f")[t]=1,clearInterval(Yl(this,Ul,"f")[t]),null==i||i({scanStatus:"failed",message:"Scan not found",isMeasured:!1}))}catch(e){clearInterval(Yl(this,Ul,"f")[t]),null==i||i(e)}})},Hl=function({onOpen:e,isFallback:t,scanId:n,onSuccess:r,onError:o,onClose:i,paramsKey:s,faceScanId:a,delay:l}){const c=t?`measurement-${n}`:`faceScan-${a}`;setTimeout(()=>{Yl(this,Fl,"m",Bl).call(this,c);const l=`${lr({urlName:jn,urlType:Yl(this,Dl,"f")})}${Wn}?${s}=${n||a}`,u=new WebSocket(l);Yl(this,Il,"f")[c]=u,u.onopen=()=>{null==e||e(),t&&n&&Yl(this,Fl,"m",$l).call(this,{scanId:n,onSuccess:r,onError:o},c)},u.onmessage=e=>{const t=JSON.parse(e.data);200===(null==t?void 0:t.code)&&"success"===(null==t?void 0:t.scanStatus)?null==r||r(t):(clearTimeout(Yl(this,Ml,"f")[c]),null==o||o(t)),200===(null==t?void 0:t.code)&&"success"===(null==t?void 0:t.scanStatus)&&"final"===(null==t?void 0:t.resultType)&&clearTimeout(Yl(this,Ml,"f")[c])},u.onclose=()=>null==i?void 0:i(),u.onerror=()=>{t||null==o||o(new Error("An error occurred in the WebSocket connection."))}},l)};const Jl=Object.create(null);Jl.open="0",Jl.close="1",Jl.ping="2",Jl.pong="3",Jl.message="4",Jl.upgrade="5",Jl.noop="6";const Xl=Object.create(null);Object.keys(Jl).forEach(e=>{Xl[Jl[e]]=e});const Ql={type:"error",data:"parser error"},Zl="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),ec="function"==typeof ArrayBuffer,tc=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,nc=({type:e,data:t},n,r)=>Zl&&t instanceof Blob?n?r(t):rc(t,r):ec&&(t instanceof ArrayBuffer||tc(t))?n?r(t):rc(new Blob([t]),r):r(Jl[e]+(t||"")),rc=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function oc(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ic;const sc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ac="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)ac[sc.charCodeAt(e)]=e;const lc="function"==typeof ArrayBuffer,cc=(e,t)=>{if("string"!=typeof e)return{type:"message",data:dc(e,t)};const n=e.charAt(0);if("b"===n)return{type:"message",data:uc(e.substring(1),t)};return Xl[n]?e.length>1?{type:Xl[n],data:e.substring(1)}:{type:Xl[n]}:Ql},uc=(e,t)=>{if(lc){const n=(e=>{let t,n,r,o,i,s=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);const c=new ArrayBuffer(s),u=new Uint8Array(c);for(t=0;t<a;t+=4)n=ac[e.charCodeAt(t)],r=ac[e.charCodeAt(t+1)],o=ac[e.charCodeAt(t+2)],i=ac[e.charCodeAt(t+3)],u[l++]=n<<2|r>>4,u[l++]=(15&r)<<4|o>>2,u[l++]=(3&o)<<6|63&i;return c})(e);return dc(n,t)}return{base64:!0,data:e}},dc=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,hc=String.fromCharCode(30);function pc(){return new TransformStream({transform(e,t){!function(e,t){Zl&&e.data instanceof Blob?e.data.arrayBuffer().then(oc).then(t):ec&&(e.data instanceof ArrayBuffer||tc(e.data))?t(oc(e.data)):nc(e,!1,e=>{ic||(ic=new TextEncoder),t(ic.encode(e))})}(e,n=>{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const e=new DataView(o.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{o=new Uint8Array(9);const e=new DataView(o.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let _c;function fc(e){return e.reduce((e,t)=>e+t.length,0)}function mc(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;o<t;o++)n[o]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function gc(e){if(e)return function(e){for(var t in gc.prototype)e[t]=gc.prototype[t];return e}(e)}gc.prototype.on=gc.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},gc.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},gc.prototype.off=gc.prototype.removeListener=gc.prototype.removeAllListeners=gc.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;o<r.length;o++)if((n=r[o])===t||n.fn===t){r.splice(o,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},gc.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var o=(n=n.slice(0)).length;r<o;++r)n[r].apply(this,t)}return this},gc.prototype.emitReserved=gc.prototype.emit,gc.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},gc.prototype.hasListeners=function(e){return!!this.listeners(e).length};const yc="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),vc="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function wc(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const bc=vc.setTimeout,Sc=vc.clearTimeout;function Ec(e,t){t.useNativeTimers?(e.setTimeoutFn=bc.bind(vc),e.clearTimeoutFn=Sc.bind(vc)):(e.setTimeoutFn=vc.setTimeout.bind(vc),e.clearTimeoutFn=vc.clearTimeout.bind(vc))}function Pc(e){return"string"==typeof e?function(e){let t=0,n=0;for(let r=0,o=e.length;r<o;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}function Tc(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class kc extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class xc extends gc{constructor(e){super(),this.writable=!1,Ec(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new kc(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=cc(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class Cc extends xc{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(hc),r=[];for(let e=0;e<n.length;e++){const o=cc(n[e],t);if(r.push(o),"error"===o.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((e,i)=>{nc(e,!1,e=>{r[i]=e,++o===n&&t(r.join(hc))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Tc()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let Oc=!1;try{Oc="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}const jc=Oc;function Rc(){}class Ac extends Cc{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class Nc extends gc{constructor(e,t,n){super(),this.createRequest=e,Ec(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;const t=wc(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(e){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(e){return void this.setTimeoutFn(()=>{this._onError(e)},0)}"undefined"!=typeof document&&(this._index=Nc.requestsCount++,Nc.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Rc,e)try{this._xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Nc.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(Nc.requestsCount=0,Nc.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Fc);else if("function"==typeof addEventListener){addEventListener("onpagehide"in vc?"pagehide":"unload",Fc,!1)}function Fc(){for(let e in Nc.requests)Nc.requests.hasOwnProperty(e)&&Nc.requests[e].abort()}const Ic=function(){const e=Mc({xdomain:!1});return e&&null!==e.responseType}();function Mc(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||jc))return new XMLHttpRequest}catch(e){}if(!t)try{return new(vc[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}const Uc="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Lc extends xc{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Uc?{}:wc(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;nc(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(e){}r&&yc(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Tc()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const zc=vc.WebSocket||vc.MozWebSocket;const Dc={websocket:class extends Lc{createSocket(e,t,n){return Uc?new zc(e,t,n):t?new zc(e,t):new zc(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends xc{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){_c||(_c=new TextDecoder);const n=[];let r=0,o=-1,i=!1;return new TransformStream({transform(s,a){for(n.push(s);;){if(0===r){if(fc(n)<1)break;const e=mc(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(fc(n)<2)break;const e=mc(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(fc(n)<8)break;const e=mc(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){a.enqueue(Ql);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(fc(n)<o)break;const e=mc(n,o);a.enqueue(cc(i?e:_c.decode(e),t)),r=0}if(0===o||o>e){a.enqueue(Ql);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=pc();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const o=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),o())}).catch(e=>{})};o();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this._writer.write(i).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&yc(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Ac{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Ic&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Nc(Mc,this.uri(),e)}}},Bc=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,$c=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function qc(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");-1!=n&&-1!=r&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=Bc.exec(e||""),i={},s=14;for(;s--;)i[$c[s]]=o[s]||"";return-1!=n&&-1!=r&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||r.splice(0,1);"/"==t.slice(-1)&&r.splice(r.length-1,1);return r}(0,i.path),i.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}(0,i.query),i}const Wc="function"==typeof addEventListener&&"function"==typeof removeEventListener,Hc=[];Wc&&addEventListener("offline",()=>{Hc.forEach(e=>e())},!1);class Vc extends gc{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=qc(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=qc(t.host).host);Ec(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,r=n.length;e<r;e++){let r=n[e].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}(this.opts.query)),Wc&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Hc.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Vc.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Vc.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=Pc(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,yc(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const o={type:e,data:t,options:n};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Vc.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Wc&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Hc.indexOf(this._offlineEventListener);-1!==e&&Hc.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Vc.protocol=4;class Kc extends Vc{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Vc.priorWebsocketSuccess=!1;const r=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Vc.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function o(){n||(n=!0,c(),t.close(),t=null)}const i=e=>{const n=new Error("probe error: "+e);n.transport=t.name,o(),this.emitReserved("upgradeError",n)};function s(){i("transport closed")}function a(){i("socket closed")}function l(e){t&&e.name!==t.name&&o()}const c=()=>{t.removeListener("open",r),t.removeListener("error",i),t.removeListener("close",s),this.off("close",a),this.off("upgrading",l)};t.once("open",r),t.once("error",i),t.once("close",s),this.once("close",a),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let Yc=class extends Kc{constructor(e,t={}){const n="object"==typeof e?e:t;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(e=>Dc[e]).filter(e=>!!e)),super(e,n)}};const Gc="function"==typeof ArrayBuffer,Jc=Object.prototype.toString,Xc="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Jc.call(Blob),Qc="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Jc.call(File);function Zc(e){return Gc&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Xc&&e instanceof Blob||Qc&&e instanceof File}function eu(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(eu(e[t]))return!0;return!1}if(Zc(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return eu(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&eu(e[t]))return!0;return!1}function tu(e){const t=[],n=e.data,r=e;return r.data=nu(n,t),r.attachments=t.length,{packet:r,buffers:t}}function nu(e,t){if(!e)return e;if(Zc(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=nu(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=nu(e[r],t));return n}return e}function ru(e,t){return e.data=ou(e.data,t),delete e.attachments,e}function ou(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=ou(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ou(e[n],t));return e}const iu=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var su;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(su||(su={}));function au(e){return"[object Object]"===Object.prototype.toString.call(e)}class lu extends gc{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===su.BINARY_EVENT;n||t.type===su.BINARY_ACK?(t.type=n?su.EVENT:su.ACK,this.reconstructor=new cu(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Zc(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===su[n.type])throw new Error("unknown packet type "+n.type);if(n.type===su.BINARY_EVENT||n.type===su.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const o=e.substring(r,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(o)}if("/"===e.charAt(t+1)){const r=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}n.nsp=e.substring(r,t)}else n.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!lu.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case su.CONNECT:return au(t);case su.DISCONNECT:return void 0===t;case su.CONNECT_ERROR:return"string"==typeof t||au(t);case su.EVENT:case su.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===iu.indexOf(t[0]));case su.ACK:case su.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class cu{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=ru(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var uu=Object.freeze({__proto__:null,Decoder:lu,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==su.EVENT&&e.type!==su.ACK||!eu(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===su.EVENT?su.BINARY_EVENT:su.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==su.BINARY_EVENT&&e.type!==su.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=tu(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return su},protocol:5});function du(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const hu=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class pu extends gc{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[du(e,"open",this.onopen.bind(this)),du(e,"packet",this.onpacket.bind(this)),du(e,"error",this.onerror.bind(this)),du(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,r,o;if(hu.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:su.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),i.id=e}const s=null===(r=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===r?void 0:r.writable,a=this.connected&&!(null===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const o=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r),i=(...e)=>{this.io.clearTimeoutFn(o),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{const o=(e,t)=>e?r(e):n(t);o.withError=!0,t.push(o),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>{if(n!==this._queue[0])return;return null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:su.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case su.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case su.EVENT:case su.BINARY_EVENT:this.onevent(e);break;case su.ACK:case su.BINARY_ACK:this.onack(e);break;case su.DISCONNECT:this.ondisconnect();break;case su.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,t.packet({type:su.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:su.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function _u(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}_u.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},_u.prototype.reset=function(){this.attempts=0},_u.prototype.setMin=function(e){this.ms=e},_u.prototype.setMax=function(e){this.max=e},_u.prototype.setJitter=function(e){this.jitter=e};class fu extends gc{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,Ec(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new _u({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||uu;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Yc(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=du(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=du(t,"error",o);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{r(),o(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(du(e,"ping",this.onping.bind(this)),du(e,"data",this.ondata.bind(this)),du(e,"error",this.onerror.bind(this)),du(e,"close",this.onclose.bind(this)),du(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){yc(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new pu(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const mu={};function gu(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),r=qc(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const o=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port+t,r.href=r.protocol+"://"+o+(n&&n.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=mu[o]&&i in mu[o].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new fu(r,t):(mu[o]||(mu[o]=new fu(r,t)),a=mu[o]),n.query&&!t.query&&(t.query=n.queryKey),a.socket(n.path,t)}Object.assign(gu,{Manager:fu,Socket:pu,io:gu,connect:gu});var yu,vu,wu,bu=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},Su=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class Eu{constructor(e,t=tr.PROD){yu.set(this,null),vu.set(this,void 0),wu.set(this,void 0),bu(this,vu,e,"f"),bu(this,wu,t,"f")}connect(){return new Promise((e,t)=>{bu(this,yu,gu(lr({urlName:"APP_POSE_DETECTION_WEBSOCKET_URL",urlType:Su(this,wu,"f")})),"f"),Su(this,yu,"f").on("connect",()=>{var n;const r=null===(n=Su(this,yu,"f"))||void 0===n?void 0:n.id;r?e(r):t("Failed to obtain socket ID.")}),Su(this,yu,"f").on("connect_error",e=>{t(e)})})}videoEmit({image:e,scanId:t}){if(!Su(this,yu,"f"))throw new Error("Socket is not connected");Su(this,yu,"f").emit("video",{image:e,user_unique_key:t})}disconnect(){var e;null===(e=Su(this,yu,"f"))||void 0===e||e.disconnect()}poseStatus(e){if(!Su(this,yu,"f"))throw new Error("Socket is not connected");Su(this,yu,"f").on("pose_status",t=>{null==e||e(t)})}connected(){var e;return!!(null===(e=Su(this,yu,"f"))||void 0===e?void 0:e.connected)}}yu=new WeakMap,vu=new WeakMap,wu=new WeakMap;var Pu,Tu,ku,xu,Cu,Ou,ju,Ru,Au,Nu,Fu=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function s(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){e.done?o(e.value):function(e){return e instanceof n?e:new n(function(t){t(e)})}(e.value).then(s,a)}l((r=r.apply(e,t||[])).next())})},Iu=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},Mu=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class Uu{constructor(e,t=tr.PROD){Pu.add(this),Tu.set(this,new Map),ku.set(this,new Map),xu.set(this,void 0),Cu.set(this,void 0),Ru.set(this,e=>{if(e){const t=Mu(this,Tu,"f").get(e),n=Mu(this,ku,"f").get(e);null==t||t.close(),n&&clearTimeout(n),Mu(this,Tu,"f").delete(e),Mu(this,ku,"f").delete(e)}else Mu(this,Tu,"f").forEach(e=>e.close()),Mu(this,ku,"f").forEach(e=>clearTimeout(e)),Mu(this,Tu,"f").clear(),Mu(this,ku,"f").clear()}),Au.set(this,({onSuccess:e,onError:t,tryonId:n})=>{const r=setTimeout(()=>{Mu(this,Nu,"f").call(this,{onSuccess:e,onError:t,tryonId:n}),Mu(this,Ru,"f").call(this,n)},3e5);Mu(this,ku,"f").set(n,r)}),this.handleTryOnWebSocket=({tryonId:e,onError:t,onSuccess:n,onClose:r,onOpen:o})=>{if(!1===or(e))throw new Error(Xn);Mu(this,Ru,"f").call(this,e);const i=`${lr({urlName:jn,urlType:Mu(this,Cu,"f")})}${$n}?tryonId=${e}`,s=new WebSocket(i);Mu(this,Tu,"f").set(e,s),s.onopen=()=>{null==o||o(),Mu(this,Au,"f").call(this,{onSuccess:n,onError:t,tryonId:e})},s.onmessage=r=>{let o;try{o=JSON.parse(r.data)}catch(e){return void console.log("Invalid JSON:",r.data)}"success"===(null==o?void 0:o.status)?null==n||n(o):null==t||t(o);const i=Mu(this,ku,"f").get(e);i&&clearTimeout(i),Mu(this,ku,"f").delete(e)},s.onclose=()=>{null==r||r()},s.onerror=e=>{null==t||t(e)}},Nu.set(this,e=>Fu(this,[e],void 0,function*({onSuccess:e,onError:t,tryonId:n}){try{const t=yield this.getTryOnResult({tryonId:n});null==e||e(t.data)}catch(e){null==t||t(e)}})),this.getTryOnResult=({tryonId:e})=>{if(!1===or(e))throw new Error(Xn);const t=`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${Bn}/${e}`;return ln.post(t,null,{headers:{"X-Api-Key":Mu(this,xu,"f")}})},Iu(this,xu,e,"f"),Iu(this,Cu,t,"f")}uploadFile(e){return Fu(this,arguments,void 0,function*({files:e,userEmail:t,fileNoLimit:n=2}){if(!1===or(e,t))throw new Error(Xn);if(!cr(t.trim()))throw new Error(Zn);if(n<=0)throw new Error(`Provide valid file number limit ${n}.`);if((null==e?void 0:e.length)>n)throw new Error(`Cannot allow more than ${n} files.`);try{const n={userEmail:t,userImages:[]};null==e||e.forEach(e=>{n.userImages.push(e.name)});const r=yield Mu(this,Pu,"m",Ou).call(this,n);for(const t of e)yield Mu(this,Pu,"m",ju).call(this,r.data.uploadUrls[t.name].url,t);return"uploaded successfully!"}catch(e){throw e}})}getUploadedFiles(e){if(!1===or(e))throw new Error(Xn);if(!cr(e.trim()))throw new Error(Zn);const t={userEmail:e};return ln.post(`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${zn}`,t,{headers:{"X-Api-Key":Mu(this,xu,"f")}})}deleteImage({userEmail:e,fileName:t}){if(!1===or(e,t))throw new Error(Xn);if(!cr(e.trim()))throw new Error(Zn);const n={userEmail:e,file:t};return ln.delete(`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${Dn}`,{headers:{"X-Api-Key":Mu(this,xu,"f")},data:n})}handleTryOnSubmit({shopDomain:e,products:t,selectedUserImages:n,requestSource:r,callbackUrl:o,openTryonId:i,selectedProductImageUrl:s,token:a}){if(!1===or(e,t,a))throw new Error(Xn);const l=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({products:t,customerStoreUrl:e},null!=n&&{selectedUserImages:n}),null!=r&&{requestSource:r}),null!=o&&{callbackUrl:o}),null!=i&&{openTryonId:i}),null!=s&&{selectedProductImageUrl:s}),c=`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${$n}`,u={"X-Api-Key":Mu(this,xu,"f")};return a&&(u.Authorization=`Bearer ${a}`),ln.post(c,l,{headers:u})}getShareLink(e){return ln.post(`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${Vn}`,{tryonId:e},{headers:{"X-Api-Key":Mu(this,xu,"f")}})}getProductImageEligibility({storeUrl:e,productHandle:t,imageURL:n,productDescription:r}){if(!1===or(e,t,n))throw new Error(Xn);const o={storeUrl:e,productHandle:t,imageURL:n,productDescription:null!=r?r:null},i=`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${Yn}`;return ln.post(i,o,{headers:{"X-Api-Key":Mu(this,xu,"f")}})}}Tu=new WeakMap,ku=new WeakMap,xu=new WeakMap,Cu=new WeakMap,Ru=new WeakMap,Au=new WeakMap,Nu=new WeakMap,Pu=new WeakSet,Ou=function(e){if(!1===or(e))throw new Error(Xn);return ln.post(`${lr({urlName:On,urlType:Mu(this,Cu,"f")})}${Ln}`,e,{headers:{"Content-Type":"application/json","X-Api-Key":Mu(this,xu,"f")}})},ju=function(e,t){if(!1===or(e,t))throw new Error(Xn);return ln.put(e,t,{headers:{"Content-Type":t.type}})};var Lu,zu,Du,Bu=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},$u=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};Lu=new WeakMap,zu=new WeakMap,function(e){e.DEV="dev",e.STAGING="staging",e.PROD="prod"}(Du||(Du={}));const qu=new class{constructor(e,t=tr.PROD){Lu.set(this,void 0),zu.set(this,void 0),Bu(this,Lu,e,"f"),Bu(this,zu,t,"f"),this.auth=new fr($u(this,Lu,"f"),$u(this,zu,"f")),this.custom=new wr($u(this,Lu,"f"),$u(this,zu,"f")),this.fileUpload=new Nl($u(this,Lu,"f"),$u(this,zu,"f")),this.measurement=new Gl($u(this,Lu,"f"),$u(this,zu,"f")),this.poseDetection=new Eu($u(this,Lu,"f"),$u(this,zu,"f")),this.tryOn=new Uu($u(this,Lu,"f"),$u(this,zu,"f"))}}("8e35dfd4-010c-40ca-ad79-fc72dc307efb",Du.STAGING);let Wu,Hu=null,Vu=null;var Ku=t.memo(function({setIsScanLocked:o,resetDetector:i,scanID:s,setIsVideoUploaded:a,setScanFailsError:l,setScanStartTime:c,setScanUniqueKey:u,userDetails:d,config:h}){const{gender:p,heightInCm:_,email:f,shopDomain:m}=d,g=t.useRef(null),y=t.useRef(null),[v,w]=t.useState([]),[b,S]=t.useState(!0),[E,P]=t.useState(!1),[T,k]=t.useState(!1),[x,C]=t.useState(!0),[O,j]=t.useState(!1),R=t.useRef(null),[A,N]=t.useState(""),[F,I]=t.useState([]),[M,U]=t.useState(""),[L,z]=t.useState(!1),[D,B]=t.useState(!1),[$,q]=t.useState(!1),[W,H]=t.useState([]),[V,K]=t.useState(!1),Y=t.useRef(!0),G=t.useRef(!0),J=t.useRef(!1);let X=0;const{setStartGyro:Q,handleFileUpload:ne,setUploadLoading:re}=t.useContext(ee),oe=()=>{J.current=!1,clearTimeout(Wu),R.current&&clearTimeout(R.current),u(r.generateUuid()),l(""),re?.(!1),w([]),S(!0),P(!1),k(!1),C(!0),j(!1),R.current=null,N(""),I([]),U(""),z(!L),Q(!1),te.stopAudio(),B(!1),q(!1),X=0,null!==y.current&&y.current.stop(),W.forEach(e=>{y.current&&y.current.removeEventListener("dataavailable",e)}),H([]),Y.current=!0,K(!1),a(!1)},ie=t.useCallback(()=>{setTimeout(()=>{S(!1)},1e3)},[]),se=t.useCallback(()=>{r.rescanSupportCaptureEvent({eventName:`${m}/rescan`,email:f,scanID:s,height:_,gender:p,status:!1}),Y.current=!1,oe(),me()},[oe,s,f]),ae=t.useCallback(()=>{Y.current=!1,q(!0),K(!1),R.current&&clearTimeout(R.current),y.current&&y.current.pause(),te.stopAudio(),qu.poseDetection.disconnect(),X=0,y.current&&y.current.stop(),W.forEach(e=>{y.current&&y.current.removeEventListener("dataavailable",e)}),H([]),clearTimeout(Wu)},[y,W,te,Y]),le=n.videoTypes.filter(e=>MediaRecorder.isTypeSupported(e)),ce=t.useCallback(async()=>{Y.current=!0,await te.playAudio(`${n.voiceOverAssetsPath}SpotOn.mp3`),q(!1),K(!1),R.current&&clearTimeout(R.current),P(!1)},[R,te]),ue=t.useCallback(async()=>{try{Hu=await qu.poseDetection.connect(),r.qo.capture(`${m}/pose_detection_connected`,{scanID:s,email:f,id:Hu})}catch(e){console.log(e,"while connecting websocket")}},[s,m,f]),de=t.useCallback(({data:e})=>{e&&e.size>0&&Y.current&&(w(t=>t.concat(e)),!J.current&&g.current&&(J.current=!0))},[ce,r.handleScanTimeCapture,m,s,f,g]),he=t.useCallback(async()=>{F.length>0&&Y.current&&(await te.playAudio(n.voiceOverAssetsPath+F[F.length-1]),Y.current&&(Wu=setTimeout(he,2e3)))},[F,Y]),pe=t.useCallback(()=>{y&&y.current&&y.current.stop(),P(!0);try{if(g&&g.current&&g.current.stream){const e={mimeType:le[0]};y.current=new MediaRecorder(g.current.stream,e),y.current.addEventListener("dataavailable",de),H([...W,de]),y.current.start(1e3),C(!1)}}catch(e){console.log("error while using media recorder",e)}},[g,le,de,W]),_e=t.useCallback(async()=>{R.current&&clearTimeout(R.current),pe(),Y.current&&(R.current=setTimeout(async()=>{Y.current&&(await te.playAudio(`${n.voiceOverAssetsPath}SpotOn.mp3`),P(!1))},15e3)),k(!0),Y.current&&await te.playAudio(`${n.voiceOverAssetsPath}Spin.mp3`)},[pe,Y,te]),fe=t.useCallback(({data:e})=>{e.size>0&&qu.poseDetection.connected()&&(qu.poseDetection.poseStatus(async e=>{if(e&&e.audio&&e.audio.length>0){const t=document.querySelector("#audioElement");!0===e.status&&e.sid===Hu?X<2?(0===X&&t?.paused&&await te.playAudio(n.voiceOverAssetsPath+e.audio),X+=1):(U(e.audio),clearTimeout(Wu),qu.poseDetection.disconnect(),setTimeout(_e,1e3)):(X=0,!t?.paused||Vu&&Vu?.audioName===e.audio?Vu?.audioName===e.audio&&t?.paused&&(Vu&&Vu.no_of_times_skipped>=Vu.skipCount?(Vu.no_of_times_skipped=0,te.playAudio(n.voiceOverAssetsPath+e.audio)):Vu&&(Vu.no_of_times_skipped+=1)):(Vu={skipCount:2,no_of_times_skipped:0,audioName:e.audio},te.playAudio(n.voiceOverAssetsPath+e.audio)))}}),g?.current&&null!==g.current.getScreenshot()&&qu.poseDetection.videoEmit({image:g.current.getScreenshot()||"",scanId:s}))},[g,s,qu,Hu,X,_e,te]),me=t.useCallback(async()=>{j(!0),Q(!0),G.current&&(G.current=!1,r.handleScanTimeCapture({eventName:"scan started",scanID:s,status:"success",email:f})),c(r.getCurrentTimeInSeconds()),S(!0),Y.current&&await te.playAudio(`${n.voiceOverAssetsPath}StartScan.mp3`),Y.current&&await te.playAudio(`${n.voiceOverAssetsPath}LiftArmsAndHoldAtHip.mp3`),Y.current&&(j(!1),P(!0),B(!0),K(!0),ie());try{if(g&&g.current&&g.current.stream&&Y.current){const e={mimeType:le[0]};Y.current&&(y.current=new MediaRecorder(g.current.stream,e)),Y.current&&y.current&&y.current.addEventListener("dataavailable",fe),H([...W,fe]),y.current&&y.current.start(1e3),C(!1),Y.current&&(Wu=setTimeout(he,2e3))}}catch(e){console.log("error ----------",e)}},[g,le,fe,W,he,Y]);return t.useEffect(()=>(m&&(o(!0),ue()),()=>{Hu&&(qu.poseDetection.disconnect(),r.qo.capture(`${m}/pose_detection_disconnected`,{scanID:s,email:f,id:Hu})),W.forEach(e=>{y?.current?.removeEventListener("dataavailable",e)})}),[L,m]),t.useEffect(()=>{F.push(A)},[A]),t.useEffect(()=>{I([])},[M]),t.useEffect(()=>{const e=v.length&&v.length>0;x||!e||E||!Y.current||$||y&&y.current&&(E||(y.current.stop(),C(!0)))},[x,E,v,$]),t.useEffect(()=>{const e=v.length&&v.length>0;if(x||!e||E)console.log("No video found to upload");else if(y&&y.current&&Y.current&&!$&&!E){const e=new File(v,`${s}.webm`,{type:"video/webm"});re?.(!0),l(""),ne?.(e)}},[x,E,v,$,y,Y]),t.useEffect(()=>{oe()},[]),e.jsx(Z,{resetDetector:i,handleShowStreamCamera:oe,loadingCam:b,handlePause:ae,showRestart:D,pause:$,handleReScan:se,recordingStarted:E,isScanning:O,startSendingVideoFrames:me,faceDone:T,stopRecording:ce,showPause:V,webcamRef:g,handleUserMedia:ie,config:h})});function Yu({scanID:n,userDetails:r,setIsVideoUploaded:o,setScanFailsError:i,setScanStartTime:s,setScanUniqueKey:a,config:l}){const[c,u]=t.useState(90),[d,h]=t.useState(0),[p,_]=t.useState(null),[f,m]=t.useState(!1),[g,y]=t.useState(0),v=t.useRef([]),[w,b]=t.useState(!1),S=c-d,E=S>=80&&S<=95;t.useEffect(()=>{if("undefined"!=typeof window&&window.DeviceOrientationEvent){const e=e=>{if(null!==e.beta){let t=Math.abs(e.beta);null!==e.gamma&&(t*=Math.cos(e.gamma*Math.PI/180)),t=Math.max(0,Math.min(180,t)),u(t)}},t=async()=>{const t=DeviceOrientationEvent;if(t&&"function"==typeof t.requestPermission)try{"granted"===await t.requestPermission()&&window.addEventListener("deviceorientation",e)}catch(e){console.error("Permission error",e)}else window.addEventListener("deviceorientation",e);return()=>{e&&window.removeEventListener("deviceorientation",e)}};document.addEventListener("click",t,{once:!0})}},[]),t.useEffect(()=>{if(v.current=[...v.current.slice(-4),S],v.current.length>=5){const e=Math.max(...v.current)-Math.min(...v.current);y(E&&e<2?e=>Math.min(100,e+10):e=>Math.max(0,e-20))}E||null===p&&!f||T()},[S,E,p,f]),t.useEffect(()=>{g>=100&&null===p&&!f&&P(),g<50&&null!==p&&T()},[g,p,f]);const P=()=>{_(3);const e=setInterval(()=>{_(t=>null===t||t<=1?(clearInterval(e),m(!0),null):t-1)},1e3)},T=()=>{_(null),w||m(!1)};return e.jsx(A,{angle:S,countdown:p,isScanning:f,isInTargetRange:E,stabilityScore:g,config:l,children:f&&e.jsx(Ku,{setIsScanLocked:b,resetDetector:()=>{u(90),h(0),_(null),m(!1),y(0),b(!1),v.current=[]},scanID:n,userDetails:r,setIsVideoUploaded:o,setScanFailsError:i,setScanStartTime:s,setScanUniqueKey:a,config:l})})}function Gu({message:o,config:i}){const[s]=t.useState(!0),{translate:a}=t.useContext(X)||{};return e.jsx(v,{open:s,className:"confirm-modal",children:e.jsx("div",{className:"modal-main",children:e.jsx("div",{className:"text-center",children:o?e.jsxs(e.Fragment,{children:[e.jsx("h2",{style:{fontFamily:i?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:i?.style?.heading?.headingFontSize||"32px",color:i?.style?.heading?.headingColor||"#000",fontWeight:i?.style?.heading?.headingFontWeight||"normal"},children:"Seems camera already in use"}),e.jsxs("p",{className:"mt-[0.5rem] text-sm",style:{fontFamily:i?.style?.base?.baseFontFamily||"Inter, sans-serif",fontSize:i?.style?.base?.baseFontSize||"16px",color:i?.style?.base?.baseTextColor||"#000"},children:["Can you try closing the browser/app that is using the camera and try again here."," "]})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{style:{fontFamily:i?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:i?.style?.heading?.headingFontSize||"32px",color:i?.style?.heading?.headingColor||"#000",fontWeight:i?.style?.heading?.headingFontWeight||"normal"},children:a?.(n.LanguageKeys.Please_check_your_setting_for_camera_permission)}),e.jsx("p",{className:"mt-[0.5rem] text-sm",style:{fontFamily:i?.style?.base?.baseFontFamily||"Inter, sans-serif",fontSize:i?.style?.base?.baseFontSize||"16px",color:i?.style?.base?.baseTextColor||"#000"},children:`${a?.(n.LanguageKeys.Settings)} > ${r.getBrowserName()} > ${a?.(n.LanguageKeys.Enable_the_camera_permissions)}`})]})})})})}function Ju({setShowDrawer:i,config:s,loader:a}){const[l,c]=t.useState({disabled:!1,message:""}),[u,d]=t.useState(!0),h=t.useRef(null),p=t.useCallback(async()=>{const e=await r.checkCameraPermission();c(e),d(!1)},[]);return t.useEffect(()=>{p()},[]),u?e.jsx(o.LoadingScreen,{url:a}):l?.disabled?e.jsx(Gu,{config:s,message:l?.message}):e.jsx(M,{audio:!1,ref:h,screenshotQuality:1,videoConstraints:n.videoConstraints,mirrored:!0,onUserMedia:()=>i?.(!0),screenshotFormat:"image/jpeg",style:{position:"relative",top:0,bottom:0,zIndex:0,width:"100%",height:"100%",objectFit:"cover"}})}function Xu({link:r,onReady:o,wrapperClassName:s="[&_video]:rounded-t-[20px] w-full h-full"}){const a=t.useRef(null),l=t.useRef(null);let c={autoplay:!0,controls:!1,responsive:!0,fluid:!0,muted:!0,navigationUI:"hide",preload:"metadata",poster:n.videoPoster};return t.useEffect(()=>{if(!l.current&&r&&a?.current){const e=i(a.current,{...c});e.ready(()=>{l.current=e;const t={...c,sources:[{src:r,type:"application/x-mpegURL"}]};e.autoplay(t.autoplay),e.src(t.sources),o?.(e)})}},[r,a]),t.useEffect(()=>{const e=l.current;return()=>{e&&!e.isDisposed()&&(e.dispose(),l.current=null)}},[l]),e.jsx("div",{className:s,children:e.jsx("video",{ref:a,muted:!0,className:"video-js",playsInline:!0,onDrag:e=>e.preventDefault()})})}function Qu({scanFailsError:o,serverAtCapacity:i=!1,onNext:s,gender:a,setScanUniqueKey:l,resolvedConfig:c,setIsVideoUploaded:u}){const{translate:d}=t.useContext(X)||{},[h,p]=t.useState(!1),_=()=>{p(!h)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col h-full max-w-[28rem] mx-auto w-full rounded-t-[20px] overflow-y-auto",style:{background:c?.style?.base?.backgroundColor},children:[e.jsx("div",{className:"w-full max-w-[28rem] mx-auto pt-[1rem] px-[1rem]",children:e.jsx(n.Header,{noTitle:!0,resolvedConfig:c})}),e.jsxs("div",{className:"flex-1",children:[o&&e.jsxs("div",{className:"px-[1rem]",children:[e.jsx("h2",{className:"text-center",style:{fontFamily:c?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:c?.style?.heading?.headingFontSize||"32px",color:c?.style?.heading?.headingColor||"#000",fontWeight:c?.style?.heading?.headingFontWeight||"normal"},children:"There was an issue with your scan"}),e.jsx("p",{style:{fontFamily:c?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:"Reason:"}),e.jsx("p",{style:{fontFamily:c?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:r.handleErrorMessage(o)}),e.jsx("img",{className:"my-[0.5rem] aspect-[2/1.4] w-full object-cover",onClick:_,src:n.VIDEO_POSTER_GENDER_BASED[a],alt:"icon"})]}),i&&e.jsxs("div",{className:"p-[1rem] text-center",children:[e.jsxs("h3",{style:{fontFamily:c?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:c?.style?.heading?.headingFontSize||"32px",color:c?.style?.heading?.headingColor||"#000",fontWeight:c?.style?.heading?.headingFontWeight||"normal"},children:[d?.(n.LanguageKeys.Scan_s)," ",e.jsx("span",{children:d?.(n.LanguageKeys.vision_model)})," ",d?.(n.LanguageKeys.is_at_capacity)]}),e.jsx("p",{className:"text-base mt-[0.5rem]",style:{fontFamily:c?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:d?.(n.LanguageKeys.We_are_sorry_about_this_We_are_working_hard_to_add_capacity_Please_try_again_soon)})]})]}),o&&e.jsx("div",{className:"p-[1rem] flex gap-[0.5rem]",children:e.jsx(n.SpecificButton,{disabled:!1,buttonText:"Scan again",className:"!shadow-none",buttonFunc:()=>{s?s?.():l(r.generateUuid()),u(!1)},resolvedConfig:c})})]}),h&&e.jsxs(v,{className:"w-screen h-screen video-modal",onClose:_,open:h,children:[e.jsx("div",{className:"flex justifyEnd ",children:e.jsx("span",{className:"closeBtn",onClick:_,children:e.jsx(U,{className:"absolute right-[8px] top-[8px] text-white z-[9]"})})}),e.jsx("div",{className:"aspect-video object-cover rounded-[20px] ",children:e.jsx(Xu,{link:a?n.GENDER[a].PRE_LINK:n.GENDER.male.PRE_LINK,wrapperClassName:"w-screen h-screen fixed top-[0] left-[0]"})})]})]})}function Zu({scanId:o,userDetails:i,config:s,isFaceScan:a,isVideoUploadedCorrect:l,isMeasurementAvailable:c,onComplete:u,isSuccess:h}){const{gender:p,shopDomain:_,heightInCm:f,deviceFocalLength:m,userName:g,email:y,scanType:v}=i,w=[n.CLOTHING_CUSTOM_SCAN,n.CLOTHING_BANNER_SCAN,n.CLOTHING_CUSTOM_FIT_SCAN].includes(v),[b,S]=t.useState(!0),E=t.useCallback(async()=>{try{w&&await qu.auth.addUser({scanId:o,email:y,name:g,gender:p,height:f}),r.qo.capture(_,{scanID:o,email:y,height:f,focalLength:m,clothesFit:"0",gender:p})}catch(e){console.log(e)}},[w]);t.useEffect(()=>{l&&E()},[l]);const P=h||(a?c&&l:l||c);return e.jsx(d,{className:"flex h-full w-full flex-col ",children:e.jsxs("div",{className:"h-full w-full flex-col items-center justify-center flex",children:[e.jsx(Ju,{loader:s?.loader,setShowDrawer:S}),e.jsx(O,{open:b,onClose:(e,t)=>{},className:"camera-drawer",anchor:"bottom",children:e.jsx("div",{className:"max-w-[28rem] mx-auto w-full h-full flex text-center flex-col justify-between items-center bg-primary rounded-t-[30px] p-[1rem]",style:{background:s?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"w-full h-full flex flex-col",children:[e.jsx(n.Header,{title:"Your measurements are being taken",resolvedConfig:s}),e.jsx("div",{className:"flex items-center justify-center flex-1",children:e.jsx("video",{preload:"auto",className:"max-h-[calc(100vh-450px)] mx-auto w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:p===r.GenderType.Male?n.maleMeasurementProgress:n.measurementProgress,type:"video/mp4"})})}),P&&e.jsx(n.SpecificButton,{resolvedConfig:s,className:"!w-[180px] mx-auto",buttonText:"Next",buttonFunc:u&&u})]})})})]})})}exports.BodyScan=({userDetails:i,language:s=r.PreferredLanguage.English,config:a,onRetry:l,onScanSuccess:c,onComplete:u,onScanError:d,isError:h,isSuccess:p})=>{const{gender:_,scanType:f,shopDomain:m,heightInCm:g,email:y,deviceFocalLength:v,deviceModelName:w,callbackUrl:b}=i,[S,E]=t.useState(!1),[P,T]=t.useState(!1),[k,x]=t.useState(!1),[C,j]=t.useState({disabled:!1,message:""}),[R,A]=t.useState(""),[N,F]=t.useState(!1),[I,M]=t.useState(!0),[U,L]=t.useState(!1),[z,D]=t.useState(""),[B,q]=t.useState(r.getCurrentTimeInSeconds()),{gyroData:W}=function(e){const[n,r]=t.useState([]),[o,i]=t.useState(!1),s=t.useCallback(e=>{try{const{alpha:t,beta:n,gamma:o}=e;r(e=>[...e,{alpha:t?.toString()||void 0,beta:n?.toString()||void 0,gamma:o?.toString()||void 0,timestamp:(new Date).toISOString()}])}catch(e){console.log(e)}},[]),a=t.useCallback(async()=>{const e=DeviceOrientationEvent;if(void 0!==e&&"function"==typeof e.requestPermission)try{"granted"===await e.requestPermission()?i(!0):console.warn("Device orientation permission denied.")}catch(e){console.error("Error requesting device orientation permission:",e)}else i(!0)},[]);return t.useEffect(()=>(e&&o?window.addEventListener("deviceorientation",s):r([]),()=>{window.removeEventListener("deviceorientation",s)}),[e,o,s]),t.useEffect(()=>{e&&a()},[e,a]),{gyroData:n}}(U),{setPreferredLanguage:H}=t.useContext(X)||{},V=n.useLocalConfig(a),K=t.useCallback(()=>{D(r.generateUuid()),A(""),E(!1),F(!1)},[]),Y=e=>{d({...e,message:r.handleErrorMessage(e)}),G(),x(!1),A(e),T(!1),r.handleScanTimeCapture({eventName:`${m}/measurement_failed/fit-view`,scanID:z,status:"failed",email:y,message:r.handleErrorMessage(e)}),B&&r.handleScanTimeCapture({eventName:`${m}/scan_completion_time`,scanID:z,status:"failed",completionTime:r.getCurrentTimeInSeconds()-B,email:y})},G=()=>{q(null),D("")},J=t.useCallback(async e=>{if(e&&"success"===e?.scanStatus&&"intermediate"===e?.resultType&&200===e?.code)return r.handleScanTimeCapture({eventName:`${m}/measurement_success/intermediate`,scanID:z,status:"success",email:y}),void c?.(e);G();const t=z;x(!0),r.handleScanTimeCapture({eventName:`${m}/measurement_success/fit-view`,scanID:t,status:"success",email:y}),B&&r.handleScanTimeCapture({eventName:`${m}/scan_completion_time`,scanID:t,status:"success",completionTime:r.getCurrentTimeInSeconds()-B,email:y})},[f,m,z]),Z=e=>{x(!1),A(""),T(!1),qu.measurement.handleMeasurementSocket({scanId:e||z,onOpen:()=>{r.handleWebSocketCapture({eventName:`${m}/webSocket`,scanID:z,connection:"open",type:"measurement_recommendation",email:y})},onClose:()=>r.handleWebSocketCapture({eventName:`${m}/webSocket`,scanID:z,connection:"close",type:"measurement_recommendation",email:y}),onError:e=>{Y(e),r.handleWebSocketCapture({eventName:`${m}/webSocket`,scanID:z,connection:"error",type:"measurement_recommendation",email:y})},onSuccess:e=>{r.handleWebSocketCapture({eventName:`${m}/webSocket`,scanID:z,connection:"success",type:"measurement_recommendation",email:y}),J(e)}})},te=t.useCallback(async e=>{const t=r.createObjectMetadataArray({gender:_,focal_length:`${v}`,height:`${g}`,customer_store_url:m,clothes_fit:"0",scan_type:f,callback_url:b||"https://example.com/webhook"});r.handleScanTimeCapture({eventName:`${m}/body_scan_meta_data`,scanID:z,email:y,data:JSON.stringify(t)});try{await qu.fileUpload.uploadFileFrontend({file:e,arrayMetaData:t,scanId:z,email:y}),await qu.fileUpload.setDeviceInfo({model:w,detection:"manual",gyro:W,scanId:z}),console.log("video successfully uploaded"),F(!1),r.handleScanTimeCapture({eventName:`${m}/scan_success`,scanID:z,status:"success",email:y,data:JSON.stringify(t)}),r.handleScanTimeCapture({eventName:"scan finished",scanID:z,status:"success",email:y}),q(r.getCurrentTimeInSeconds()),setTimeout(()=>{F(!0)},3e3)}catch(e){r.handleScanTimeCapture({eventName:"scan finished",scanID:z,status:"failed",email:y,message:r.handleErrorMessage(e)}),r.handleScanTimeCapture({eventName:`${m}/scan_failed`,scanID:z,status:"failed",email:y,message:r.handleErrorMessage(e),data:JSON.stringify(t)}),A(r.handleErrorMessage(e)),F(!1),console.log(e,"video upload failed")}finally{L(!1)}},[z,W]),ne=t.useCallback(async e=>{try{const t=await qu.measurement.getMeasurementResult(e),n=t?.data?.isMeasured,o=B||r.getCurrentTimeInSeconds(),i=r.getCurrentTimeInSeconds(),s=300;if(M(!1),!1===n)return G(),void D(r.generateUuid());E(!0),!0===n?await J(null):null===n&&o>i+s?Y(t?.data?.error):Z(e)}catch(e){console.log(e),G(),D(r.generateUuid()),E(!1)}},[Y,J,D]),re=t.useCallback(async()=>{if(+g<152.4||+g>213.36)return void d({message:"Height must be between 152.4cm (5ft) and 213.36cm (7ft)"});const e=await r.checkCameraPermission();if(e.disabled)r.handleScanTimeCapture({eventName:`${m}/camera_activation`,scanID:z,status:"failed",email:y}),M(!1);else{z?ne(z):M(!1),r.handleScanTimeCapture({eventName:`${m}/camera_activation`,scanID:z,status:"success",email:y})}j(e),A(""),F(!1)},[ne,y,z,D,m]);return t.useEffect(()=>{H?.(s),r.qo.init(n.posthogPublicKey,{api_host:n.posthogPublicHost}),r.qo.capture("$pageview")},[]),t.useEffect(()=>{h||p||m&&re()},[m,g,h,p]),t.useEffect(()=>{h||p||N&&m&&z&&Z()},[N,m,z,h,p]),h?e.jsxs(Q,{children:[e.jsx(Ju,{}),e.jsx(O,{anchor:"bottom",open:!0,className:"camera-drawer",onClose:(e,t)=>{},children:e.jsx(Qu,{scanFailsError:R||h,onNext:()=>{},setScanUniqueKey:D,gender:_,resolvedConfig:V,setIsVideoUploaded:F})})]}):p?e.jsx(Zu,{isFaceScan:!1,scanId:z,isMeasurementAvailable:k,userDetails:i,isVideoUploadedCorrect:P,config:V,isSuccess:p}):I?e.jsx("div",{className:"flex top-0 !mt-0 left-0 z-[999] bg-opacity-80 bg-[#1b1b1b] absolute justify-center items-center w-full h-full",children:e.jsx(o.LoadingScreen,{url:V?.loader})}):C.disabled?e.jsx(Q,{children:e.jsx(Gu,{})}):S||R?!S&&!k||R?e.jsxs(Q,{children:[e.jsx(Ju,{}),e.jsx(O,{anchor:"bottom",open:!0,className:"camera-drawer",onClose:(e,t)=>{},children:e.jsx(Qu,{scanFailsError:R,onNext:()=>{l?.(),K()},setScanUniqueKey:D,gender:_,resolvedConfig:V,setIsVideoUploaded:F})})]}):e.jsx(Zu,{isFaceScan:!1,scanId:z,isMeasurementAvailable:k,userDetails:i,onComplete:u,isVideoUploadedCorrect:P,config:V}):e.jsx(ee.Provider,{value:{setStartGyro:L,handleFileUpload:te,setUploadLoading:E},children:e.jsx($,{children:e.jsx(Q,{children:e.jsx(Yu,{config:V,scanID:z,userDetails:i,setIsVideoUploaded:F,setScanFailsError:A,setScanStartTime:q,setScanUniqueKey:D})})})})};
20
20
  //# sourceMappingURL=bodyScan.js.map