@buildbase/sdk 0.0.29 → 0.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import{jsxs as e,jsx as t,Fragment as r}from"react/jsx-runtime";import*as n from"react";import a,{Component as o,useRef as i,useMemo as s,createContext as l,useReducer as c,useEffect as d,useCallback as u,useState as f,useContext as m,Suspense as p,lazy as h,forwardRef as g,createElement as b,useLayoutEffect as y}from"react";import*as v from"react-dom";import w from"react-dom";function x(e){var t,r,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e)){var a=e.length;for(t=0;t<a;t++)e[t]&&(r=x(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function S(){for(var e,t,r=0,n="",a=arguments.length;r<a;r++)(e=arguments[r])&&(t=x(e))&&(n&&(n+=" "),n+=t);return n}const k=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),N="-",C=[],E=e=>{const t=T(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=e;return{getClassGroupId:e=>{if(e.startsWith("[")&&e.endsWith("]"))return _(e);const r=e.split(N),n=""===r[0]&&r.length>1?1:0;return A(r,n,t)},getConflictingClassGroupIds:(e,t)=>{if(t){const t=n[e],a=r[e];return t?a?((e,t)=>{const r=new Array(e.length+t.length);for(let t=0;t<e.length;t++)r[t]=e[t];for(let n=0;n<t.length;n++)r[e.length+n]=t[n];return r})(a,t):t:a||C}return r[e]||C}}},A=(e,t,r)=>{if(0===e.length-t)return r.classGroupId;const n=e[t],a=r.nextPart.get(n);if(a){const r=A(e,t+1,a);if(r)return r}const o=r.validators;if(null===o)return;const i=0===t?e.join(N):e.slice(t).join(N),s=o.length;for(let e=0;e<s;e++){const t=o[e];if(t.validator(i))return t.classGroupId}},_=e=>-1===e.slice(1,-1).indexOf(":")?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),n=t.slice(0,r);return n?"arbitrary.."+n:void 0})(),T=e=>{const{theme:t,classGroups:r}=e;return P(r,t)},P=(e,t)=>{const r=k();for(const n in e){const a=e[n];R(a,r,n,t)}return r},R=(e,t,r,n)=>{const a=e.length;for(let o=0;o<a;o++){const a=e[o];I(a,t,r,n)}},I=(e,t,r,n)=>{"string"!=typeof e?"function"!=typeof e?M(e,t,r,n):D(e,t,r,n):O(e,t,r)},O=(e,t,r)=>{(""===e?t:U(t,e)).classGroupId=r},D=(e,t,r,n)=>{z(e)?R(e(n),t,r,n):(null===t.validators&&(t.validators=[]),t.validators.push(((e,t)=>({classGroupId:e,validator:t}))(r,e)))},M=(e,t,r,n)=>{const a=Object.entries(e),o=a.length;for(let e=0;e<o;e++){const[o,i]=a[e];R(i,U(t,o),r,n)}},U=(e,t)=>{let r=e;const n=t.split(N),a=n.length;for(let e=0;e<a;e++){const t=n[e];let a=r.nextPart.get(t);a||(a=k(),r.nextPart.set(t,a)),r=a}return r},z=e=>"isThemeGetter"in e&&!0===e.isThemeGetter,F=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),n=Object.create(null);const a=(a,o)=>{r[a]=o,t++,t>e&&(t=0,n=r,r=Object.create(null))};return{get(e){let t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(a(e,t),t):void 0},set(e,t){e in r?r[e]=t:a(e,t)}}},L=[],$=(e,t,r,n,a)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:n,isExternal:a}),V=e=>{const{prefix:t,experimentalParseClassName:r}=e;let n=e=>{const t=[];let r,n=0,a=0,o=0;const i=e.length;for(let s=0;s<i;s++){const i=e[s];if(0===n&&0===a){if(":"===i){t.push(e.slice(o,s)),o=s+1;continue}if("/"===i){r=s;continue}}"["===i?n++:"]"===i?n--:"("===i?a++:")"===i&&a--}const s=0===t.length?e:e.slice(o);let l=s,c=!1;s.endsWith("!")?(l=s.slice(0,-1),c=!0):s.startsWith("!")&&(l=s.slice(1),c=!0);return $(t,c,l,r&&r>o?r-o:void 0)};if(t){const e=t+":",r=n;n=t=>t.startsWith(e)?r(t.slice(e.length)):$(L,!1,t,void 0,!0)}if(r){const e=n;n=t=>r({className:t,parseClassName:e})}return n},W=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((e,r)=>{t.set(e,1e6+r)}),e=>{const r=[];let n=[];for(let a=0;a<e.length;a++){const o=e[a],i="["===o[0],s=t.has(o);i||s?(n.length>0&&(n.sort(),r.push(...n),n=[]),r.push(o)):n.push(o)}return n.length>0&&(n.sort(),r.push(...n)),r}},j=/\s+/,B=e=>{if("string"==typeof e)return e;let t,r="";for(let n=0;n<e.length;n++)e[n]&&(t=B(e[n]))&&(r&&(r+=" "),r+=t);return r},G=(e,...t)=>{let r,n,a,o;const i=e=>{const t=n(e);if(t)return t;const o=((e,t)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:a,sortModifiers:o}=t,i=[],s=e.trim().split(j);let l="";for(let e=s.length-1;e>=0;e-=1){const t=s[e],{isExternal:c,modifiers:d,hasImportantModifier:u,baseClassName:f,maybePostfixModifierPosition:m}=r(t);if(c){l=t+(l.length>0?" "+l:l);continue}let p=!!m,h=n(p?f.substring(0,m):f);if(!h){if(!p){l=t+(l.length>0?" "+l:l);continue}if(h=n(f),!h){l=t+(l.length>0?" "+l:l);continue}p=!1}const g=0===d.length?"":1===d.length?d[0]:o(d).join(":"),b=u?g+"!":g,y=b+h;if(i.indexOf(y)>-1)continue;i.push(y);const v=a(h,p);for(let e=0;e<v.length;++e){const t=v[e];i.push(b+t)}l=t+(l.length>0?" "+l:l)}return l})(e,r);return a(e,o),o};return o=s=>{const l=t.reduce((e,t)=>t(e),e());return r=(e=>({cache:F(e.cacheSize),parseClassName:V(e),sortModifiers:W(e),...E(e)}))(l),n=r.cache.get,a=r.cache.set,o=i,i(s)},(...e)=>o(((...e)=>{let t,r,n=0,a="";for(;n<e.length;)(t=e[n++])&&(r=B(t))&&(a&&(a+=" "),a+=r);return a})(...e))},K=[],H=e=>{const t=t=>t[e]||K;return t.isThemeGetter=!0,t},Z=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,q=/^\((?:(\w[\w-]*):)?(.+)\)$/i,J=/^\d+\/\d+$/,Y=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,X=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Q=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,ee=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,te=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,re=e=>J.test(e),ne=e=>!!e&&!Number.isNaN(Number(e)),ae=e=>!!e&&Number.isInteger(Number(e)),oe=e=>e.endsWith("%")&&ne(e.slice(0,-1)),ie=e=>Y.test(e),se=()=>!0,le=e=>X.test(e)&&!Q.test(e),ce=()=>!1,de=e=>ee.test(e),ue=e=>te.test(e),fe=e=>!pe(e)&&!we(e),me=e=>Ae(e,Re,ce),pe=e=>Z.test(e),he=e=>Ae(e,Ie,le),ge=e=>Ae(e,Oe,ne),be=e=>Ae(e,Te,ce),ye=e=>Ae(e,Pe,ue),ve=e=>Ae(e,Me,de),we=e=>q.test(e),xe=e=>_e(e,Ie),Se=e=>_e(e,De),ke=e=>_e(e,Te),Ne=e=>_e(e,Re),Ce=e=>_e(e,Pe),Ee=e=>_e(e,Me,!0),Ae=(e,t,r)=>{const n=Z.exec(e);return!!n&&(n[1]?t(n[1]):r(n[2]))},_e=(e,t,r=!1)=>{const n=q.exec(e);return!!n&&(n[1]?t(n[1]):r)},Te=e=>"position"===e||"percentage"===e,Pe=e=>"image"===e||"url"===e,Re=e=>"length"===e||"size"===e||"bg-size"===e,Ie=e=>"length"===e,Oe=e=>"number"===e,De=e=>"family-name"===e,Me=e=>"shadow"===e,Ue=G(()=>{const e=H("color"),t=H("font"),r=H("text"),n=H("font-weight"),a=H("tracking"),o=H("leading"),i=H("breakpoint"),s=H("container"),l=H("spacing"),c=H("radius"),d=H("shadow"),u=H("inset-shadow"),f=H("text-shadow"),m=H("drop-shadow"),p=H("blur"),h=H("perspective"),g=H("aspect"),b=H("ease"),y=H("animate"),v=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom",we,pe],w=()=>[we,pe,l],x=()=>[re,"full","auto",...w()],S=()=>[ae,"none","subgrid",we,pe],k=()=>["auto",{span:["full",ae,we,pe]},ae,we,pe],N=()=>[ae,"auto",we,pe],C=()=>["auto","min","max","fr",we,pe],E=()=>["auto",...w()],A=()=>[re,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...w()],_=()=>[e,we,pe],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom",ke,be,{position:[we,pe]}],P=()=>["auto","cover","contain",Ne,me,{size:[we,pe]}],R=()=>[oe,xe,he],I=()=>["","none","full",c,we,pe],O=()=>["",ne,xe,he],D=()=>[ne,oe,ke,be],M=()=>["","none",p,we,pe],U=()=>["none",ne,we,pe],z=()=>["none",ne,we,pe],F=()=>[ne,we,pe],L=()=>[re,"full",...w()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ie],breakpoint:[ie],color:[se],container:[ie],"drop-shadow":[ie],ease:["in","out","in-out"],font:[fe],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ie],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ie],shadow:[ie],spacing:["px",ne],text:[ie],"text-shadow":[ie],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",re,pe,we,g]}],container:["container"],columns:[{columns:[ne,pe,we,s]}],"break-after":[{"break-after":["auto","avoid","all","avoid-page","page","left","right","column"]}],"break-before":[{"break-before":["auto","avoid","all","avoid-page","page","left","right","column"]}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:v()}],overflow:[{overflow:["auto","hidden","clip","visible","scroll"]}],"overflow-x":[{"overflow-x":["auto","hidden","clip","visible","scroll"]}],"overflow-y":[{"overflow-y":["auto","hidden","clip","visible","scroll"]}],overscroll:[{overscroll:["auto","contain","none"]}],"overscroll-x":[{"overscroll-x":["auto","contain","none"]}],"overscroll-y":[{"overscroll-y":["auto","contain","none"]}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:x()}],"inset-x":[{"inset-x":x()}],"inset-y":[{"inset-y":x()}],start:[{start:x()}],end:[{end:x()}],top:[{top:x()}],right:[{right:x()}],bottom:[{bottom:x()}],left:[{left:x()}],visibility:["visible","invisible","collapse"],z:[{z:[ae,"auto",we,pe]}],basis:[{basis:[re,"full","auto",s,...w()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,re,"auto","initial","none",pe]}],grow:[{grow:["",ne,we,pe]}],shrink:[{shrink:["",ne,we,pe]}],order:[{order:[ae,"first","last","none",we,pe]}],"grid-cols":[{"grid-cols":S()}],"col-start-end":[{col:k()}],"col-start":[{"col-start":N()}],"col-end":[{"col-end":N()}],"grid-rows":[{"grid-rows":S()}],"row-start-end":[{row:k()}],"row-start":[{"row-start":N()}],"row-end":[{"row-end":N()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":C()}],"auto-rows":[{"auto-rows":C()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe","normal"]}],"justify-items":[{"justify-items":["start","end","center","stretch","center-safe","end-safe","normal"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch","center-safe","end-safe"]}],"align-content":[{content:["normal","start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"]}],"align-items":[{items:["start","end","center","stretch","center-safe","end-safe",{baseline:["","last"]}]}],"align-self":[{self:["auto","start","end","center","stretch","center-safe","end-safe",{baseline:["","last"]}]}],"place-content":[{"place-content":["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"]}],"place-items":[{"place-items":["start","end","center","stretch","center-safe","end-safe","baseline"]}],"place-self":[{"place-self":["auto","start","end","center","stretch","center-safe","end-safe"]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":w()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":w()}],"space-y-reverse":["space-y-reverse"],size:[{size:A()}],w:[{w:[s,"screen",...A()]}],"min-w":[{"min-w":[s,"screen","none",...A()]}],"max-w":[{"max-w":[s,"screen","none","prose",{screen:[i]},...A()]}],h:[{h:["screen","lh",...A()]}],"min-h":[{"min-h":["screen","lh","none",...A()]}],"max-h":[{"max-h":["screen","lh",...A()]}],"font-size":[{text:["base",r,xe,he]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[n,we,ge]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",oe,pe]}],"font-family":[{font:[Se,pe,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[a,we,pe]}],"line-clamp":[{"line-clamp":[ne,"none",we,ge]}],leading:[{leading:[o,...w()]}],"list-image":[{"list-image":["none",we,pe]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",we,pe]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:_()}],"text-color":[{text:_()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:["solid","dashed","dotted","double","wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",we,he]}],"text-decoration-color":[{decoration:_()}],"underline-offset":[{"underline-offset":[ne,"auto",we,pe]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:w()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",we,pe]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",we,pe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:T()}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","space","round"]}]}],"bg-size":[{bg:P()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ae,we,pe],radial:["",we,pe],conic:[ae,we,pe]},Ce,ye]}],"bg-color":[{bg:_()}],"gradient-from-pos":[{from:R()}],"gradient-via-pos":[{via:R()}],"gradient-to-pos":[{to:R()}],"gradient-from":[{from:_()}],"gradient-via":[{via:_()}],"gradient-to":[{to:_()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:O()}],"border-w-x":[{"border-x":O()}],"border-w-y":[{"border-y":O()}],"border-w-s":[{"border-s":O()}],"border-w-e":[{"border-e":O()}],"border-w-t":[{"border-t":O()}],"border-w-r":[{"border-r":O()}],"border-w-b":[{"border-b":O()}],"border-w-l":[{"border-l":O()}],"divide-x":[{"divide-x":O()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":O()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:["solid","dashed","dotted","double","hidden","none"]}],"divide-style":[{divide:["solid","dashed","dotted","double","hidden","none"]}],"border-color":[{border:_()}],"border-color-x":[{"border-x":_()}],"border-color-y":[{"border-y":_()}],"border-color-s":[{"border-s":_()}],"border-color-e":[{"border-e":_()}],"border-color-t":[{"border-t":_()}],"border-color-r":[{"border-r":_()}],"border-color-b":[{"border-b":_()}],"border-color-l":[{"border-l":_()}],"divide-color":[{divide:_()}],"outline-style":[{outline:["solid","dashed","dotted","double","none","hidden"]}],"outline-offset":[{"outline-offset":[ne,we,pe]}],"outline-w":[{outline:["",ne,xe,he]}],"outline-color":[{outline:_()}],shadow:[{shadow:["","none",d,Ee,ve]}],"shadow-color":[{shadow:_()}],"inset-shadow":[{"inset-shadow":["none",u,Ee,ve]}],"inset-shadow-color":[{"inset-shadow":_()}],"ring-w":[{ring:O()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:_()}],"ring-offset-w":[{"ring-offset":[ne,he]}],"ring-offset-color":[{"ring-offset":_()}],"inset-ring-w":[{"inset-ring":O()}],"inset-ring-color":[{"inset-ring":_()}],"text-shadow":[{"text-shadow":["none",f,Ee,ve]}],"text-shadow-color":[{"text-shadow":_()}],opacity:[{opacity:[ne,we,pe]}],"mix-blend":[{"mix-blend":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"]}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ne]}],"mask-image-linear-from-pos":[{"mask-linear-from":D()}],"mask-image-linear-to-pos":[{"mask-linear-to":D()}],"mask-image-linear-from-color":[{"mask-linear-from":_()}],"mask-image-linear-to-color":[{"mask-linear-to":_()}],"mask-image-t-from-pos":[{"mask-t-from":D()}],"mask-image-t-to-pos":[{"mask-t-to":D()}],"mask-image-t-from-color":[{"mask-t-from":_()}],"mask-image-t-to-color":[{"mask-t-to":_()}],"mask-image-r-from-pos":[{"mask-r-from":D()}],"mask-image-r-to-pos":[{"mask-r-to":D()}],"mask-image-r-from-color":[{"mask-r-from":_()}],"mask-image-r-to-color":[{"mask-r-to":_()}],"mask-image-b-from-pos":[{"mask-b-from":D()}],"mask-image-b-to-pos":[{"mask-b-to":D()}],"mask-image-b-from-color":[{"mask-b-from":_()}],"mask-image-b-to-color":[{"mask-b-to":_()}],"mask-image-l-from-pos":[{"mask-l-from":D()}],"mask-image-l-to-pos":[{"mask-l-to":D()}],"mask-image-l-from-color":[{"mask-l-from":_()}],"mask-image-l-to-color":[{"mask-l-to":_()}],"mask-image-x-from-pos":[{"mask-x-from":D()}],"mask-image-x-to-pos":[{"mask-x-to":D()}],"mask-image-x-from-color":[{"mask-x-from":_()}],"mask-image-x-to-color":[{"mask-x-to":_()}],"mask-image-y-from-pos":[{"mask-y-from":D()}],"mask-image-y-to-pos":[{"mask-y-to":D()}],"mask-image-y-from-color":[{"mask-y-from":_()}],"mask-image-y-to-color":[{"mask-y-to":_()}],"mask-image-radial":[{"mask-radial":[we,pe]}],"mask-image-radial-from-pos":[{"mask-radial-from":D()}],"mask-image-radial-to-pos":[{"mask-radial-to":D()}],"mask-image-radial-from-color":[{"mask-radial-from":_()}],"mask-image-radial-to-color":[{"mask-radial-to":_()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"]}],"mask-image-conic-pos":[{"mask-conic":[ne]}],"mask-image-conic-from-pos":[{"mask-conic-from":D()}],"mask-image-conic-to-pos":[{"mask-conic-to":D()}],"mask-image-conic-from-color":[{"mask-conic-from":_()}],"mask-image-conic-to-color":[{"mask-conic-to":_()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:T()}],"mask-repeat":[{mask:["no-repeat",{repeat:["","x","y","space","round"]}]}],"mask-size":[{mask:P()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",we,pe]}],filter:[{filter:["","none",we,pe]}],blur:[{blur:M()}],brightness:[{brightness:[ne,we,pe]}],contrast:[{contrast:[ne,we,pe]}],"drop-shadow":[{"drop-shadow":["","none",m,Ee,ve]}],"drop-shadow-color":[{"drop-shadow":_()}],grayscale:[{grayscale:["",ne,we,pe]}],"hue-rotate":[{"hue-rotate":[ne,we,pe]}],invert:[{invert:["",ne,we,pe]}],saturate:[{saturate:[ne,we,pe]}],sepia:[{sepia:["",ne,we,pe]}],"backdrop-filter":[{"backdrop-filter":["","none",we,pe]}],"backdrop-blur":[{"backdrop-blur":M()}],"backdrop-brightness":[{"backdrop-brightness":[ne,we,pe]}],"backdrop-contrast":[{"backdrop-contrast":[ne,we,pe]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,we,pe]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,we,pe]}],"backdrop-invert":[{"backdrop-invert":["",ne,we,pe]}],"backdrop-opacity":[{"backdrop-opacity":[ne,we,pe]}],"backdrop-saturate":[{"backdrop-saturate":[ne,we,pe]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,we,pe]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",we,pe]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",we,pe]}],ease:[{ease:["linear","initial",b,we,pe]}],delay:[{delay:[ne,we,pe]}],animate:[{animate:["none",y,we,pe]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[h,we,pe]}],"perspective-origin":[{"perspective-origin":v()}],rotate:[{rotate:U()}],"rotate-x":[{"rotate-x":U()}],"rotate-y":[{"rotate-y":U()}],"rotate-z":[{"rotate-z":U()}],scale:[{scale:z()}],"scale-x":[{"scale-x":z()}],"scale-y":[{"scale-y":z()}],"scale-z":[{"scale-z":z()}],"scale-3d":["scale-3d"],skew:[{skew:F()}],"skew-x":[{"skew-x":F()}],"skew-y":[{"skew-y":F()}],transform:[{transform:[we,pe,"","none","gpu","cpu"]}],"transform-origin":[{origin:v()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:L()}],"translate-x":[{"translate-x":L()}],"translate-y":[{"translate-y":L()}],"translate-z":[{"translate-z":L()}],"translate-none":["translate-none"],accent:[{accent:_()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:_()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",we,pe]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",we,pe]}],fill:[{fill:["none",..._()]}],"stroke-w":[{stroke:[ne,xe,he,ge]}],stroke:[{stroke:["none",..._()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function ze(...e){return Ue(S(e))}let Fe=!0;function Le(e,...t){Fe&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}function $e(e,...t){console.error(e,...t)}function Ve(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}async function We(e,t){try{const r=await e.json();return r?.message||r?.error||t}catch{return t}}async function je(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function Be(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await je(e);r=t.message||t.error||r}catch{r=function(e,t){const r={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${r})`)}(e,t).message}throw new Error(r)}try{return await je(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class Ge extends Error{constructor(e,t,r,n){super(e),this.code=t,this.context=r,this.originalError=n,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,Ge)}}const Ke=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(e){this.config={...this.config,...e},void 0!==e.enableConsoleLogging&&function(e){void 0!==e.enableLogging&&(Fe=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(Ve(e))return;const r=e instanceof Error?e:new Ge("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),n=r instanceof Ge?r:new Ge(r.message,"SDK_ERROR",t,r);if(this.config.enableConsoleLogging&&Le(`[SDK Error] ${t.component||"Unknown"}:`,{message:n.message,code:n.code,context:n.context,originalError:n.originalError,stack:n.stack}),this.config.onError)try{this.config.onError(n,t)}catch(e){$e("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(n,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...r)=>e(...r).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...r)=>{try{return e(...r)}catch(e){throw this.handleError(e,t),e}}}};function He(e,t={}){Ke.handleError(e,t)}function Ze(e,t={}){return!Ve(e)&&(Ke.handleError(e,t),!0)}class qe extends o{constructor(e){super(e),this.resetError=()=>{this.setState({hasError:!1,error:null})},this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){if(He(e,{component:"ErrorBoundary",action:"componentDidCatch",metadata:{componentStack:t.componentStack,errorBoundary:this.constructor.name}}),this.props.onError)try{this.props.onError(e,t)}catch(e){$e("[SDK ErrorBoundary] Error in onError callback:",e)}}componentDidUpdate(e){this.state.hasError&&!1!==this.props.resetOnPropsChange&&e.children!==this.props.children&&this.resetError()}render(){return this.state.hasError&&this.state.error?this.props.fallback?"function"==typeof this.props.fallback?this.props.fallback(this.state.error,this.resetError):this.props.fallback:e("div",{style:{padding:"1rem",border:"1px solid #ef4444",borderRadius:"0.5rem",backgroundColor:"#fef2f2",color:"#991b1b"},children:[t("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem",fontWeight:600},children:"Something went wrong"}),t("p",{style:{margin:"0 0 1rem 0",fontSize:"0.875rem"},children:this.state.error.message||"An unexpected error occurred"}),t("button",{onClick:this.resetError,style:{padding:"0.5rem 1rem",backgroundColor:"#ef4444",color:"white",border:"none",borderRadius:"0.25rem",cursor:"pointer",fontSize:"0.875rem"},children:"Try again"})]}):this.props.children}}const Je=()=>({type:"AUTHENTICATION_STARTED"}),Ye=()=>({type:"AUTHENTICATION_PROCESSING"}),Xe=()=>({type:"AUTHENTICATION_FAILED"}),Qe=e=>({type:"SET_SESSION",payload:e}),et=()=>({type:"REMOVE_SESSION"});function tt(e,t,r){const n=i(t),a=i(r),o=i(void 0),l=i(!1);return n.current=t,a.current=r,s(()=>{const t=n.current(e);if(l.current){if(a.current?a.current(o.current,t):Object.is(o.current,t))return o.current}return o.current=t,l.current=!0,t},[e])}function rt({name:e,initialState:r,reducer:n,initializer:o}){const i=l(null),d=l(null),u=l(null),f=a.memo(({children:e})=>{const[a,l]=c(n,r,o||(e=>e)),f=s(()=>({state:a,dispatch:l}),[a,l]);return t(u.Provider,{value:f,children:t(i.Provider,{value:a,children:t(d.Provider,{value:l,children:e})})})});f.displayName=`${e}Provider`;const m=t=>new Error(`use${e}${t} must be used within a ${e}Provider. Make sure SaaSOSProvider is wrapping your application.`),p=()=>{const e=a.useContext(i);if(null===e)throw m("State");return e};return{Provider:f,useContext:()=>{const e=a.useContext(u);if(!e)throw m("Context");return e},useState:p,useDispatch:()=>{const e=a.useContext(d);if(null===e)throw m("Dispatch");return e},useSelector:(e,t)=>{const r=e||(e=>e);return tt(p(),r,t)}}}var nt;function at(e){return{isAuthenticated:e===nt.authenticated,isLoading:e===nt.loading||e===nt.redirecting||e===nt.authenticating,isRedirecting:e===nt.redirecting}}function ot(e,t,r){return{...e,[t]:r}}function it(e,t){return{...e,...t}}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(nt||(nt={}));const st=()=>({session:null,status:nt.loading}),{Provider:lt,useState:ct,useDispatch:dt}=rt({name:"Auth",initialState:st(),reducer:(e,t)=>{switch(t.type){case"AUTHENTICATION_STARTED":return ot(e,"status",nt.redirecting);case"AUTHENTICATION_PROCESSING":return ot(e,"status",nt.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return it(e,{session:null,status:nt.unauthenticated});case"SET_SESSION":return it(e,{session:t.payload,status:nt.authenticated});default:return e}},initializer:st}),ut=lt,ft=ct,mt=dt,pt=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),ht=e=>({type:"SET_SETTINGS",payload:e});var gt;function bt(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}!function(e){e.V1="v1"}(gt||(gt={}));const yt=()=>({serverUrl:"",version:gt.V1,orgId:"",settings:null}),{Provider:vt,useState:wt,useDispatch:xt}=rt({name:"OS",initialState:yt(),reducer:(e,t)=>{switch(t.type){case"SET_SAAS_OS_CONFIG":return it(e,t.payload);case"REMOVE_SAAS_OS_CONFIG":return yt();case"SET_SETTINGS":return ot(e,"settings",t.payload);default:return e}}}),St=vt,kt=wt,Nt=xt,Ct=e=>({type:"SET_WORKSPACES",payload:e}),Et=e=>({type:"ADD_WORKSPACE",payload:e}),At=e=>({type:"UPDATE_WORKSPACE",payload:e}),_t=e=>({type:"REMOVE_WORKSPACE",payload:e}),Tt=e=>({type:"SET_ALL_FEATURES",payload:e}),Pt=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),Rt=()=>({type:"RESET_CURRENT_WORKSPACE"}),It=e=>({type:"SET_IS_INITIALIZED",payload:e}),Ot=e=>({type:"SET_LOADING",payload:e}),Dt=e=>({type:"SET_ERROR",payload:e}),Mt=e=>({type:"SET_REFRESHING",payload:e}),Ut=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:zt,useState:Ft,useDispatch:Lt}=rt({name:"Workspace",initialState:{workspaces:[],loading:!1,error:null,currentWorkspace:null,refreshing:!1,switchingToId:null,isInitialized:!1,allFeatures:[]},reducer:(e,t)=>{switch(t.type){case"SET_WORKSPACES":return ot(e,"workspaces",t.payload);case"ADD_WORKSPACE":return ot(e,"workspaces",[...e.workspaces,t.payload]);case"UPDATE_WORKSPACE":return ot(e,"workspaces",e.workspaces.map(e=>e._id===t.payload._id?t.payload:e));case"REMOVE_WORKSPACE":return ot(e,"workspaces",e.workspaces.filter(e=>e._id!==t.payload));case"SET_ALL_FEATURES":return ot(e,"allFeatures",t.payload);case"SET_CURRENT_WORKSPACE":return ot(e,"currentWorkspace",t.payload);case"RESET_CURRENT_WORKSPACE":return ot(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return ot(e,"isInitialized",t.payload);case"SET_LOADING":return ot(e,"loading",t.payload);case"SET_ERROR":return ot(e,"error",t.payload);case"SET_REFRESHING":return ot(e,"refreshing",t.payload);case"SET_SWITCHING_TO_ID":return ot(e,"switchingToId",t.payload);default:return e}}}),$t=zt,Vt=Ft,Wt=Lt,jt=a.memo(({children:e})=>t(St,{children:t(ut,{children:t($t,{children:e})})}));function Bt(e,t){const r=e.pricingVariants;if(!r?.length)return null;const n=t.toLowerCase();return r.find(e=>e.currency?.toLowerCase()===n)??null}function Gt(e,t,r){const n=Bt(e,t);if(!n?.basePricing)return null;const a=n.basePricing[r];return null!=a?a:null}function Kt(e,t,r,n){const a=Bt(e,t),o=a?.quotaOverages?.[r];if(o)return o[n]}function Ht(e,t,r,n){const a=e.quotas?.[r];if(null==a)return null;const o=a[n];if(!o)return null;const i=Kt(e,t,r,n);return{included:o.included,...void 0!==o.unitSize&&{unitSize:o.unitSize},...void 0!==i&&{overage:i}}}function Zt(e,t){if(!e)return null;for(const r of t){const t=r.pricingVariants;if(t?.length)for(const r of t){const t=r.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:r.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:r.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:r.currency}}}}return null}function qt(e,t){const r=Bt(e,t);return r?.seatPricing?.enabled?r.seatPricing:null}function Jt(e,t,r){const n=qt(e,t);return n?.perSeat?n.perSeat[r]??null:null}function Yt(e){const{planVersion:t,currency:r="usd",settingsMaxUsers:n}=e;if(t){const e=qt(t,r);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=n&&n>0?{maxUsers:n,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function Xt(e){const{memberCount:t,maxUsersConfig:r,hasSubscription:n=!0,requireSubscription:a=!1}=e;if(a&&!n)return{canInvite:!1,blockReason:"no_subscription",blockMessage:"A subscription is required to invite members."};const{maxUsers:o,source:i}=r;if(o<=0)return{canInvite:!0,blockReason:null,blockMessage:null};if(t>=o){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[i]??"seat_limit_reached",blockMessage:{seat_pricing:`Your plan allows up to ${o} members. Upgrade for more seats.`,settings:`This workspace allows up to ${o} members.`}[i]??`Member limit of ${o} reached.`}}return{canInvite:!0,blockReason:null,blockMessage:null}}jt.displayName="SDKContextProvider";const Qt=new Set;function er(){Qt.forEach(e=>e())}const tr=new class{constructor(){this.callbacks=null}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,t){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,t)}catch(t){He(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit("user:created",{user:e})}async emitUserUpdated(e,t){await this.emit("user:updated",{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit("workspace:changed",{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit("workspace:updated",{workspace:e})}async emitWorkspaceUserAdded(e,t,r){await this.emit("workspace:user-added",{userId:e,workspace:t,role:r})}async emitWorkspaceUserRemoved(e,t,r){await this.emit("workspace:user-removed",{userId:e,workspace:t,role:r})}async emitWorkspaceUserRoleChanged(e,t,r,n){await this.emit("workspace:user-role-changed",{userId:e,workspace:t,previousRole:r,newRole:n})}async emitWorkspaceCreated(e){await this.emit("workspace:created",{workspace:e})}async emitWorkspaceDeleted(e){await this.emit("workspace:deleted",{workspace:e})}};function rr(e,t,r){d(()=>{const t=new AbortController;return e(t.signal).catch(e=>{Ve(e)||(r?.onError?r.onError(e):He(e,{component:"useAsyncEffect",action:"effect",metadata:{note:"Unhandled rejection - consider passing onError"}}))}),()=>t.abort()},t)}function nr(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return He(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function ar(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){He(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}function or(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){He(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}const ir="saas-session-id",sr="code";function lr(e){ar(ir,e)}function cr(){return function(){if("undefined"==typeof window)return null;try{return nr(ir)}catch(e){return He(e,{component:"auth-utils",action:"getSessionId",metadata:{key:ir}}),null}}()}function dr(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(sr)}catch(e){return He(e,{component:"auth-utils",action:"getTokenFromUrl",metadata:{param:sr}}),null}}const ur="SDK is not ready (missing serverUrl, version, or orgId)";class fr{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(ur);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(ur)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=cr(),t={};return e&&(t["x-session-id"]=e),t}()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}async executeFetch(e,t){const r=this.url(e),n=(t.method??"GET").toUpperCase(),a=this.buildHeaders(t),o={...t,headers:a};let i;if(this._timeout>0){const e=new AbortController;i=setTimeout(()=>e.abort(),this._timeout),o.signal=t.signal?AbortSignal.any([t.signal,e.signal]):e.signal}const s=async t=>{try{const e=this._fetch.bind(globalThis),a=await e(r,o);if(this._debug&&console.log(`[BuildBase] ${n} ${r} → ${a.status}`),a.status>=500&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),s(t+1)}return a}catch(r){if(r instanceof Error&&"AbortError"===r.name){if(void 0!==i){const t=new Error(`Request timeout after ${this._timeout}ms: ${n} ${e}`);throw this._onError?.(t,{method:n,path:e}),t}throw r}if(t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),s(t+1)}throw r instanceof Error&&this._onError?.(r,{method:n,path:e}),r}};try{return await s(0)}finally{void 0!==i&&clearTimeout(i)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const n=await this.executeFetch(e,t);return await Be(n,r)}catch(r){throw r instanceof Error&&this._onError?.(r,{method:(t.method??"GET").toUpperCase(),path:e}),r}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}}class mr extends fr{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}function pr(){return qr(e=>e.os)}let hr=null;function gr(){const e=Jr(),t=pr(),{serverUrl:r,version:n,orgId:a,settings:o}=t,i=s(()=>bt(t)?new mr({serverUrl:r,version:n,orgId:a}):null,[r,n,a]),l=u(async t=>i?hr||(hr=(async()=>{try{const r=await i.getSettings(t);return e.os(ht(r)),r}catch(e){return Ze(e,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:r,version:n,orgId:a}}),null}finally{hr=null}})(),hr):null,[i,e,r,n,a]);return rr(async e=>{o||bt(t)&&await l(e)},[r,n,a],{onError:e=>Ze(e,{component:"useSaaSSettings",action:"fetchSettings",metadata:{serverUrl:r,version:n,orgId:a}})}),s(()=>({settings:o,getSettings:l}),[o,l])}class br extends fr{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(){return this.fetchJson("workspaces",{},"Failed to fetch workspaces")}async createWorkspace(e){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e)},"Failed to create workspace")}async updateWorkspace(e,t){return this.fetchJson(`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,r){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r)},"Failed to update user")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,t,r){return this.fetchJson(`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(`workspaces/${e}`,{},"Failed to fetch workspace")}async getProfile(){return this.fetchJson("profile",{},"Failed to fetch profile")}async updateUserProfile(e){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e)},"Failed to update user profile")}async getCurrentSubscription(e){const t=await this.fetchResponse(`workspaces/${e}/subscription`);if(!t.ok){let e="Failed to fetch subscription";try{e=(await t.json()).message||e}catch{e=404===t.status?"Workspace not found or no subscription available":401===t.status?"Unauthorized - Please check your session":`Failed to fetch subscription (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch subscription");return r.data||r}return r}async getPlanGroup(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/plan-group`);if(!t.ok){let e="Failed to fetch plan group";try{e=(await t.json()).message||e}catch{e=404===t.status?"No plan group found for this workspace":401===t.status?"Unauthorized - Please check your session":`Failed to fetch plan group (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch plan group");return r.data||r}return r}async getPlanGroupByVersion(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/plan-group?groupVersionId=${t}`);if(!r.ok){let e="Failed to fetch plan group version";try{e=(await r.json()).message||e}catch{e=404===r.status?"Plan group version not found":401===r.status?"Unauthorized - Please check your session":`Failed to fetch plan group version (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to fetch plan group version");return n.data||n}return n}async getPlanGroupVersions(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/plan-group/versions`);if(!t.ok){let e="Failed to fetch plan group versions";try{e=(await t.json()).message||e}catch{e=404===t.status?"No plan group versions found":401===t.status?"Unauthorized - Please check your session":`Failed to fetch plan group versions (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch plan group versions");return r.data||r}return r}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const t=await this.fetchResponse(`${this.orgId}/plans/${encodeURIComponent(e)}`);if(!t.ok){let r="Failed to fetch plans";try{r=(await t.json()).message||r}catch{r=404===t.status?`Plans "${e}" not found`:`Failed to fetch plans (${t.status}: ${t.statusText})`}throw new Error(r)}const r=await t.json();if(void 0!==r.success&&!r.success)throw new Error(r.message||"Failed to fetch plans");return r.data??r}async getPlanGroupVersion(e){const t=await this.fetchResponse(`plan-group-versions/${e}`);if(!t.ok){let e="Failed to fetch plan group version";try{e=(await t.json()).message||e}catch{e=404===t.status?"Plan group version not found":401===t.status?"Unauthorized - Please check your session":`Failed to fetch plan group version (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch plan group version");return r.data||r}return r}async createCheckoutSession(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});if(!r.ok){let e="Failed to create checkout session";try{e=(await r.json()).message||e}catch{e=`Failed to create checkout session (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to create checkout session");return n.data||n}return n}async updateSubscription(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});if(!r.ok){let e="Failed to update subscription";try{e=(await r.json()).message||e}catch{e=`Failed to update subscription (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to update subscription");return n.data?.checkoutUrl||n.checkoutUrl,n.data||n}return n.checkoutUrl,n}async createBillingPortalSession(e,t){return this.fetchJson(`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,r){const n=new URLSearchParams;n.append("limit",t.toString()),r&&n.append("starting_after",r);const a=await this.fetchResponse(`workspaces/${e}/subscription/invoices?${n.toString()}`,{});if(!a.ok){let e="Failed to fetch invoices";try{e=(await a.json()).message||e}catch{e=404===a.status?"Workspace not found or no invoices available":401===a.status?"Unauthorized - Please check your session":`Failed to fetch invoices (${a.status}: ${a.statusText})`}throw new Error(e)}const o=await a.json();if(void 0!==o.success){if(!o.success)throw new Error(o.message||"Failed to fetch invoices");return o}return o}async getInvoice(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/invoices/${t}`,{});if(!r.ok){let e="Failed to fetch invoice";try{e=(await r.json()).message||e}catch{e=404===r.status?"Invoice not found":401===r.status?"Unauthorized - Please check your session":`Failed to fetch invoice (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to fetch invoice");return n}return n}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});if(!t.ok){let e="Failed to cancel subscription";try{e=(await t.json()).message||e}catch{e=404===t.status?"Subscription not found":401===t.status?"Unauthorized - Please check your session":`Failed to cancel subscription (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to cancel subscription");return r.data||r}return r}async resumeSubscription(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/resume`,{method:"POST"});if(!t.ok){let e="Failed to resume subscription";try{e=(await t.json()).message||e}catch{e=404===t.status?"Subscription not found":401===t.status?"Unauthorized - Please check your session":`Failed to resume subscription (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to resume subscription");return r.data||r}return r}async recordUsage(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});if(!r.ok){let e="Failed to record usage";try{e=(await r.json()).message||e}catch{e=`Failed to record usage (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to record usage");return n.data||n}return n}async getQuotaUsageStatus(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/usage/status?quotaSlug=${encodeURIComponent(t)}`);if(!r.ok){let e="Failed to fetch quota usage status";try{e=(await r.json()).message||e}catch{e=404===r.status?"Workspace not found or no subscription available":401===r.status?"Unauthorized - Please check your session":`Failed to fetch quota usage status (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to fetch quota usage status");return n.data||n}return n}async getAllQuotaUsage(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/usage/all`);if(!t.ok){let e="Failed to fetch all quota usage";try{e=(await t.json()).message||e}catch{e=404===t.status?"Workspace not found or no subscription available":401===t.status?"Unauthorized - Please check your session":`Failed to fetch all quota usage (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch all quota usage");return r.data||r}return r}async getUsageLogs(e,t){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const n=r.toString(),a=`workspaces/${e}/subscription/usage/logs${n?`?${n}`:""}`,o=await this.fetchResponse(a);if(!o.ok){let e="Failed to fetch usage logs";try{e=(await o.json()).message||e}catch{e=404===o.status?"Workspace not found":401===o.status?"Unauthorized - Please check your session":`Failed to fetch usage logs (${o.status}: ${o.statusText})`}throw new Error(e)}const i=await o.json();if(void 0!==i.success){if(!i.success)throw new Error(i.message||"Failed to fetch usage logs");return i.data||i}return i}}const yr="saas-workspace-current",vr=e=>{e?ar(yr,e._id):or(yr)},wr=()=>nr(yr),xr=()=>{or(yr)},Sr=(e,t)=>!!e&&t.some(t=>t._id===e);function kr(e,t){if(!t)return!1;const r=(n=e.createdBy)?"string"==typeof n?n:"object"==typeof n&&"_id"in n&&"string"==typeof n._id?n._id:null:null;var n;return null!==r&&r===t}function Nr(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const r=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return r&&"object"==typeof r&&"role"in r&&"string"==typeof r.role?r.role:null}function Cr(){const e=pr(),t=function(e){return s(()=>new br(e),[e.serverUrl,e.version,e.orgId])}(e);return s(()=>({os:e,api:t}),[e,t])}const Er=()=>{const e=Jr(),{os:t,api:r}=Cr(),{settings:n}=gr(),o=qr(e=>e.workspaces),i=qr(e=>e.auth.session?.user),s=u((t,r)=>{if((!(t._id===o.currentWorkspace?._id)||r?.forceEmit)&&t){const r=o.currentWorkspace;vr(t),e.workspaces(Pt(t)),tr.emitWorkspaceChanged(t,r).catch(e=>{He(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceChanged",metadata:{workspaceId:t._id}})})}},[o.currentWorkspace,e]),l=u(async(r,n)=>{const a=++p.current;e.workspaces(Ut(r._id));try{const e=t.auth?.callbacks?.onWorkspaceChange;if(e){const t=Nr(r,i?.id);try{await e({workspace:r,user:i??null,role:t})}catch(e){throw He(e,{component:"useSaaSWorkspaces",action:"onWorkspaceChange",metadata:{workspaceId:r._id}}),e}if(a!==p.current)return}s(r,n)}finally{a===p.current&&e.workspaces(Ut(null))}},[e,t.auth?.callbacks?.onWorkspaceChange,s,i]);d(()=>{if(!o.isInitialized){const t=wr();if(e.workspaces(It(!0)),t){const e=o.workspaces.find(e=>e._id===t);e&&l(e,{forceEmit:!0}).catch(()=>{})}}},[o.isInitialized,o.workspaces,o.currentWorkspace,e,l]);const c=u(()=>{xr(),e.workspaces(Rt())},[e]),f=a.useRef(!1),m=a.useRef(!1),p=a.useRef(0),h=u(async()=>{if(!o.loading&&!f.current){f.current=!0,e.workspaces(Ot(!0)),e.workspaces(Dt(null));try{const t=await r.getWorkspaces();if(e.workspaces(Ct(t)),t.length>0){const e=wr();if(e&&Sr(e,t)){const r=t.find(t=>t._id===e);if(r)try{await l(r,{forceEmit:!0})}catch{}}else{const e=t[0];try{await l(e,{forceEmit:!0})}catch{}}}}catch(t){e.workspaces(Dt(t instanceof Error?t.message:"Failed to fetch workspaces"))}finally{e.workspaces(Ot(!1)),f.current=!1}}},[r,o.loading,e,l]),g=u(async()=>{if(!o.refreshing&&!f.current){f.current=!0,e.workspaces(Mt(!0));try{const t=await r.getWorkspaces();e.workspaces(Ct(t))}catch(e){}finally{e.workspaces(Mt(!1)),f.current=!1}}},[r,o.refreshing,e]),b=u(async(t,n)=>{const a=await r.createWorkspace({name:t,image:n});e.workspaces(Et(a)),tr.emitWorkspaceCreated(a).catch(e=>{He(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceCreated",metadata:{workspaceId:a._id}})})},[r,e]),y=u(async(t,n)=>{const a=await r.updateWorkspace(t._id,n);e.workspaces(At(a)),tr.emitWorkspaceUpdated(a).catch(e=>{He(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceUpdated",metadata:{workspaceId:a._id}})})},[r,e]),v=u(async()=>{if(m.current)return o.allFeatures.length>0?o.allFeatures:null;if(o.allFeatures.length>0)return o.allFeatures;m.current=!0;try{const t=await r.getFeatures();return e.workspaces(Tt(t)),t}catch(e){return He(e,{component:"useSaaSWorkspaces",action:"getFeatures"}),null}finally{m.current=!1}},[r,e,o.allFeatures]),w=u(async(e,t,n)=>await r.updateFeature(e,t,n),[r]);d(()=>{if(!o.currentWorkspace?._id||0===o.workspaces.length)return;const t=o.currentWorkspace._id,r=o.workspaces.find(e=>e._id===t);if(r)r!==o.currentWorkspace&&(vr(r),e.workspaces(Pt(r)));else if(o.workspaces.length>0){const e=o.workspaces[0];e._id!==t&&l(e).catch(()=>{})}},[o.workspaces,o.currentWorkspace,e,l]);const x=u(async e=>await r.getWorkspaceUsers(e),[r]),S=u(async(e,t,a)=>{const i=o.workspaces.find(t=>t._id===e);if(i){const e=Yt({settingsMaxUsers:n?.workspace?.maxWorkspaceUsers}),t=Xt({memberCount:i.users?.length??0,maxUsersConfig:e});if(!t.canInvite)throw new Error(t.blockMessage||"Member limit reached")}const s=await r.addUser(e,{email:t,role:a});return i&&tr.emitWorkspaceUserAdded(s.userId,i,a).catch(t=>{He(t,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserAdded",metadata:{workspaceId:e,userId:s.userId,role:a}})}),g().catch(()=>{}),er(),s},[r,o.workspaces,g,n]),k=u(async(e,t)=>{const n=o.workspaces.find(t=>t._id===e);if(n&&kr(n,t))throw new Error("Cannot remove the workspace owner");const a=(await r.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t),i=await r.removeUser(e,t);if(n&&a){const t=a.role;tr.emitWorkspaceUserRemoved(i.userId,n,t).catch(r=>{He(r,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserRemoved",metadata:{workspaceId:e,userId:i.userId,role:t}})})}return g().catch(()=>{}),er(),i},[r,o.workspaces,g]),N=u(async(e,t,n)=>{if(n.role){const r=o.workspaces.find(t=>t._id===e);if(r&&kr(r,t))throw new Error("Cannot change the role of the workspace owner")}let a;if(n.role){const n=(await r.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t);a=n?.role}const i=await r.updateUser(e,t,n);return n.role&&a&&a!==n.role&&tr.emitWorkspaceUserRoleChanged(i.userId,i.workspace,a,n.role).catch(r=>{He(r,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserRoleChanged",metadata:{workspaceId:e,userId:t,previousRole:a,newRole:n.role}})}),i},[r,o.workspaces]),C=u(async e=>{const t=await r.getProfile().catch(()=>null),n=await r.updateUserProfile(e);return tr.emitUserUpdated(n,t||void 0).catch(e=>{He(e,{component:"useSaaSWorkspaces",action:"emitUserUpdated",metadata:{userId:n._id}})}),n},[r]),E=u(async()=>await r.getProfile(),[r]),A=u(async e=>await r.getWorkspace(e),[r]),_=u(async t=>{if(!i)throw new Error("User must be authenticated to delete a workspace");const n=o.workspaces.find(e=>e._id===t);if(!n)throw new Error("Workspace not found");if(!kr(n,i.id))throw new Error("Only the workspace creator can delete the workspace");const a=await r.deleteWorkspace(t);return e.workspaces(_t(t)),o.currentWorkspace?._id===t&&(xr(),e.workspaces(Rt())),n&&tr.emitWorkspaceDeleted(n).catch(e=>{He(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceDeleted",metadata:{workspaceId:t}})}),a},[r,o.workspaces,o.currentWorkspace,e,i]);return{workspaces:o.workspaces,loading:o.loading,error:o.error,fetchWorkspaces:h,refreshWorkspaces:g,refreshing:o.refreshing,currentWorkspace:o.currentWorkspace,setCurrentWorkspace:s,switchToWorkspace:l,resetCurrentWorkspace:c,createWorkspace:b,allFeatures:o.allFeatures,getFeatures:v,updateFeature:w,getWorkspace:A,updateWorkspace:y,getUsers:x,addUser:S,removeUser:k,updateUser:N,getProfile:E,updateUserProfile:C,deleteWorkspace:_,switching:null!==o.switchingToId,switchingToId:o.switchingToId}},Ar=new Set;function _r(){Ar.forEach(e=>e())}const Tr=e=>{const{os:t,api:r}=Cr(),n=bt(t),[a,o]=f(null),[i,s]=f(!1),[l,c]=f(null),m=u(async()=>{if(e&&n){s(!0),c(null);try{const t=await r.getPublicPlans(e);o(t)}catch(t){const r=t instanceof Error?t.message:"Failed to fetch plans";c(r),He(t,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{s(!1)}}else o(null)},[r,e,n]);d(()=>{m()},[m]);const p=e&&!n||i;return{items:a?.items??[],plans:a?.plans??[],notes:a?.notes,loading:p,error:l,refetch:m}},Pr=e=>{const{api:t}=Cr(),[r,n]=f(null),[a,o]=f(!1),[i,s]=f(null),l=u(async()=>{if(e){o(!0),s(null);try{const r=await t.getPlanGroupVersion(e);n(r)}catch(t){const r=t instanceof Error?t.message:"Failed to fetch plan group version";s(r),He(t,{component:"usePublicPlanGroupVersion",action:"fetchVersion",metadata:{groupVersionId:e}})}finally{o(!1)}}else n(null)},[t,e]);return d(()=>{l()},[l]),{planGroupVersion:r,loading:a,error:i,refetch:l}},Rr=e=>{const{api:t}=Cr(),[r,n]=f(null),[a,o]=f(!1),[i,s]=f(null),l=u(async()=>{if(e){o(!0),s(null);try{const r=await t.getCurrentSubscription(e);n(r)}catch(t){const r=t instanceof Error?t.message:"Failed to fetch subscription";s(r),He(t,{component:"useSubscription",action:"fetchSubscription",metadata:{workspaceId:e}})}finally{o(!1)}}else n(null)},[t,e]);return d(()=>{l()},[l]),{subscription:r,loading:a,error:i,refetch:l}},Ir=(e,t)=>{const{api:r}=Cr(),[n,a]=f(null),[o,i]=f(!1),[s,l]=f(null),c=u(async()=>{if(e){i(!0),l(null);try{const n=t?await r.getPlanGroupByVersion(e,t):await r.getPlanGroup(e);a(n)}catch(r){const n=r instanceof Error?r.message:"Failed to fetch plan group";l(n),He(r,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:t}})}finally{i(!1)}}else a(null)},[r,e,t]);return d(()=>{c()},[c]),{planGroup:n,loading:o,error:s,refetch:c}},Or=e=>{const{api:t}=Cr(),[r,n]=f(null),[a,o]=f(!1),[i,s]=f(null),l=u(async()=>{if(e){o(!0),s(null);try{const r=await t.getPlanGroupVersions(e);n(r)}catch(t){const r=t instanceof Error?t.message:"Failed to fetch plan group versions";s(r),He(t,{component:"usePlanGroupVersions",action:"fetchVersions",metadata:{workspaceId:e}})}finally{o(!1)}}else n(null)},[t,e]);return d(()=>{l()},[l]),{versions:r,loading:a,error:i,refetch:l}},Dr=e=>{const{api:t}=Cr(),[r,n]=f(!1),[a,o]=f(null);return{createCheckoutSession:u(async r=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const n=await t.createCheckoutSession(e,r);return"trial_started"===n.type&&(er(),_r()),n}catch(t){const n=t instanceof Error?t.message:"Failed to create checkout session";throw o(n),He(t,{component:"useCreateCheckoutSession",action:"createCheckoutSession",metadata:{workspaceId:e,request:r}}),t}finally{n(!1)}},[t,e]),loading:r,error:a}},Mr=e=>{const{api:t}=Cr(),[r,n]=f(!1),[a,o]=f(null),i=u(async(r,a)=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const n={planVersionId:r,...a?.billingInterval&&{billingInterval:a.billingInterval},...a?.successUrl&&{successUrl:a.successUrl},...a?.cancelUrl&&{cancelUrl:a.cancelUrl}},o=await t.updateSubscription(e,n);return er(),o}catch(t){const n=t instanceof Error?t.message:"Failed to update subscription";throw o(n),He(t,{component:"useUpdateSubscription",action:"updateSubscription",metadata:{workspaceId:e,planVersionId:r,options:a}}),t}finally{n(!1)}},[t,e]);return{updateSubscription:i,loading:r,error:a}},Ur=(e,t)=>{const r=Rr(e),n=Ir(e,t),a=Mr(e),o=u(async()=>{await Promise.all([r.refetch(),n.refetch()])},[r.refetch,n.refetch]);return{subscription:r.subscription,planGroup:n.planGroup,loading:r.loading||n.loading||a.loading,error:r.error||n.error||a.error,updateSubscription:a.updateSubscription,refetch:o}},zr=(e,t=10,r)=>{const{api:n}=Cr(),[a,o]=f([]),[i,s]=f(!1),[l,c]=f(!1),[m,p]=f(null),h=u(async()=>{if(!e)return o([]),void s(!1);c(!0),p(null);try{const a=await n.listInvoices(e,t,r);o(a.invoices||[]),s(a.has_more||!1)}catch(n){const a=n instanceof Error?n.message:"Failed to fetch invoices";p(a),He(n,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:t,startingAfter:r}})}finally{c(!1)}},[n,e,t,r]);return d(()=>{h()},[h]),{invoices:a,hasMore:i,loading:l,error:m,refetch:h}},Fr=e=>{const{api:t}=Cr(),[r,n]=f(!1),[a,o]=f(null);return{openBillingPortal:u(async r=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const n=r||window.location.href,a=await t.createBillingPortalSession(e,n);return a.url&&window.open(a.url,"_blank","noopener,noreferrer"),a}catch(t){const r=t instanceof Error?t.message:"Failed to open billing portal";throw o(r),He(t,{component:"useBillingPortal",action:"openBillingPortal",metadata:{workspaceId:e}}),t}finally{n(!1)}},[e,t]),loading:r,error:a}},Lr=(e,t)=>{const{api:r}=Cr(),[n,a]=f(null),[o,i]=f(!1),[s,l]=f(null),c=u(async()=>{if(e&&t){i(!0),l(null);try{const n=await r.getInvoice(e,t);a(n.invoice)}catch(r){const n=r instanceof Error?r.message:"Failed to fetch invoice";l(n),He(r,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:t}})}finally{i(!1)}}else a(null)},[r,e,t]);return d(()=>{c()},[c]),{invoice:n,loading:o,error:s,refetch:c}},$r=e=>{const{api:t}=Cr(),[r,n]=f(!1),[a,o]=f(null);return{cancelSubscription:u(async()=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const r=await t.cancelSubscriptionAtPeriodEnd(e);return er(),r}catch(t){const r=t instanceof Error?t.message:"Failed to cancel subscription";throw o(r),He(t,{component:"useCancelSubscription",action:"cancelSubscription",metadata:{workspaceId:e}}),t}finally{n(!1)}},[t,e]),loading:r,error:a}},Vr=e=>{const{api:t}=Cr(),[r,n]=f(!1),[a,o]=f(null);return{resumeSubscription:u(async()=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const r=await t.resumeSubscription(e);return er(),r}catch(t){const r=t instanceof Error?t.message:"Failed to resume subscription";throw o(r),He(t,{component:"useResumeSubscription",action:"resumeSubscription",metadata:{workspaceId:e}}),t}finally{n(!1)}},[t,e]),loading:r,error:a}},Wr=e=>{const{api:t}=Cr(),[r,n]=f(!1),[a,o]=f(null);return{recordUsage:u(async r=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const n=await t.recordUsage(e,r);return _r(),n}catch(t){const n=t instanceof Error?t.message:"Failed to record usage";throw o(n),He(t,{component:"useRecordUsage",action:"recordUsage",metadata:{workspaceId:e,request:r}}),t}finally{n(!1)}},[t,e]),loading:r,error:a}},jr=(e,t)=>{const{api:r}=Cr(),[n,a]=f(null),[o,i]=f(!1),[s,l]=f(null),c=u(async()=>{if(e&&t){i(!0),l(null);try{const n=await r.getQuotaUsageStatus(e,t);a(n)}catch(r){const n=r instanceof Error?r.message:"Failed to fetch quota usage status";l(n),He(r,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:t}})}finally{i(!1)}}else a(null)},[r,e,t]);return d(()=>{c()},[c]),{status:n,loading:o,error:s,refetch:c}},Br=e=>{const{api:t}=Cr(),[r,n]=f(null),[a,o]=f(!1),[i,s]=f(null),l=u(async()=>{if(e){o(!0),s(null);try{const r=await t.getAllQuotaUsage(e);n(r.quotas)}catch(t){const r=t instanceof Error?t.message:"Failed to fetch all quota usage";s(r),He(t,{component:"useAllQuotaUsage",action:"fetchAllUsage",metadata:{workspaceId:e}})}finally{o(!1)}}else n(null)},[t,e]);return d(()=>{l()},[l]),{quotas:r,loading:a,error:i,refetch:l}},Gr=(e,t,r)=>{const{api:n}=Cr(),[a,o]=f([]),[i,s]=f(0),[l,c]=f(0),[m,p]=f(1),[h,g]=f(!1),[b,y]=f(!1),[v,w]=f(!1),[x,S]=f(null),k=r?.from,N=r?.to,C=r?.source,E=r?.page,A=r?.limit,_=u(async()=>{if(!e)return o([]),s(0),c(0),p(1),g(!1),void y(!1);w(!0),S(null);try{const r={...t&&{quotaSlug:t},...k&&{from:k},...N&&{to:N},...C&&{source:C},...E&&{page:E},...A&&{limit:A}},a=await n.getUsageLogs(e,r);o(a.docs||[]),s(a.totalDocs||0),c(a.totalPages||0),p(a.page||1),g(a.hasNextPage||!1),y(a.hasPrevPage||!1)}catch(r){const n=r instanceof Error?r.message:"Failed to fetch usage logs";S(n),He(r,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:t}})}finally{w(!1)}},[n,e,t,k,N,C,E,A]);return d(()=>{_()},[_]),{logs:a,totalDocs:i,totalPages:l,page:m,hasNextPage:h,hasPrevPage:b,loading:v,error:x,refetch:_}},Kr=l(null);Kr.displayName="SubscriptionContext";const Hr=a.memo(function({children:e}){const{currentWorkspace:r}=Er(),{subscription:n,loading:a,error:o,refetch:i}=Rr(r?._id);d(()=>{return e=i,Qt.add(e),()=>{Qt.delete(e)};var e},[i]);const l=s(()=>({response:n,loading:a,error:o,refetch:i}),[n,a,o,i]);return t(Kr.Provider,{value:l,children:e})});function Zr(){const e=m(Kr);if(null===e)throw new Error("useSubscriptionContext must be used within SubscriptionContextProvider. Make sure SubscriptionContextProvider is wrapping your application (or the tree that uses subscription gates).");return e}function qr(e,t){const r=kt(),n=ft(),a=Vt(),o=e||(e=>e);return tt(s(()=>({os:r,auth:n,workspaces:a}),[r,n,a]),o,t)}function Jr(){const e=mt(),t=Nt(),r=Wt();return s(()=>({auth:e,os:t,workspaces:r}),[e,t,r])}Hr.displayName="SubscriptionContextProvider";const Yr=l(null);Yr.displayName="QuotaUsageContext";const Xr=a.memo(function({children:e}){const{currentWorkspace:r}=Er(),{quotas:n,loading:a,error:o,refetch:i}=Br(r?._id);d(()=>{return e=i,Ar.add(e),()=>{Ar.delete(e)};var e},[i]);const l=s(()=>({quotas:n,loading:a,error:o,refetch:i}),[n,a,o,i]);return t(Yr.Provider,{value:l,children:e})});function Qr(){const e=m(Yr);if(null===e)throw new Error("useQuotaUsageContext must be used within QuotaUsageContextProvider. Make sure QuotaUsageContextProvider is wrapping your application (or the tree that uses quota gates).");return e}Xr.displayName="QuotaUsageContextProvider";class en extends fr{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let e="Failed to initiate authentication";try{e=(await r.json()).message||e}catch{e=`Failed to initiate authentication (${r.status}: ${r.statusText})`}throw new Error(e)}return r.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}}const tn=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:"profile"}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getState(){return{...this.currentState}}openWorkspaceSettings(e){this.currentState={open:!0,section:e||"profile"},this.notifyListeners()}closeSettings(){this.currentState={...this.currentState,open:!1},this.notifyListeners()}setSection(e){this.currentState={...this.currentState,section:e},this.notifyListeners()}notifyListeners(){this.listeners.forEach(e=>{e(this.currentState.open,this.currentState.section)})}};function rn(e,t,r){const n=e._id||e.id;if(!n||"string"!=typeof n)throw new Error("User data missing required ID field");if(!e.email||"string"!=typeof e.email)throw new Error("User data missing required email field");return{id:n,name:e.name||"",org:t,email:e.email,emailVerified:!0,clientId:r,role:e.role||"",image:e.image}}function nn(e,t){return{user:e,sessionId:t,expires:new Date(Date.now()+864e5).toISOString()}}function an(){return qr(e=>e.auth)}function on(){const e=Jr(),t=an(),r=pr(),{serverUrl:n,orgId:a,auth:o}=r,{resetCurrentWorkspace:i,currentWorkspace:l}=Er(),c=s(()=>new en({serverUrl:n,version:r.version}),[n,r.version]),d=u(async()=>{e.auth(Je());try{const t=await c.requestAuth({orgId:a,clientId:o?.clientId??"",redirect:{success:o?.redirectUrl||window.location.href,error:o?.redirectUrl||window.location.href}});if(!t.success)throw e.auth(Xe()),new Error(t.message||"Authentication failed");window.location.href=t.data.redirectUrl}catch(t){throw e.auth(Xe()),He(t,{component:"useSaaSAuth",action:"signIn"}),t}},[c,a,o,e]),f=u(async()=>{try{o?.callbacks?.onSignOut&&"function"==typeof o.callbacks.onSignOut&&await o.callbacks.onSignOut()}catch(e){He(e,{component:"useSaaSAuth",action:"signOut"})}finally{or(ir),e.auth(et()),i()}},[e,i,o?.callbacks?.onSignOut]),m=u(e=>{l?tn.openWorkspaceSettings(e):He(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),p=s(()=>at(t.status),[t.status]);return s(()=>({user:t.session?.user,session:t.session,status:t.status,...p,signIn:d,signOut:f,openWorkspaceSettings:m}),[t.session,t.status,p,d,f,m])}class sn extends fr{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}const ln=l(null);function cn(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r.charCodeAt(e);return n}const dn=a.memo(function({children:e,serviceWorkerPath:r="/push-sw.js",autoSubscribe:n=!1}){const a=pr(),{isAuthenticated:o}=on(),i="undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,l=s(()=>new sn({serverUrl:a.serverUrl,version:a.version,orgId:a.orgId}),[a.serverUrl,a.version,a.orgId]),[c,m]=f({permission:i?Notification.permission:"default",isSubscribed:!1,isSupported:i,loading:!1,error:null});d(()=>{o&&i&&async function(){try{const e=await navigator.serviceWorker.getRegistration(r);if(!e)return void m(e=>({...e,isSubscribed:!1}));const t=await e.pushManager.getSubscription();m(e=>({...e,isSubscribed:!!t,permission:Notification.permission}))}catch{m(e=>({...e,isSubscribed:!1}))}}()},[o,i]);const p=u(async()=>{if(!i)return!1;const e=await Notification.requestPermission();return m(t=>({...t,permission:e})),"granted"===e},[i]),h=u(async()=>{if(i&&o){m(e=>({...e,loading:!0,error:null}));try{if(!await p())return void m(e=>({...e,loading:!1,error:"Notification permission denied"}));const{publicKey:e}=await l.getVapidPublicKey(),t=await navigator.serviceWorker.register(r);await navigator.serviceWorker.ready;const n=(await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:cn(e)})).toJSON();await l.subscribe({endpoint:n.endpoint,keys:{p256dh:n.keys.p256dh,auth:n.keys.auth}},navigator.userAgent),m(e=>({...e,isSubscribed:!0,loading:!1}))}catch(e){const t=e instanceof Error?e.message:"Failed to subscribe to push notifications";m(e=>({...e,loading:!1,error:t})),He(e,{component:"PushNotificationProvider",action:"subscribe"})}}},[i,o,l,r,p]),g=u(async()=>{if(i){m(e=>({...e,loading:!0,error:null}));try{const e=await navigator.serviceWorker.getRegistration(r);if(e){const t=await e.pushManager.getSubscription();if(t){const e=t.endpoint;await t.unsubscribe(),await l.unsubscribe(e)}}m(e=>({...e,isSubscribed:!1,loading:!1}))}catch(e){const t=e instanceof Error?e.message:"Failed to unsubscribe";m(e=>({...e,loading:!1,error:t})),He(e,{component:"PushNotificationProvider",action:"unsubscribe"})}}},[i,l,r]),b=s(()=>({...c,requestPermission:p,subscribe:h,unsubscribe:g}),[c,p,h,g]);return t(ln.Provider,{value:b,children:e})});function un(){const e=m(ln);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e}let fn=!1,mn=null;const pn=a.memo(({children:e,callbacks:n})=>{const o=Jr(),i=an(),l=pr(),c=at(i.status).isAuthenticated,f=a.useRef(!1),m=a.useRef(null),p=s(()=>n,[n]),h=u(async e=>{try{if(p?.handleAuthentication){const{sessionId:t}=await p.handleAuthentication(e);if(!t||"string"!=typeof t||""===t.trim())throw new Error("Invalid sessionId received from authentication callback");const r=l;if(!bt(r))throw new Error("OS configuration is not available");const{serverUrl:n,version:a,orgId:i}=r,s=new en({serverUrl:n,version:a}),c=await s.getProfile(t),d=nn(rn(c,i,r.auth?.clientId||""),t);lr(d.sessionId),o.auth(Qe(d)),function(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.delete(sr),window.history.replaceState({},"",e.toString())}catch(e){He(e,{component:"auth-utils",action:"removeTokenFromUrl",metadata:{param:sr}})}}()}}catch(t){throw He(t,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),o.auth(Xe()),t}},[o,p,l]);return rr(async e=>{if("undefined"==typeof window)return;if(c)return;if(fn)return;if(mn)return;if(!bt(l))return;return dr()?void 0:p?.getSession?void(mn=(async()=>{let t=null;try{t=await p.getSession()}catch(e){He(e,{component:"AuthProviderWrapper",action:"getSession"})}if(!t)return fn=!0,void o.auth(Xe());try{const{orgId:r}=l,n=new en({serverUrl:l.serverUrl,version:l.version}),a=await n.getProfile(t,e),i=nn(rn(a,r,l.auth?.clientId||""),t);lr(i.sessionId),fn=!0,o.auth(Qe(i))}catch(e){if(!Ze(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}))return;fn=!0,o.auth(Xe())}finally{mn=null}})()):(fn=!0,void o.auth(Xe()))},[o,l]),d(()=>{const e=dr();if(!e)return;if(f.current||m.current===e)return;if(!bt(l))return;f.current=!0,m.current=e;let t=!1;return o.auth(Ye()),h(e).then(()=>{t||(m.current=null)}).catch(e=>{t||(He(e,{component:"AuthProviderWrapper",action:"handleAuthRedirectEffect",metadata:{hasCode:!0}}),m.current=null)}).finally(()=>{f.current=!1}),()=>{t=!0}},[h,l.serverUrl,l.version,l.orgId]),t(r,{children:e})});pn.displayName="AuthProviderWrapper";const hn=a.memo(({config:e,auth:n,children:o})=>{const i=Jr(),l=pr(),c=a.useMemo(()=>({clientId:n?.clientId||"",redirectUrl:n?.redirectUrl||"",callbacks:n?.callbacks}),[n?.clientId,n?.redirectUrl,n?.callbacks]);d(()=>{i.os(pt({...e,auth:c}))},[e,c,i]);const u=s(()=>bt(l)?new mr(l):null,[l.serverUrl,l.version,l.orgId]);return rr(async e=>{if(!u||l.settings)return;const t=await u.getSettings(e);i.os(ht(t))},[u,l.settings,i],{onError:e=>He(e,{component:"ContextConfigProvider",action:"fetchSettings",metadata:{serverUrl:l.serverUrl,version:l.version,orgId:l.orgId}})}),t(r,{children:o})});hn.displayName="ContextConfigProvider";const gn=l({container:null,setContainer:()=>{}}),bn=a.memo(({children:r})=>{const[n,o]=a.useState(null),i=a.useMemo(()=>({container:n,setContainer:o}),[n]),s=a.useMemo(()=>r,[r]);return e(gn.Provider,{value:i,children:[s,t("div",{ref:o,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});bn.displayName="PortalProvider";class yn extends fr{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});if(!t.ok)throw new Error(await We(t,"Failed to fetch user attributes"));const r=await t.json();return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});if(!t.ok)throw new Error(await We(t,"Failed to fetch user features"));const r=await t.json();return"object"==typeof r&&null!==r?r:{}}}const vn=a.createContext(void 0),wn=a.memo(({children:e})=>{const r=pr(),n=function(){const e=pr();return s(()=>new yn(e),[e.serverUrl,e.version])}(),{isAuthenticated:o}=on(),{serverUrl:i,version:l}=r,[c,d]=f({}),[m,p]=f({}),[h,g]=f(!1),[b,y]=f(null),v=u(async e=>{if(i&&l&&o)try{const t=await n.getAttributes(e);d(t)}catch(e){if(Ve(e))return;const t=e instanceof Error?e:new Error("Failed to fetch user attributes");y(t),He(e,{component:"UserProvider",action:"fetchAttributes"})}else d({})},[n,i,l,o]),w=u(async()=>{if(i&&l&&o){g(!0),y(null);try{await v()}finally{g(!1)}}},[i,l,o,v]),x=u(async e=>{g(!0),y(null);try{const t=await n.updateAttributes(e);return await v(),t}catch(t){const r=t instanceof Error?t:new Error("Failed to update user attributes");throw y(r),He(t,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),t}finally{g(!1)}},[n,v]),S=u(async(e,t)=>{g(!0),y(null);try{const r=await n.updateAttribute(e,t);return await v(),r}catch(r){const n=r instanceof Error?r:new Error("Failed to update user attribute");throw y(n),He(r,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:t}}),r}finally{g(!1)}},[n,v]),k=u(async e=>{if(i&&l&&o)try{const t=await n.getFeatures(e);p(t)}catch(e){if(Ve(e))return;const t=e instanceof Error?e:new Error("Failed to fetch user features");y(t),He(e,{component:"UserProvider",action:"fetchFeatures"})}else p({})},[n,i,l,o]),N=u(async()=>{if(i&&l&&o){g(!0),y(null);try{await k()}finally{g(!1)}}},[i,l,o,k]);rr(async e=>{if(!o||!i||!l)return d({}),void p({});g(!0),y(null);try{await Promise.all([v(e),k(e)])}finally{g(!1)}},[o,i,l,v,k],{onError:e=>He(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const C=a.useMemo(()=>({attributes:c,features:m,isLoading:h,error:b,updateAttributes:x,updateAttribute:S,refreshAttributes:w,refreshFeatures:N}),[c,m,h,b,x,S,w,N]);return t(vn.Provider,{value:C,children:e})});wn.displayName="UserProvider";const xn=h(()=>Promise.resolve().then(function(){return HS}).then(e=>({default:e.default}))),Sn=({children:n})=>{const{currentWorkspace:a}=Er(),[o,i]=f(!1),[s,l]=f("profile");return d(()=>{const e=tn.getState();i(e.open),l(e.section);return tn.subscribe((e,t)=>{i(e),l(t)})},[]),e(r,{children:[n,a&&o&&t(p,{fallback:null,children:t(xn,{workspace:a,open:o,onOpenChange:e=>{e||tn.closeSettings()},section:s,onSectionChange:e=>{tn.setSection(e)},showTrigger:!1})})]})},kn=(e,t,r)=>{if(t!==gt.V1)throw new Error(`Invalid version: "${t}". Only "${gt.V1}" is currently supported.`);if(!e||"string"!=typeof e)throw new Error("serverUrl is required and must be a string");if(!(e=>{try{return new URL(e),!0}catch{return!1}})(e))throw new Error(`Invalid serverUrl: "${e}". Must be a valid URL.`);if(!r||"string"!=typeof r)throw new Error("orgId is required and must be a string");if(!/^[0-9a-fA-F]{24}$/.test(r))throw new Error(`Invalid orgId: "${r}". Must be a valid MongoDB ObjectId (24 hexadecimal characters).`)},Nn=a.memo(({serverUrl:e,version:r,orgId:n,auth:o,children:i})=>{kn(e,r,n);const s=a.useMemo(()=>({serverUrl:e,version:r,orgId:n}),[e,r,n]),l=a.useMemo(()=>o?.callbacks,[o?.callbacks?.handleAuthentication,o?.callbacks?.onSignOut,o?.callbacks?.handleEvent,o?.callbacks?.onWorkspaceChange]),c=o?.callbacks?.handleEvent;return d(()=>(tr.setCallbacks(c?{handleEvent:c}:null),()=>{tr.setCallbacks(null)}),[c]),t(jt,{children:t(pn,{callbacks:l,children:t(bn,{children:t(hn,{config:s,auth:o,children:t(wn,{children:t(Hr,{children:t(Xr,{children:t(dn,{children:t(Sn,{children:i})})})})})})})})})});Nn.displayName="SaaSOSProviderInner";const Cn=({children:e,...r})=>t(qe,{children:t(Nn,{...r,children:e})});Cn.displayName="SaaSOSProvider";const En=e=>{const{children:t}=e,{status:r}=on();return r!==nt.authenticated?null:t},An=e=>{const{children:t}=e,{status:r}=on();return r!==nt.unauthenticated?null:t};En.displayName="WhenAuthenticated",An.displayName="WhenUnauthenticated";const _n=e=>{const{children:t,fallback:r,roles:n}=e,{user:a}=on();return n.includes(a?.role??"")?t:r||null},Tn=e=>{const{children:t,fallback:r,roles:n}=e,{user:a}=on(),{currentWorkspace:o}=Er(),i=o?.users.find(e=>e._id===a?.id);return i&&n.includes(i?.role??"")?t:r||null};function Pn(){const e=m(vn);if(void 0===e)throw new Error("useUserAttributes must be used within a UserProvider");return e}function Rn(){const e=m(vn);if(void 0===e)throw new Error("useUserFeatures must be used within a UserProvider");return{features:e.features,isLoading:e.isLoading,error:e.error,refreshFeatures:e.refreshFeatures,isFeatureEnabled:t=>Boolean(e.features[t])}}_n.displayName="WhenRoles",Tn.displayName="WhenWorkspaceRoles";const In=e=>{const{children:t,slug:r}=e,{currentWorkspace:n}=Er(),a=n?.features?.[r];return a?t:null},On=e=>{const{children:t,slug:r}=e,{currentWorkspace:n}=Er(),a=n?.features?.[r];return a?null:t},Dn=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:n}=Rn();return n(r)?t:null},Mn=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:n}=Rn();return n(r)?null:t};In.displayName="WhenWorkspaceFeatureEnabled",On.displayName="WhenWorkspaceFeatureDisabled",Dn.displayName="WhenUserFeatureEnabled",Mn.displayName="WhenUserFeatureDisabled";const Un=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{response:a,loading:o}=Zr();return o?r??null:a?.subscription?t:n??null},zn=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{response:a,loading:o}=Zr();return o?r??null:a?.subscription?n??null:t},Fn=e=>{const{children:t,plans:r,loadingComponent:n,fallbackComponent:a}=e,{response:o,loading:i}=Zr();if(i)return n??null;if(!o?.subscription)return a??null;const s=o.plan??o.subscription?.plan;if(!s)return a??null;const l=r.map(e=>e.trim().toLowerCase()),c=(s.slug??"").toLowerCase();return l.includes(c)?t:a??null},Ln=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{response:a,loading:o}=Zr();return o?r??null:"trialing"!==a?.subscription?.subscriptionStatus?n??null:t},$n=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{response:a,loading:o}=Zr();return o?r??null:"trialing"===a?.subscription?.subscriptionStatus?n??null:t},Vn=e=>{const{children:t,loadingComponent:r,fallbackComponent:n,daysThreshold:a=3}=e,{response:o,loading:i}=Zr();if(i)return r??null;const s=o?.subscription;if(!s||"trialing"!==s.subscriptionStatus)return n??null;const l=s.trialEnd||s.stripeCurrentPeriodEnd;if(!l)return n??null;const c=new Date(l);if(isNaN(c.getTime()))return n??null;return Math.max(0,Math.ceil((c.getTime()-Date.now())/864e5))>a?n??null:t};Un.displayName="WhenSubscription",zn.displayName="WhenNoSubscription",Fn.displayName="WhenSubscriptionToPlans",Ln.displayName="WhenTrialing",$n.displayName="WhenNotTrialing",Vn.displayName="WhenTrialEnding";const Wn=e=>{const{slug:t,children:r,loadingComponent:n,fallbackComponent:a}=e,{quotas:o,loading:i}=Qr();if(i)return n??null;const s=o?.[t];return s?s.available<=0?a??null:r:a??null},jn=e=>{const{slug:t,children:r,loadingComponent:n,fallbackComponent:a}=e,{quotas:o,loading:i}=Qr();if(i)return n??null;const s=o?.[t];return s?s.available>0?a??null:r:a??null},Bn=e=>{const{slug:t,children:r,loadingComponent:n,fallbackComponent:a}=e,{quotas:o,loading:i}=Qr();if(i)return n??null;const s=o?.[t];return s&&s.hasOverage?r:a??null},Gn=e=>{const{slug:t,threshold:r,children:n,loadingComponent:a,fallbackComponent:o}=e,{quotas:i,loading:s}=Qr();if(s)return a??null;const l=i?.[t];if(!l)return o??null;return(l.included>0?l.consumed/l.included*100:l.consumed>0?100:0)<r?o??null:n};function Kn(e){if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t}function Hn(){const{response:e}=Zr();return s(()=>{const t=e?.subscription;if(!t||"trialing"!==t.subscriptionStatus)return{isTrialing:!1,daysRemaining:0,trialEndsAt:null,trialStartedAt:null,isTrialEnding:!1};const r=Kn(t.trialEnd)??Kn(t.stripeCurrentPeriodEnd),n=Kn(t.trialStart),a=r?Math.max(0,Math.ceil((r.getTime()-Date.now())/864e5)):0;return{isTrialing:!0,daysRemaining:a,trialEndsAt:r,trialStartedAt:n,isTrialEnding:a<=3}},[e])}function Zn(e,t){const{response:r}=Zr();return s(()=>{if(!e)return{hasSeatPricing:!1,memberCount:0,includedSeats:0,maxUsers:0,maxSeats:0,limitSource:"none",billableSeats:0,availableSeats:1/0,isAtMax:!1,isNearMax:!1,perSeatPriceCents:null,currency:"",canInvite:!0,inviteBlockReason:null,inviteBlockMessage:null};const n=e.users?.length??0,a=r?.planVersion,o=r?.subscription,i=e.billingCurrency||"usd",s=Yt({planVersion:a,currency:i,settingsMaxUsers:t?.settingsMaxUsers}),{maxUsers:l,hasSeatPricing:c,includedSeats:d}=s,u=c?Math.max(0,n-d):0,f=l>0?Math.max(0,l-n):1/0,m=l>0&&n>=l,p=l>0&&n>=.8*l&&!m,h=c&&a?Jt(a,i,o?.billingInterval??"monthly"):null,g=Xt({memberCount:n,maxUsersConfig:s});return{hasSeatPricing:c,memberCount:n,includedSeats:d,maxUsers:l,maxSeats:l,limitSource:s.source,billableSeats:u,availableSeats:f,isAtMax:m,isNearMax:p,perSeatPriceCents:h,currency:i,canInvite:g.canInvite,inviteBlockReason:g.blockReason,inviteBlockMessage:g.blockMessage}},[r,e,t?.settingsMaxUsers])}Wn.displayName="WhenQuotaAvailable",jn.displayName="WhenQuotaExhausted",Bn.displayName="WhenQuotaOverage",Gn.displayName="WhenQuotaThreshold";var qn=e=>"checkbox"===e.type,Jn=e=>e instanceof Date,Yn=e=>null==e;const Xn=e=>"object"==typeof e;var Qn=e=>!Yn(e)&&!Array.isArray(e)&&Xn(e)&&!Jn(e),ea=e=>Qn(e)&&e.target?qn(e.target)?e.target.checked:e.target.value:e,ta=(e,t)=>e.has((e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e)(t)),ra="undefined"!=typeof window&&void 0!==window.HTMLElement&&"undefined"!=typeof document;function na(e){if(e instanceof Date)return new Date(e);const t="undefined"!=typeof FileList&&e instanceof FileList;if(ra&&(e instanceof Blob||t))return e;const r=Array.isArray(e);if(!(r||Qn(e)&&(e=>{const t=e.constructor&&e.constructor.prototype;return Qn(t)&&t.hasOwnProperty("isPrototypeOf")})(e)))return e;const n=r?[]:Object.create(Object.getPrototypeOf(e));for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=na(e[t]));return n}var aa=e=>/^\w*$/.test(e),oa=e=>void 0===e,ia=e=>Array.isArray(e)?e.filter(Boolean):[],sa=e=>ia(e.replace(/["|']|\]/g,"").split(/\.|\[/)),la=(e,t,r)=>{if(!t||!Qn(e))return r;const n=(aa(t)?[t]:sa(t)).reduce((e,t)=>Yn(e)?e:e[t],e);return oa(n)||n===e?oa(e[t])?r:e[t]:n},ca=e=>"boolean"==typeof e,da=e=>"function"==typeof e,ua=(e,t,r)=>{let n=-1;const a=aa(t)?[t]:sa(t),o=a.length,i=o-1;for(;++n<o;){const t=a[n];let o=r;if(n!==i){const r=e[t];o=Qn(r)||Array.isArray(r)?r:isNaN(+a[n+1])?{}:[]}if("__proto__"===t||"constructor"===t||"prototype"===t)return;e[t]=o,e=e[t]}};const fa="blur",ma="focusout",pa="change",ha="onBlur",ga="onChange",ba="onSubmit",ya="onTouched",va="all",wa="max",xa="min",Sa="maxLength",ka="minLength",Na="pattern",Ca="required",Ea="validate",Aa=a.createContext(null);Aa.displayName="HookFormControlContext";const _a=()=>a.useContext(Aa);var Ta=(e,t,r,n=!0)=>{const a={defaultValues:t._defaultValues};for(const o in e)Object.defineProperty(a,o,{get:()=>{const a=o;return t._proxyFormState[a]!==va&&(t._proxyFormState[a]=!n||va),r&&(r[a]=!0),e[a]}});return a};const Pa="undefined"!=typeof window?a.useLayoutEffect:a.useEffect;var Ra=e=>"string"==typeof e,Ia=(e,t,r,n,a)=>Ra(e)?(n&&t.watch.add(e),la(r,e,a)):Array.isArray(e)?e.map(e=>(n&&t.watch.add(e),la(r,e))):(n&&(t.watchAll=!0),r),Oa=e=>Yn(e)||!Xn(e);function Da(e,t,r=new WeakSet){if(Oa(e)||Oa(t))return Object.is(e,t);if(Jn(e)&&Jn(t))return Object.is(e.getTime(),t.getTime());const n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length)return!1;if(r.has(e)||r.has(t))return!0;r.add(e),r.add(t);for(const o of n){const n=e[o];if(!a.includes(o))return!1;if("ref"!==o){const e=t[o];if(Jn(n)&&Jn(e)||Qn(n)&&Qn(e)||Array.isArray(n)&&Array.isArray(e)?!Da(n,e,r):!Object.is(n,e))return!1}}return!0}function Ma(e){const t=_a(),{name:r,disabled:n,control:o=t,shouldUnregister:i,defaultValue:s,exact:l=!0}=e,c=ta(o._names.array,r),d=a.useMemo(()=>la(o._formValues,r,la(o._defaultValues,r,s)),[o,r,s]),u=function(e){const t=_a(),{control:r=t,name:n,defaultValue:o,disabled:i,exact:s,compute:l}=e||{},c=a.useRef(o),d=a.useRef(l),u=a.useRef(void 0),f=a.useRef(r),m=a.useRef(n);d.current=l;const[p,h]=a.useState(()=>{const e=r._getWatch(n,c.current);return d.current?d.current(e):e}),g=a.useCallback(e=>{const t=Ia(n,r._names,e||r._formValues,!1,c.current);return d.current?d.current(t):t},[r._formValues,r._names,n]),b=a.useCallback(e=>{if(!i){const t=Ia(n,r._names,e||r._formValues,!1,c.current);if(d.current){const e=d.current(t);Da(e,u.current)||(h(e),u.current=e)}else h(t)}},[r._formValues,r._names,i,n]);Pa(()=>(f.current===r&&Da(m.current,n)||(f.current=r,m.current=n,b()),r._subscribe({name:n,formState:{values:!0},exact:s,callback:e=>{b(e.values)}})),[r,s,n,b]),a.useEffect(()=>r._removeUnmounted());const y=f.current!==r,v=m.current,w=a.useMemo(()=>{if(i)return null;const e=!y&&!Da(v,n);return y||e?g():null},[i,y,n,v,g]);return null!==w?w:p}({control:o,name:r,defaultValue:d,exact:l}),f=function(e){const t=_a(),{control:r=t,disabled:n,name:o,exact:i}=e||{},[s,l]=a.useState(r._formState),c=a.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return Pa(()=>r._subscribe({name:o,formState:c.current,exact:i,callback:e=>{!n&&l({...r._formState,...e})}}),[o,n,i]),a.useEffect(()=>{c.current.isValid&&r._setValid(!0)},[r]),a.useMemo(()=>Ta(s,r,c.current,!1),[s,r])}({control:o,name:r,exact:l}),m=a.useRef(e),p=a.useRef(void 0),h=a.useRef(o.register(r,{...e.rules,value:u,...ca(e.disabled)?{disabled:e.disabled}:{}}));m.current=e;const g=a.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!la(f.errors,r)},isDirty:{enumerable:!0,get:()=>!!la(f.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!la(f.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!la(f.validatingFields,r)},error:{enumerable:!0,get:()=>la(f.errors,r)}}),[f,r]),b=a.useCallback(e=>h.current.onChange({target:{value:ea(e),name:r},type:pa}),[r]),y=a.useCallback(()=>h.current.onBlur({target:{value:la(o._formValues,r),name:r},type:fa}),[r,o._formValues]),v=a.useCallback(e=>{const t=la(o._fields,r);t&&t._f&&e&&(t._f.ref={focus:()=>da(e.focus)&&e.focus(),select:()=>da(e.select)&&e.select(),setCustomValidity:t=>da(e.setCustomValidity)&&e.setCustomValidity(t),reportValidity:()=>da(e.reportValidity)&&e.reportValidity()})},[o._fields,r]),w=a.useMemo(()=>({name:r,value:u,...ca(n)||f.disabled?{disabled:f.disabled||n}:{},onChange:b,onBlur:y,ref:v}),[r,n,f.disabled,b,y,v,u]);return a.useEffect(()=>{const e=o._options.shouldUnregister||i,t=p.current;t&&t!==r&&!c&&o.unregister(t),o.register(r,{...m.current.rules,...ca(m.current.disabled)?{disabled:m.current.disabled}:{}});const n=(e,t)=>{const r=la(o._fields,e);r&&r._f&&(r._f.mount=t)};if(n(r,!0),e){const e=na(la(o._options.defaultValues,r,m.current.defaultValue));ua(o._defaultValues,r,e),oa(la(o._formValues,r))&&ua(o._formValues,r,e)}return!c&&o.register(r),p.current=r,()=>{(c?e&&!o._state.action:e)?o.unregister(r):n(r,!1)}},[r,o,c,i]),a.useEffect(()=>{o._setDisabledField({disabled:n,name:r})},[n,r,o]),a.useMemo(()=>({field:w,formState:f,fieldState:g}),[w,f,g])}const Ua=e=>e.render(Ma(e)),za=a.createContext(null);za.displayName="HookFormContext";const Fa=e=>{const{children:t,watch:r,getValues:n,getFieldState:o,setError:i,clearErrors:s,setValue:l,trigger:c,formState:d,resetField:u,reset:f,handleSubmit:m,unregister:p,control:h,register:g,setFocus:b,subscribe:y}=e;return a.createElement(za.Provider,{value:a.useMemo(()=>({watch:r,getValues:n,getFieldState:o,setError:i,clearErrors:s,setValue:l,trigger:c,formState:d,resetField:u,reset:f,handleSubmit:m,unregister:p,control:h,register:g,setFocus:b,subscribe:y}),[s,h,d,o,n,m,g,f,u,i,b,l,y,c,p,r])},a.createElement(Aa.Provider,{value:h},t))};var La=(e,t,r,n,a)=>t?{...r[e],types:{...r[e]&&r[e].types?r[e].types:{},[n]:a||!0}}:{},$a=e=>Array.isArray(e)?e:[e],Va=()=>{let e=[];return{get observers(){return e},next:t=>{for(const r of e)r.next&&r.next(t)},subscribe:t=>(e.push(t),{unsubscribe:()=>{e=e.filter(e=>e!==t)}}),unsubscribe:()=>{e=[]}}};function Wa(e,t){const r={};for(const n in e)if(e.hasOwnProperty(n)){const a=e[n],o=t[n];if(a&&Qn(a)&&o){const e=Wa(a,o);Qn(e)&&(r[n]=e)}else e[n]&&(r[n]=o)}return r}var ja=e=>Qn(e)&&!Object.keys(e).length,Ba=e=>"file"===e.type,Ga=e=>{if(!ra)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Ka=e=>"select-multiple"===e.type,Ha=e=>"radio"===e.type,Za=e=>Ga(e)&&e.isConnected;function qa(e,t){const r=Array.isArray(t)?t:aa(t)?[t]:sa(t),n=1===r.length?e:function(e,t){const r=t.slice(0,-1).length;let n=0;for(;n<r;)e=oa(e)?n++:e[t[n++]];return e}(e,r),a=r.length-1,o=r[a];return n&&delete n[o],0!==a&&(Qn(n)&&ja(n)||Array.isArray(n)&&function(e){for(const t in e)if(e.hasOwnProperty(t)&&!oa(e[t]))return!1;return!0}(n))&&qa(e,r.slice(0,-1)),e}function Ja(e){return Array.isArray(e)||Qn(e)&&!(e=>{for(const t in e)if(da(e[t]))return!0;return!1})(e)}function Ya(e,t={}){for(const r in e){const n=e[r];Ja(n)?(t[r]=Array.isArray(n)?[]:{},Ya(n,t[r])):oa(n)||(t[r]=!0)}return t}function Xa(e,t,r){r||(r=Ya(t));for(const n in e){const a=e[n];if(Ja(a))oa(t)||Oa(r[n])?r[n]=Ya(a,Array.isArray(a)?[]:{}):Xa(a,Yn(t)?{}:t[n],r[n]);else{const e=t[n];r[n]=!Da(a,e)}}return r}const Qa={value:!1,isValid:!1},eo={value:!0,isValid:!0};var to=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(e=>e&&e.checked&&!e.disabled).map(e=>e.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!oa(e[0].attributes.value)?oa(e[0].value)||""===e[0].value?eo:{value:e[0].value,isValid:!0}:eo:Qa}return Qa},ro=(e,{valueAsNumber:t,valueAsDate:r,setValueAs:n})=>oa(e)?e:t?""===e?NaN:e?+e:e:r&&Ra(e)?new Date(e):n?n(e):e;const no={isValid:!1,value:null};var ao=e=>Array.isArray(e)?e.reduce((e,t)=>t&&t.checked&&!t.disabled?{isValid:!0,value:t.value}:e,no):no;function oo(e){const t=e.ref;return Ba(t)?t.files:Ha(t)?ao(e.refs).value:Ka(t)?[...t.selectedOptions].map(({value:e})=>e):qn(t)?to(e.refs).value:ro(oa(t.value)?e.ref.value:t.value,e)}var io=e=>e instanceof RegExp,so=e=>oa(e)?e:io(e)?e.source:Qn(e)?io(e.value)?e.value.source:e.value:e,lo=e=>({isOnSubmit:!e||e===ba,isOnBlur:e===ha,isOnChange:e===ga,isOnAll:e===va,isOnTouch:e===ya});const co="AsyncFunction";var uo=e=>!!e&&!!e.validate&&!!(da(e.validate)&&e.validate.constructor.name===co||Qn(e.validate)&&Object.values(e.validate).find(e=>e.constructor.name===co)),fo=(e,t,r)=>!r&&(t.watchAll||t.watch.has(e)||[...t.watch].some(t=>e.startsWith(t)&&/^\.\w+/.test(e.slice(t.length))));const mo=(e,t,r,n)=>{for(const a of r||Object.keys(e)){const r=la(e,a);if(r){const{_f:e,...o}=r;if(e){if(e.refs&&e.refs[0]&&t(e.refs[0],a)&&!n)return!0;if(e.ref&&t(e.ref,e.name)&&!n)return!0;if(mo(o,t))break}else if(Qn(o)&&mo(o,t))break}}};function po(e,t,r){const n=la(e,r);if(n||aa(r))return{error:n,name:r};const a=r.split(".");for(;a.length;){const n=a.join("."),o=la(t,n),i=la(e,n);if(o&&!Array.isArray(o)&&r!==n)return{name:r};if(i&&i.type)return{name:n,error:i};if(i&&i.root&&i.root.type)return{name:`${n}.root`,error:i.root};a.pop()}return{name:r}}var ho=(e,t,r)=>{const n=$a(la(e,r));return ua(n,"root",t[r]),ua(e,r,n),e};function go(e,t,r="validate"){if(Ra(e)||Array.isArray(e)&&e.every(Ra)||ca(e)&&!e)return{type:r,message:Ra(e)?e:"",ref:t}}var bo=e=>Qn(e)&&!io(e)?e:{value:e,message:""},yo=async(e,t,r,n,a,o)=>{const{ref:i,refs:s,required:l,maxLength:c,minLength:d,min:u,max:f,pattern:m,validate:p,name:h,valueAsNumber:g,mount:b}=e._f,y=la(r,h);if(!b||t.has(h))return{};const v=s?s[0]:i,w=e=>{a&&v.reportValidity&&(v.setCustomValidity(ca(e)?"":e||""),v.reportValidity())},x={},S=Ha(i),k=qn(i),N=S||k,C=(g||Ba(i))&&oa(i.value)&&oa(y)||Ga(i)&&""===i.value||""===y||Array.isArray(y)&&!y.length,E=La.bind(null,h,n,x),A=(e,t,r,n=Sa,a=ka)=>{const o=e?t:r;x[h]={type:e?n:a,message:o,ref:i,...E(e?n:a,o)}};if(o?!Array.isArray(y)||!y.length:l&&(!N&&(C||Yn(y))||ca(y)&&!y||k&&!to(s).isValid||S&&!ao(s).isValid)){const{value:e,message:t}=Ra(l)?{value:!!l,message:l}:bo(l);if(e&&(x[h]={type:Ca,message:t,ref:v,...E(Ca,t)},!n))return w(t),x}if(!(C||Yn(u)&&Yn(f))){let e,t;const r=bo(f),a=bo(u);if(Yn(y)||isNaN(y)){const n=i.valueAsDate||new Date(y),o=e=>new Date((new Date).toDateString()+" "+e),s="time"==i.type,l="week"==i.type;Ra(r.value)&&y&&(e=s?o(y)>o(r.value):l?y>r.value:n>new Date(r.value)),Ra(a.value)&&y&&(t=s?o(y)<o(a.value):l?y<a.value:n<new Date(a.value))}else{const n=i.valueAsNumber||(y?+y:y);Yn(r.value)||(e=n>r.value),Yn(a.value)||(t=n<a.value)}if((e||t)&&(A(!!e,r.message,a.message,wa,xa),!n))return w(x[h].message),x}if((c||d)&&!C&&(Ra(y)||o&&Array.isArray(y))){const e=bo(c),t=bo(d),r=!Yn(e.value)&&y.length>+e.value,a=!Yn(t.value)&&y.length<+t.value;if((r||a)&&(A(r,e.message,t.message),!n))return w(x[h].message),x}if(m&&!C&&Ra(y)){const{value:e,message:t}=bo(m);if(io(e)&&!y.match(e)&&(x[h]={type:Na,message:t,ref:i,...E(Na,t)},!n))return w(t),x}if(p)if(da(p)){const e=go(await p(y,r),v);if(e&&(x[h]={...e,...E(Ea,e.message)},!n))return w(e.message),x}else if(Qn(p)){let e={};for(const t in p){if(!ja(e)&&!n)break;const a=go(await p[t](y,r),v,t);a&&(e={...a,...E(t,a.message)},w(a.message),n&&(x[h]=e))}if(!ja(e)&&(x[h]={ref:v,...e},!n))return x}return w(!0),x};const vo={mode:ba,reValidateMode:ga,shouldFocusError:!0};function wo(e={}){let t,r={...vo,...e},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:da(r.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:r.errors||{},disabled:r.disabled||!1},a={},o=(Qn(r.defaultValues)||Qn(r.values))&&na(r.defaultValues||r.values)||{},i=r.shouldUnregister?{}:na(o),s={action:!1,mount:!1,watch:!1,keepIsValid:!1},l={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},c=0;const d={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},u={...d};let f={...u};const m={array:Va(),state:Va()},p=r.criteriaMode===va,h=async e=>{if(!s.keepIsValid&&!r.disabled&&(u.isValid||f.isValid||e)){let e;r.resolver?(e=ja((await w()).errors),g()):e=await x(a,!0),e!==n.isValid&&m.state.next({isValid:e})}},g=(e,t)=>{!r.disabled&&(u.isValidating||u.validatingFields||f.isValidating||f.validatingFields)&&((e||Array.from(l.mount)).forEach(e=>{e&&(t?ua(n.validatingFields,e,t):qa(n.validatingFields,e))}),m.state.next({validatingFields:n.validatingFields,isValidating:!ja(n.validatingFields)}))},b=(e,t,r,n)=>{const l=la(a,e);if(l){const a=la(i,e,oa(r)?la(o,e):r);oa(a)||n&&n.defaultChecked||t?ua(i,e,t?a:oo(l._f)):N(e,a),s.mount&&!s.action&&h()}},y=(e,t,a,i,s)=>{let l=!1,c=!1;const d={name:e};if(!r.disabled){if(!a||i){(u.isDirty||f.isDirty)&&(c=n.isDirty,n.isDirty=d.isDirty=S(),l=c!==d.isDirty);const r=Da(la(o,e),t);c=!!la(n.dirtyFields,e),r?qa(n.dirtyFields,e):ua(n.dirtyFields,e,!0),d.dirtyFields=n.dirtyFields,l=l||(u.dirtyFields||f.dirtyFields)&&c!==!r}if(a){const t=la(n.touchedFields,e);t||(ua(n.touchedFields,e,a),d.touchedFields=n.touchedFields,l=l||(u.touchedFields||f.touchedFields)&&t!==a)}l&&s&&m.state.next(d)}return l?d:{}},v=(e,a,o,i)=>{const s=la(n.errors,e),l=(u.isValid||f.isValid)&&ca(a)&&n.isValid!==a;var d;if(r.delayError&&o?(d=()=>((e,t)=>{ua(n.errors,e,t),m.state.next({errors:n.errors})})(e,o),t=e=>{clearTimeout(c),c=setTimeout(d,e)},t(r.delayError)):(clearTimeout(c),t=null,o?ua(n.errors,e,o):qa(n.errors,e)),(o?!Da(s,o):s)||!ja(i)||l){const t={...i,...l&&ca(a)?{isValid:a}:{},errors:n.errors,name:e};n={...n,...t},m.state.next(t)}},w=async e=>{g(e,!0);const t=await r.resolver(i,r.context,((e,t,r,n)=>{const a={};for(const r of e){const e=la(t,r);e&&ua(a,r,e._f)}return{criteriaMode:r,names:[...e],fields:a,shouldUseNativeValidation:n}})(e||l.mount,a,r.criteriaMode,r.shouldUseNativeValidation));return t},x=async(t,a,o={valid:!0})=>{for(const s in t){const c=t[s];if(c){const{_f:t,...s}=c;if(t){const s=l.array.has(t.name),d=c._f&&uo(c._f);d&&u.validatingFields&&g([t.name],!0);const f=await yo(c,l.disabled,i,p,r.shouldUseNativeValidation&&!a,s);if(d&&u.validatingFields&&g([t.name]),f[t.name]&&(o.valid=!1,a||e.shouldUseNativeValidation))break;!a&&(la(f,t.name)?s?ho(n.errors,f,t.name):ua(n.errors,t.name,f[t.name]):qa(n.errors,t.name))}!ja(s)&&await x(s,a,o)}}return o.valid},S=(e,t)=>!r.disabled&&(e&&t&&ua(i,e,t),!Da(P(),o)),k=(e,t,r)=>Ia(e,l,{...s.mount?i:oa(t)?o:Ra(e)?{[e]:t}:t},r,t),N=(e,t,r={})=>{const n=la(a,e);let o=t;if(n){const r=n._f;r&&(!r.disabled&&ua(i,e,ro(t,r)),o=Ga(r.ref)&&Yn(t)?"":t,Ka(r.ref)?[...r.ref.options].forEach(e=>e.selected=o.includes(e.value)):r.refs?qn(r.ref)?r.refs.forEach(e=>{e.defaultChecked&&e.disabled||(Array.isArray(o)?e.checked=!!o.find(t=>t===e.value):e.checked=o===e.value||!!o)}):r.refs.forEach(e=>e.checked=e.value===o):Ba(r.ref)?r.ref.value="":(r.ref.value=o,r.ref.type||m.state.next({name:e,values:na(i)})))}(r.shouldDirty||r.shouldTouch)&&y(e,o,r.shouldTouch,r.shouldDirty,!0),r.shouldValidate&&T(e)},C=(e,t,r)=>{for(const n in t){if(!t.hasOwnProperty(n))return;const o=t[n],i=e+"."+n,s=la(a,i);(l.array.has(e)||Qn(o)||s&&!s._f)&&!Jn(o)?C(i,o,r):N(i,o,r)}},E=(e,t,r={})=>{const c=la(a,e),d=l.array.has(e),p=na(t);ua(i,e,p),d?(m.array.next({name:e,values:na(i)}),(u.isDirty||u.dirtyFields||f.isDirty||f.dirtyFields)&&r.shouldDirty&&m.state.next({name:e,dirtyFields:Xa(o,i),isDirty:S(e,p)})):!c||c._f||Yn(p)?N(e,p,r):C(e,p,r),fo(e,l)?m.state.next({...n,name:e,values:na(i)}):m.state.next({name:s.mount?e:void 0,values:na(i)})},A=async e=>{s.mount=!0;const o=e.target;let c=o.name,d=!0;const b=la(a,c),S=e=>{d=Number.isNaN(e)||Jn(e)&&isNaN(e.getTime())||Da(e,la(i,c,e))},k=lo(r.mode),N=lo(r.reValidateMode);if(b){let s,C;const E=o.type?oo(b._f):ea(e),A=e.type===fa||e.type===ma,_=!(e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate))(b._f)&&!r.resolver&&!la(n.errors,c)&&!b._f.deps||((e,t,r,n,a)=>!a.isOnAll&&(!r&&a.isOnTouch?!(t||e):(r?n.isOnBlur:a.isOnBlur)?!e:!(r?n.isOnChange:a.isOnChange)||e))(A,la(n.touchedFields,c),n.isSubmitted,N,k),P=fo(c,l,A);ua(i,c,E),A?o&&o.readOnly||(b._f.onBlur&&b._f.onBlur(e),t&&t(0)):b._f.onChange&&b._f.onChange(e);const R=y(c,E,A),I=!ja(R)||P;if(!A&&m.state.next({name:c,type:e.type,values:na(i)}),_)return(u.isValid||f.isValid)&&("onBlur"===r.mode?A&&h():A||h()),I&&m.state.next({name:c,...P?{}:R});if(!A&&P&&m.state.next({...n}),r.resolver){const{errors:e}=await w([c]);if(g([c]),S(E),d){const t=po(n.errors,a,c),r=po(e,a,t.name||c);s=r.error,c=r.name,C=ja(e)}}else g([c],!0),s=(await yo(b,l.disabled,i,p,r.shouldUseNativeValidation))[c],g([c]),S(E),d&&(s?C=!1:(u.isValid||f.isValid)&&(C=await x(a,!0)));d&&(b._f.deps&&(!Array.isArray(b._f.deps)||b._f.deps.length>0)&&T(b._f.deps),v(c,C,s,R))}},_=(e,t)=>{if(la(n.errors,t)&&e.focus)return e.focus(),1},T=async(e,t={})=>{let o,i;const s=$a(e);if(r.resolver){const t=await(async e=>{const{errors:t}=await w(e);if(g(e),e)for(const r of e){const e=la(t,r);e?ua(n.errors,r,e):qa(n.errors,r)}else n.errors=t;return t})(oa(e)?e:s);o=ja(t),i=e?!s.some(e=>la(t,e)):o}else e?(i=(await Promise.all(s.map(async e=>{const t=la(a,e);return await x(t&&t._f?{[e]:t}:t)}))).every(Boolean),(i||n.isValid)&&h()):i=o=await x(a);return m.state.next({...!Ra(e)||(u.isValid||f.isValid)&&o!==n.isValid?{}:{name:e},...r.resolver||!e?{isValid:o}:{},errors:n.errors}),t.shouldFocus&&!i&&mo(a,_,e?s:l.mount),i},P=(e,t)=>{let r={...s.mount?i:o};return t&&(r=Wa(t.dirtyFields?n.dirtyFields:n.touchedFields,r)),oa(e)?r:Ra(e)?la(r,e):e.map(e=>la(r,e))},R=(e,t)=>({invalid:!!la((t||n).errors,e),isDirty:!!la((t||n).dirtyFields,e),error:la((t||n).errors,e),isValidating:!!la(n.validatingFields,e),isTouched:!!la((t||n).touchedFields,e)}),I=(e,t,r)=>{const o=(la(a,e,{_f:{}})._f||{}).ref,i=la(n.errors,e)||{},{ref:s,message:l,type:c,...d}=i;ua(n.errors,e,{...d,...t,ref:o}),m.state.next({name:e,errors:n.errors,isValid:!1}),r&&r.shouldFocus&&o&&o.focus&&o.focus()},O=e=>m.state.subscribe({next:t=>{var r,a,s;r=e.name,a=t.name,s=e.exact,r&&a&&r!==a&&!$a(r).some(e=>e&&(s?e===a:e.startsWith(a)||a.startsWith(e)))||!((e,t,r,n)=>{r(e);const{name:a,...o}=e;return ja(o)||Object.keys(o).length>=Object.keys(t).length||Object.keys(o).find(e=>t[e]===(!n||va))})(t,e.formState||u,V,e.reRenderRoot)||e.callback({values:{...i},...n,...t,defaultValues:o})}}).unsubscribe,D=(e,t={})=>{for(const s of e?$a(e):l.mount)l.mount.delete(s),l.array.delete(s),t.keepValue||(qa(a,s),qa(i,s)),!t.keepError&&qa(n.errors,s),!t.keepDirty&&qa(n.dirtyFields,s),!t.keepTouched&&qa(n.touchedFields,s),!t.keepIsValidating&&qa(n.validatingFields,s),!r.shouldUnregister&&!t.keepDefaultValue&&qa(o,s);m.state.next({values:na(i)}),m.state.next({...n,...t.keepDirty?{isDirty:S()}:{}}),!t.keepIsValid&&h()},M=({disabled:e,name:t})=>{if(ca(e)&&s.mount||e||l.disabled.has(t)){const r=l.disabled.has(t)!==!!e;e?l.disabled.add(t):l.disabled.delete(t),r&&s.mount&&!s.action&&h()}},U=(e,t={})=>{let n=la(a,e);const i=ca(t.disabled)||ca(r.disabled);return ua(a,e,{...n||{},_f:{...n&&n._f?n._f:{ref:{name:e}},name:e,mount:!0,...t}}),l.mount.add(e),n?M({disabled:ca(t.disabled)?t.disabled:r.disabled,name:e}):b(e,!0,t.value),{...i?{disabled:t.disabled||r.disabled}:{},...r.progressive?{required:!!t.required,min:so(t.min),max:so(t.max),minLength:so(t.minLength),maxLength:so(t.maxLength),pattern:so(t.pattern)}:{},name:e,onChange:A,onBlur:A,ref:i=>{if(i){U(e,t),n=la(a,e);const r=oa(i.value)&&i.querySelectorAll&&i.querySelectorAll("input,select,textarea")[0]||i,s=(e=>Ha(e)||qn(e))(r),l=n._f.refs||[];if(s?l.find(e=>e===r):r===n._f.ref)return;ua(a,e,{_f:{...n._f,...s?{refs:[...l.filter(Za),r,...Array.isArray(la(o,e))?[{}]:[]],ref:{type:r.type,name:e}}:{ref:r}}}),b(e,!1,void 0,r)}else n=la(a,e,{}),n._f&&(n._f.mount=!1),(r.shouldUnregister||t.shouldUnregister)&&(!ta(l.array,e)||!s.action)&&l.unMount.add(e)}}},z=()=>r.shouldFocusError&&mo(a,_,l.mount),F=(e,t)=>async o=>{let s;o&&(o.preventDefault&&o.preventDefault(),o.persist&&o.persist());let c=na(i);if(m.state.next({isSubmitting:!0}),r.resolver){const{errors:e,values:t}=await w();g(),n.errors=e,c=na(t)}else await x(a);if(l.disabled.size)for(const e of l.disabled)qa(c,e);if(qa(n.errors,"root"),ja(n.errors)){m.state.next({errors:{}});try{await e(c,o)}catch(e){s=e}}else t&&await t({...n.errors},o),z(),setTimeout(z);if(m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:ja(n.errors)&&!s,submitCount:n.submitCount+1,errors:n.errors}),s)throw s},L=(e,t={})=>{const c=e?na(e):o,d=na(c),f=ja(e),p=f?o:d;if(t.keepDefaultValues||(o=c),!t.keepValues){if(t.keepDirtyValues){const e=new Set([...l.mount,...Object.keys(Xa(o,i))]);for(const t of Array.from(e)){const e=la(n.dirtyFields,t),r=la(i,t),a=la(p,t);e&&!oa(r)?ua(p,t,r):e||oa(a)||E(t,a)}}else{if(ra&&oa(e))for(const e of l.mount){const t=la(a,e);if(t&&t._f){const e=Array.isArray(t._f.refs)?t._f.refs[0]:t._f.ref;if(Ga(e)){const t=e.closest("form");if(t){t.reset();break}}}}if(t.keepFieldsRef)for(const e of l.mount)E(e,la(p,e));else a={}}i=r.shouldUnregister?t.keepDefaultValues?na(o):{}:na(p),m.array.next({values:{...p}}),m.state.next({values:{...p}})}l={mount:t.keepDirtyValues?l.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},s.mount=!u.isValid||!!t.keepIsValid||!!t.keepDirtyValues||!r.shouldUnregister&&!ja(p),s.watch=!!r.shouldUnregister,s.keepIsValid=!!t.keepIsValid,s.action=!1,t.keepErrors||(n.errors={}),m.state.next({submitCount:t.keepSubmitCount?n.submitCount:0,isDirty:!f&&(t.keepDirty?n.isDirty:!(!t.keepDefaultValues||Da(e,o))),isSubmitted:!!t.keepIsSubmitted&&n.isSubmitted,dirtyFields:f?{}:t.keepDirtyValues?t.keepDefaultValues&&i?Xa(o,i):n.dirtyFields:t.keepDefaultValues&&e?Xa(o,e):t.keepDirty?n.dirtyFields:{},touchedFields:t.keepTouched?n.touchedFields:{},errors:t.keepErrors?n.errors:{},isSubmitSuccessful:!!t.keepIsSubmitSuccessful&&n.isSubmitSuccessful,isSubmitting:!1,defaultValues:o})},$=(e,t)=>L(da(e)?e(i):e,{...r.resetOptions,...t}),V=e=>{n={...n,...e}},W={control:{register:U,unregister:D,getFieldState:R,handleSubmit:F,setError:I,_subscribe:O,_runSchema:w,_updateIsValidating:g,_focusError:z,_getWatch:k,_getDirty:S,_setValid:h,_setFieldArray:(e,t=[],l,c,d=!0,p=!0)=>{if(c&&l&&!r.disabled){if(s.action=!0,p&&Array.isArray(la(a,e))){const t=l(la(a,e),c.argA,c.argB);d&&ua(a,e,t)}if(p&&Array.isArray(la(n.errors,e))){const t=l(la(n.errors,e),c.argA,c.argB);d&&ua(n.errors,e,t),((e,t)=>{!ia(la(e,t)).length&&qa(e,t)})(n.errors,e)}if((u.touchedFields||f.touchedFields)&&p&&Array.isArray(la(n.touchedFields,e))){const t=l(la(n.touchedFields,e),c.argA,c.argB);d&&ua(n.touchedFields,e,t)}(u.dirtyFields||f.dirtyFields)&&(n.dirtyFields=Xa(o,i)),m.state.next({name:e,isDirty:S(e,t),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else ua(i,e,t)},_setDisabledField:M,_setErrors:e=>{n.errors=e,m.state.next({errors:n.errors,isValid:!1})},_getFieldArray:e=>ia(la(s.mount?i:o,e,r.shouldUnregister?la(o,e,[]):[])),_reset:L,_resetDefaultValues:()=>da(r.defaultValues)&&r.defaultValues().then(e=>{$(e,r.resetOptions),m.state.next({isLoading:!1})}),_removeUnmounted:()=>{for(const e of l.unMount){const t=la(a,e);t&&(t._f.refs?t._f.refs.every(e=>!Za(e)):!Za(t._f.ref))&&D(e)}l.unMount=new Set},_disableForm:e=>{ca(e)&&(m.state.next({disabled:e}),mo(a,(t,r)=>{const n=la(a,r);n&&(t.disabled=n._f.disabled||e,Array.isArray(n._f.refs)&&n._f.refs.forEach(t=>{t.disabled=n._f.disabled||e}))},0,!1))},_subjects:m,_proxyFormState:u,get _fields(){return a},get _formValues(){return i},get _state(){return s},set _state(e){s=e},get _defaultValues(){return o},get _names(){return l},set _names(e){l=e},get _formState(){return n},get _options(){return r},set _options(e){r={...r,...e}}},subscribe:e=>(s.mount=!0,f={...f,...e.formState},O({...e,formState:{...d,...e.formState}})),trigger:T,register:U,handleSubmit:F,watch:(e,t)=>da(e)?m.state.subscribe({next:r=>"values"in r&&e(k(void 0,t),r)}):k(e,t,!0),setValue:E,getValues:P,reset:$,resetField:(e,t={})=>{la(a,e)&&(oa(t.defaultValue)?E(e,na(la(o,e))):(E(e,t.defaultValue),ua(o,e,na(t.defaultValue))),t.keepTouched||qa(n.touchedFields,e),t.keepDirty||(qa(n.dirtyFields,e),n.isDirty=t.defaultValue?S(e,na(la(o,e))):S()),t.keepError||(qa(n.errors,e),u.isValid&&h()),m.state.next({...n}))},clearErrors:e=>{e&&$a(e).forEach(e=>qa(n.errors,e)),m.state.next({errors:e?n.errors:{}})},unregister:D,setError:I,setFocus:(e,t={})=>{const r=la(a,e),n=r&&r._f;if(n){const e=n.refs?n.refs[0]:n.ref;e.focus&&setTimeout(()=>{e.focus(),t.shouldSelect&&da(e.select)&&e.select()})}},getFieldState:R};return{...W,formControl:W}}function xo(e={}){const t=a.useRef(void 0),r=a.useRef(void 0),[n,o]=a.useState({isDirty:!1,isValidating:!1,isLoading:da(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,isReady:!1,defaultValues:da(e.defaultValues)?void 0:e.defaultValues});if(!t.current)if(e.formControl)t.current={...e.formControl,formState:n},e.defaultValues&&!da(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:r,...a}=wo(e);t.current={...a,formState:n}}const i=t.current.control;return i._options=e,Pa(()=>{const e=i._subscribe({formState:i._proxyFormState,callback:()=>o({...i._formState}),reRenderRoot:!0});return o(e=>({...e,isReady:!0})),i._formState.isReady=!0,e},[i]),a.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),a.useEffect(()=>{e.mode&&(i._options.mode=e.mode),e.reValidateMode&&(i._options.reValidateMode=e.reValidateMode)},[i,e.mode,e.reValidateMode]),a.useEffect(()=>{e.errors&&(i._setErrors(e.errors),i._focusError())},[i,e.errors]),a.useEffect(()=>{e.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,e.shouldUnregister]),a.useEffect(()=>{if(i._proxyFormState.isDirty){const e=i._getDirty();e!==n.isDirty&&i._subjects.state.next({isDirty:e})}},[i,n.isDirty]),a.useEffect(()=>{var t;e.values&&!Da(e.values,r.current)?(i._reset(e.values,{keepFieldsRef:!0,...i._options.resetOptions}),(null===(t=i._options.resetOptions)||void 0===t?void 0:t.keepIsValid)||i._setValid(),r.current=e.values,o(e=>({...e}))):i._resetDefaultValues()},[i,e.values]),a.useEffect(()=>{i._state.mount||(i._setValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=a.useMemo(()=>Ta(n,i),[i,n]),t.current}const So=(e,t,r)=>{if(e&&"reportValidity"in e){const n=la(r,t);e.setCustomValidity(n&&n.message||""),e.reportValidity()}},ko=(e,t)=>{for(const r in t.fields){const n=t.fields[r];n&&n.ref&&"reportValidity"in n.ref?So(n.ref,r,e):n&&n.refs&&n.refs.forEach(t=>So(t,r,e))}},No=(e,t)=>{t.shouldUseNativeValidation&&ko(e,t);const r={};for(const n in e){const a=la(t.fields,n),o=Object.assign(e[n]||{},{ref:a&&a.ref});if(Co(t.names||Object.keys(e),n)){const e=Object.assign({},la(r,n));ua(e,"root",o),ua(r,n,e)}else ua(r,n,o)}return r},Co=(e,t)=>{const r=Eo(t);return e.some(e=>Eo(e).match(`^${r}\\.\\d+`))};function Eo(e){return e.replace(/\]|\[/g,"")}function Ao(e,t,r){function n(r,n){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:n,constr:i,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,n);const a=i.prototype,o=Object.keys(a);for(let e=0;e<o.length;e++){const t=o[e];t in r||(r[t]=a[t].bind(r))}}const a=r?.Parent??Object;class o extends a{}function i(e){var t;const a=r?.Parent?new o:this;n(a,e),(t=a._zod).deferred??(t.deferred=[]);for(const e of a._zod.deferred)e();return a}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class _o extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class To extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Po={};function Ro(e){return Po}function Io(e){const t=Object.values(e).filter(e=>"number"==typeof e),r=Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t);return r}function Oo(e,t){return"bigint"==typeof t?t.toString():t}function Do(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Mo(e){return null==e}function Uo(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const zo=Symbol("evaluating");function Fo(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==zo)return void 0===n&&(n=zo,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Lo(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function $o(...e){const t={};for(const r of e){const e=Object.getOwnPropertyDescriptors(r);Object.assign(t,e)}return Object.defineProperties({},t)}function Vo(e){return JSON.stringify(e)}const Wo="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function jo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Bo=Do(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Go(e){if(!1===jo(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const r=t.prototype;return!1!==jo(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function Ko(e){return Go(e)?{...e}:Array.isArray(e)?[...e]:e}const Ho=new Set(["string","number","symbol"]);function Zo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qo(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function Jo(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function Yo(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function Xo(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function Qo(e){return"string"==typeof e?e:e?.message}function ei(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const a=Qo(e.inst?._zod.def?.error?.(e))??Qo(t?.error?.(e))??Qo(r.customError?.(e))??Qo(r.localeError?.(e))??"Invalid input";n.message=a}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function ti(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function ri(...e){const[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}const ni=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Oo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ai=Ao("$ZodError",ni),oi=Ao("$ZodError",ni,{Parent:Error});const ii=e=>(t,r,n,a)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new _o;if(i.issues.length){const t=new(a?.Err??e)(i.issues.map(e=>ei(e,o,Ro())));throw Wo(t,a?.callee),t}return i.value},si=ii(oi),li=e=>async(t,r,n,a)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){const t=new(a?.Err??e)(i.issues.map(e=>ei(e,o,Ro())));throw Wo(t,a?.callee),t}return i.value},ci=li(oi),di=e=>(t,r,n)=>{const a=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},a);if(o instanceof Promise)throw new _o;return o.issues.length?{success:!1,error:new(e??ai)(o.issues.map(e=>ei(e,a,Ro())))}:{success:!0,data:o.value}},ui=di(oi),fi=e=>async(t,r,n)=>{const a=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},a);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>ei(e,a,Ro())))}:{success:!0,data:o.value}},mi=fi(oi),pi=e=>(t,r,n)=>{const a=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ii(e)(t,r,a)},hi=e=>(t,r,n)=>ii(e)(t,r,n),gi=e=>async(t,r,n)=>{const a=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return li(e)(t,r,a)},bi=e=>async(t,r,n)=>li(e)(t,r,n),yi=e=>(t,r,n)=>{const a=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return di(e)(t,r,a)},vi=e=>(t,r,n)=>di(e)(t,r,n),wi=e=>async(t,r,n)=>{const a=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return fi(e)(t,r,a)},xi=e=>async(t,r,n)=>fi(e)(t,r,n),Si=/^[cC][^\s-]{8,}$/,ki=/^[0-9a-z]+$/,Ni=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ci=/^[0-9a-vA-V]{20}$/,Ei=/^[A-Za-z0-9]{27}$/,Ai=/^[a-zA-Z0-9_-]{21}$/,_i=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ti=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Pi=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ri=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;const Ii=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Oi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Di=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Mi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ui=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,zi=/^[A-Za-z0-9_-]*$/,Fi=/^\+[1-9]\d{6,14}$/,Li="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",$i=new RegExp(`^${Li}$`);function Vi(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const Wi=/^[^A-Z]*$/,ji=/^[^a-z]*$/,Bi=Ao("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Gi=Ao("$ZodCheckMaxLength",(e,t)=>{var r;Bi.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!Mo(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const n=r.value;if(n.length<=t.maximum)return;const a=ti(n);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Ki=Ao("$ZodCheckMinLength",(e,t)=>{var r;Bi.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!Mo(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const n=r.value;if(n.length>=t.minimum)return;const a=ti(n);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Hi=Ao("$ZodCheckLengthEquals",(e,t)=>{var r;Bi.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!Mo(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{const n=r.value,a=n.length;if(a===t.length)return;const o=ti(n),i=a>t.length;r.issues.push({origin:o,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Zi=Ao("$ZodCheckStringFormat",(e,t)=>{var r,n;Bi.init(e,t),e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),qi=Ao("$ZodCheckRegex",(e,t)=>{Zi.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ji=Ao("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Wi),Zi.init(e,t)}),Yi=Ao("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ji),Zi.init(e,t)}),Xi=Ao("$ZodCheckIncludes",(e,t)=>{Bi.init(e,t);const r=Zo(t.includes),n=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Qi=Ao("$ZodCheckStartsWith",(e,t)=>{Bi.init(e,t);const r=new RegExp(`^${Zo(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),es=Ao("$ZodCheckEndsWith",(e,t)=>{Bi.init(e,t);const r=new RegExp(`.*${Zo(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),ts=Ao("$ZodCheckOverwrite",(e,t)=>{Bi.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class rs{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length)),n=t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e);for(const e of n)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const ns={major:4,minor:3,patch:6},as=Ao("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ns;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let n,a=Yo(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(a)continue;const t=e.issues.length,i=o._zod.check(e);if(i instanceof Promise&&!1===r?.async)throw new _o;if(n||i instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await i;e.issues.length!==t&&(a||(a=Yo(e,t)))});else{if(e.issues.length===t)continue;a||(a=Yo(e,t))}}return n?n.then(()=>e):e},r=(r,a,o)=>{if(Yo(r))return r.aborted=!0,r;const i=t(a,n,o);if(i instanceof Promise){if(!1===o.async)throw new _o;return i.then(t=>e._zod.parse(t,o))}return e._zod.parse(i,o)};e._zod.run=(a,o)=>{if(o.skipChecks)return e._zod.parse(a,o);if("backward"===o.direction){const t=e._zod.parse({value:a.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,a,o)):r(t,a,o)}const i=e._zod.parse(a,o);if(i instanceof Promise){if(!1===o.async)throw new _o;return i.then(e=>t(e,n,o))}return t(i,n,o)}}Fo(e,"~standard",()=>({validate:t=>{try{const r=ui(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return mi(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),os=Ao("$ZodString",(e,t)=>{var r;as.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(r=e._zod.bag,new RegExp(`^${r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),is=Ao("$ZodStringFormat",(e,t)=>{Zi.init(e,t),os.init(e,t)}),ss=Ao("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ti),is.init(e,t)}),ls=Ao("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Pi(e))}else t.pattern??(t.pattern=Pi());is.init(e,t)}),cs=Ao("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ri),is.init(e,t)}),ds=Ao("$ZodURL",(e,t)=>{is.init(e,t),e._zod.check=r=>{try{const n=r.value.trim(),a=new URL(n);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(a.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),void(t.normalize?r.value=a.href:r.value=n)}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),us=Ao("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),is.init(e,t)}),fs=Ao("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ai),is.init(e,t)}),ms=Ao("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Si),is.init(e,t)}),ps=Ao("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ki),is.init(e,t)}),hs=Ao("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ni),is.init(e,t)}),gs=Ao("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ci),is.init(e,t)}),bs=Ao("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ei),is.init(e,t)}),ys=Ao("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=Vi({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Li}T(?:${n})$`)}(t)),is.init(e,t)}),vs=Ao("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=$i),is.init(e,t)}),ws=Ao("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${Vi(t)}$`)),is.init(e,t)}),xs=Ao("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=_i),is.init(e,t)}),Ss=Ao("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ii),is.init(e,t),e._zod.bag.format="ipv4"}),ks=Ao("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Oi),is.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Ns=Ao("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Di),is.init(e,t)}),Cs=Ao("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Mi),is.init(e,t),e._zod.check=r=>{const n=r.value.split("/");try{if(2!==n.length)throw new Error;const[e,t]=n;if(!t)throw new Error;const r=Number(t);if(`${r}`!==t)throw new Error;if(r<0||r>128)throw new Error;new URL(`http://[${e}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Es(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const As=Ao("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ui),is.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{Es(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});const _s=Ao("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=zi),is.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{(function(e){if(!zi.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return Es(t.padEnd(4*Math.ceil(t.length/4),"="))})(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Ts=Ao("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Fi),is.init(e,t)});const Ps=Ao("$ZodJWT",(e,t)=>{is.init(e,t),e._zod.check=r=>{(function(e,t=null){try{const r=e.split(".");if(3!==r.length)return!1;const[n]=r;if(!n)return!1;const a=JSON.parse(atob(n));return!("typ"in a&&"JWT"!==a?.typ||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}})(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Rs=Ao("$ZodUnknown",(e,t)=>{as.init(e,t),e._zod.parse=e=>e}),Is=Ao("$ZodNever",(e,t)=>{as.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Os(e,t,r){e.issues.length&&t.issues.push(...Xo(r,e.issues)),t.value[r]=e.value}const Ds=Ao("$ZodArray",(e,t)=>{as.init(e,t),e._zod.parse=(r,n)=>{const a=r.value;if(!Array.isArray(a))return r.issues.push({expected:"array",code:"invalid_type",input:a,inst:e}),r;r.value=Array(a.length);const o=[];for(let e=0;e<a.length;e++){const i=a[e],s=t.element._zod.run({value:i,issues:[]},n);s instanceof Promise?o.push(s.then(t=>Os(t,r,e))):Os(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function Ms(e,t,r,n,a){if(e.issues.length){if(a&&!(r in n))return;t.issues.push(...Xo(r,e.issues))}void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function Us(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=(n=e.shape,Object.keys(n).filter(e=>"optional"===n[e]._zod.optin&&"optional"===n[e]._zod.optout));var n;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function zs(e,t,r,n,a,o){const i=[],s=a.keySet,l=a.catchall._zod,c=l.def.type,d="optional"===l.optout;for(const a in t){if(s.has(a))continue;if("never"===c){i.push(a);continue}const o=l.run({value:t[a],issues:[]},n);o instanceof Promise?e.push(o.then(e=>Ms(e,r,a,t,d))):Ms(o,r,a,t,d)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:o}),e.length?Promise.all(e).then(()=>r):r}const Fs=Ao("$ZodObject",(e,t)=>{as.init(e,t);const r=Object.getOwnPropertyDescriptor(t,"shape");if(!r?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}const n=Do(()=>Us(t));Fo(e._zod,"propValues",()=>{const e=t.shape,r={};for(const t in e){const n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(const e of n.values)r[t].add(e)}}return r});const a=jo,o=t.catchall;let i;e._zod.parse=(t,r)=>{i??(i=n.value);const s=t.value;if(!a(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};const l=[],c=i.shape;for(const e of i.keys){const n=c[e],a="optional"===n._zod.optout,o=n._zod.run({value:s[e],issues:[]},r);o instanceof Promise?l.push(o.then(r=>Ms(r,t,e,s,a))):Ms(o,t,e,s,a)}return o?zs(l,s,t,r,n.value,e):l.length?Promise.all(l).then(()=>t):t}}),Ls=Ao("$ZodObjectJIT",(e,t)=>{Fs.init(e,t);const r=e._zod.parse,n=Do(()=>Us(t));let a;const o=jo,i=!Po.jitless,s=i&&Bo.value,l=t.catchall;let c;e._zod.parse=(d,u)=>{c??(c=n.value);const f=d.value;return o(f)?i&&s&&!1===u?.async&&!0!==u.jitless?(a||(a=(e=>{const t=new rs(["shape","payload","ctx"]),r=n.value,a=e=>{const t=Vo(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let i=0;for(const e of r.keys)o[e]="key_"+i++;t.write("const newResult = {};");for(const n of r.keys){const r=o[n],i=Vo(n),s=e[n],l="optional"===s?._zod?.optout;t.write(`const ${r} = ${a(n)};`),l?t.write(`\n if (${r}.issues.length) {\n if (${i} in input) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${i}, ...iss.path] : [${i}]\n })));\n }\n }\n \n if (${r}.value === undefined) {\n if (${i} in input) {\n newResult[${i}] = undefined;\n }\n } else {\n newResult[${i}] = ${r}.value;\n }\n \n `):t.write(`\n if (${r}.issues.length) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${i}, ...iss.path] : [${i}]\n })));\n }\n \n if (${r}.value === undefined) {\n if (${i} in input) {\n newResult[${i}] = undefined;\n }\n } else {\n newResult[${i}] = ${r}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const s=t.compile();return(t,r)=>s(e,t,r)})(t.shape)),d=a(d,u),l?zs([],f,d,u,c,e):d):r(d,u):(d.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),d)}});function $s(e,t,r,n){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;const a=e.filter(e=>!Yo(e));return 1===a.length?(t.value=a[0].value,a[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>ei(e,n,Ro())))}),t)}const Vs=Ao("$ZodUnion",(e,t)=>{as.init(e,t),Fo(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Fo(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Fo(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Fo(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>Uo(e.source)).join("|")})$`)}});const r=1===t.options.length,n=t.options[0]._zod.run;e._zod.parse=(a,o)=>{if(r)return n(a,o);let i=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:a.value,issues:[]},o);if(t instanceof Promise)s.push(t),i=!0;else{if(0===t.issues.length)return t;s.push(t)}}return i?Promise.all(s).then(t=>$s(t,a,e,o)):$s(s,a,e,o)}}),Ws=Ao("$ZodIntersection",(e,t)=>{as.init(e,t),e._zod.parse=(e,r)=>{const n=e.value,a=t.left._zod.run({value:n,issues:[]},r),o=t.right._zod.run({value:n,issues:[]},r);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([t,r])=>Bs(e,t,r)):Bs(e,a,o)}});function js(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Go(e)&&Go(t)){const r=Object.keys(t),n=Object.keys(e).filter(e=>-1!==r.indexOf(e)),a={...e,...t};for(const r of n){const n=js(e[r],t[r]);if(!n.valid)return{valid:!1,mergeErrorPath:[r,...n.mergeErrorPath]};a[r]=n.data}return{valid:!0,data:a}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const a=js(e[n],t[n]);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Bs(e,t,r){const n=new Map;let a;for(const r of t.issues)if("unrecognized_keys"===r.code){a??(a=r);for(const e of r.keys)n.has(e)||n.set(e,{}),n.get(e).l=!0}else e.issues.push(r);for(const t of r.issues)if("unrecognized_keys"===t.code)for(const e of t.keys)n.has(e)||n.set(e,{}),n.get(e).r=!0;else e.issues.push(t);const o=[...n].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length&&a&&e.issues.push({...a,keys:o}),Yo(e))return e;const i=js(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const Gs=Ao("$ZodEnum",(e,t)=>{as.init(e,t);const r=Io(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(e=>Ho.has(typeof e)).map(e=>"string"==typeof e?Zo(e):e.toString()).join("|")})$`),e._zod.parse=(t,a)=>{const o=t.value;return n.has(o)||t.issues.push({code:"invalid_value",values:r,input:o,inst:e}),t}}),Ks=Ao("$ZodTransform",(e,t)=>{as.init(e,t),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new To(e.constructor.name);const a=t.transform(r.value,r);if(n.async){return(a instanceof Promise?a:Promise.resolve(a)).then(e=>(r.value=e,r))}if(a instanceof Promise)throw new _o;return r.value=a,r}});function Hs(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Zs=Ao("$ZodOptional",(e,t)=>{as.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Fo(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Fo(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Uo(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>Hs(t,e.value)):Hs(n,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}}),qs=Ao("$ZodExactOptional",(e,t)=>{Zs.init(e,t),Fo(e._zod,"values",()=>t.innerType._zod.values),Fo(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,r)=>t.innerType._zod.run(e,r)}),Js=Ao("$ZodNullable",(e,t)=>{as.init(e,t),Fo(e._zod,"optin",()=>t.innerType._zod.optin),Fo(e._zod,"optout",()=>t.innerType._zod.optout),Fo(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Uo(e.source)}|null)$`):void 0}),Fo(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),Ys=Ao("$ZodDefault",(e,t)=>{as.init(e,t),e._zod.optin="optional",Fo(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);if(void 0===e.value)return e.value=t.defaultValue,e;const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(e=>Xs(e,t)):Xs(n,t)}});function Xs(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Qs=Ao("$ZodPrefault",(e,t)=>{as.init(e,t),e._zod.optin="optional",Fo(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>("backward"===r.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),el=Ao("$ZodNonOptional",(e,t)=>{as.init(e,t),Fo(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,n)=>{const a=t.innerType._zod.run(r,n);return a instanceof Promise?a.then(t=>tl(t,e)):tl(a,e)}});function tl(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const rl=Ao("$ZodCatch",(e,t)=>{as.init(e,t),Fo(e._zod,"optin",()=>t.innerType._zod.optin),Fo(e._zod,"optout",()=>t.innerType._zod.optout),Fo(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>ei(e,r,Ro()))},input:e.value}),e.issues=[]),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>ei(e,r,Ro()))},input:e.value}),e.issues=[]),e)}}),nl=Ao("$ZodPipe",(e,t)=>{as.init(e,t),Fo(e._zod,"values",()=>t.in._zod.values),Fo(e._zod,"optin",()=>t.in._zod.optin),Fo(e._zod,"optout",()=>t.out._zod.optout),Fo(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("backward"===r.direction){const n=t.out._zod.run(e,r);return n instanceof Promise?n.then(e=>al(e,t.in,r)):al(n,t.in,r)}const n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>al(e,t.out,r)):al(n,t.out,r)}});function al(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}const ol=Ao("$ZodReadonly",(e,t)=>{as.init(e,t),Fo(e._zod,"propValues",()=>t.innerType._zod.propValues),Fo(e._zod,"values",()=>t.innerType._zod.values),Fo(e._zod,"optin",()=>t.innerType?._zod?.optin),Fo(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(il):il(n)}});function il(e){return e.value=Object.freeze(e.value),e}const sl=Ao("$ZodCustom",(e,t)=>{Bi.init(e,t),as.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const n=r.value,a=t.fn(n);if(a instanceof Promise)return a.then(t=>ll(t,r,n,e));ll(a,r,n,e)}});function ll(e,t,r,n){if(!e){const e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(ri(e))}}var cl;class dl{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];return this._map.set(e,r),r&&"object"==typeof r&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(cl=globalThis).__zod_globalRegistry??(cl.__zod_globalRegistry=new dl);const ul=globalThis.__zod_globalRegistry;function fl(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Jo(t)})}function ml(e,t){return new Gi({check:"max_length",...Jo(t),maximum:e})}function pl(e,t){return new Ki({check:"min_length",...Jo(t),minimum:e})}function hl(e,t){return new Hi({check:"length_equals",...Jo(t),length:e})}function gl(e){return new ts({check:"overwrite",tx:e})}function bl(e){const t=function(e,t){const r=new Bi({check:"custom",...Jo(t)});return r._zod.check=e,r}(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(ri(e,r.value,t._zod.def));else{const n=e;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(ri(n))}},e(r.value,r)));return t}function yl(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??ul,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function vl(e,t,r={path:[],schemaPath:[]}){var n;const a=e._zod.def,o=t.seen.get(e);if(o){o.count++;return r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema}const i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);const s=e._zod.toJSONSchema?.();if(s)i.schema=s;else{const n={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,n);else{const r=i.schema,o=t.processors[a.type];if(!o)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);o(e,t,r,n)}const o=e._zod.parent;o&&(i.ref||(i.ref=o),vl(o,t,n),t.seen.get(o).isParent=!0)}const l=t.metadataRegistry.get(e);l&&Object.assign(i.schema,l),"input"===t.io&&Sl(e)&&(delete i.schema.examples,delete i.schema.default),"input"===t.io&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault;return t.seen.get(e).schema}function wl(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const t of e.seen.entries()){const r=e.metadataRegistry.get(t[0])?.id;if(r){const e=n.get(r);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${r}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(r,t[0])}}const a=t=>{if(t[1].schema.$ref)return;const n=t[1],{ref:a,defId:o}=(t=>{const n="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const r=e.external.registry.get(t[0])?.id,a=e.external.uri??(e=>e);if(r)return{ref:a(r)};const o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${a("__shared")}#/${n}/${o}`}}if(t[1]===r)return{ref:"#"};const a=`#/${n}/`,o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:a+o}})(t);n.def={...n.schema},o&&(n.defId=o);const i=n.schema;for(const e in i)delete i[e];i.$ref=a};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const r of e.seen.entries()){const n=r[1];if(t===r[0]){a(r);continue}if(e.external){const n=e.external.registry.get(r[0])?.id;if(t!==r[0]&&n){a(r);continue}}const o=e.metadataRegistry.get(r[0])?.id;o?a(r):(n.cycle||n.count>1&&"ref"===e.reused)&&a(r)}}function xl(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=t=>{const r=e.seen.get(t);if(null===r.ref)return;const a=r.def??r.schema,o={...a},i=r.ref;if(r.ref=null,i){n(i);const r=e.seen.get(i),s=r.schema;!s.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(a,s):(a.allOf=a.allOf??[],a.allOf.push(s)),Object.assign(a,o);if(t._zod.parent===i)for(const e in a)"$ref"!==e&&"allOf"!==e&&(e in o||delete a[e]);if(s.$ref&&r.def)for(const e in a)"$ref"!==e&&"allOf"!==e&&e in r.def&&JSON.stringify(a[e])===JSON.stringify(r.def[e])&&delete a[e]}const s=t._zod.parent;if(s&&s!==i){n(s);const t=e.seen.get(s);if(t?.schema.$ref&&(a.$ref=t.schema.$ref,t.def))for(const e in a)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(a[e])===JSON.stringify(t.def[e])&&delete a[e]}e.override({zodSchema:t,jsonSchema:a,path:r.path??[]})};for(const t of[...e.seen.entries()].reverse())n(t[0]);const a={};if("draft-2020-12"===e.target?a.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?a.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?a.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const r=e.external.registry.get(t)?.id;if(!r)throw new Error("Schema is missing an `id` property");a.$id=e.external.uri(r)}Object.assign(a,r.def??r.schema);const o=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&("draft-2020-12"===e.target?a.$defs=o:a.definitions=o);try{const r=JSON.parse(JSON.stringify(a));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:kl(t,"input",e.processors),output:kl(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch(e){throw new Error("Error converting schema to JSON.")}}function Sl(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;if("transform"===n.type)return!0;if("array"===n.type)return Sl(n.element,r);if("set"===n.type)return Sl(n.valueType,r);if("lazy"===n.type)return Sl(n.getter(),r);if("promise"===n.type||"optional"===n.type||"nonoptional"===n.type||"nullable"===n.type||"readonly"===n.type||"default"===n.type||"prefault"===n.type)return Sl(n.innerType,r);if("intersection"===n.type)return Sl(n.left,r)||Sl(n.right,r);if("record"===n.type||"map"===n.type)return Sl(n.keyType,r)||Sl(n.valueType,r);if("pipe"===n.type)return Sl(n.in,r)||Sl(n.out,r);if("object"===n.type){for(const e in n.shape)if(Sl(n.shape[e],r))return!0;return!1}if("union"===n.type){for(const e of n.options)if(Sl(e,r))return!0;return!1}if("tuple"===n.type){for(const e of n.items)if(Sl(e,r))return!0;return!(!n.rest||!Sl(n.rest,r))}return!1}const kl=(e,t,r={})=>n=>{const{libraryOptions:a,target:o}=n??{},i=yl({...a??{},target:o,io:t,processors:r});return vl(e,i),wl(i,e),xl(i,e)},Nl={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Cl=(e,t,r,n)=>{const a=e._zod.def;vl(a.innerType,t,n);t.seen.get(e).ref=a.innerType};function El(e,t){try{var r=e()}catch(e){return t(e)}return r&&r.then?r.then(void 0,t):r}function Al(e,t){for(var r={};e.length;){var n=e[0],a=n.code,o=n.message,i=n.path.join(".");if(!r[i])if("unionErrors"in n){var s=n.unionErrors[0].errors[0];r[i]={message:s.message,type:s.code}}else r[i]={message:o,type:a};if("unionErrors"in n&&n.unionErrors.forEach(function(t){return t.errors.forEach(function(t){return e.push(t)})}),t){var l=r[i].types,c=l&&l[n.code];r[i]=La(i,t,r,a,c?[].concat(c,n.message):n.message)}e.shift()}return r}function _l(e,t){for(var r={};e.length;){var n=e[0],a=n.code,o=n.message,i=n.path.join(".");if(!r[i])if("invalid_union"===n.code&&n.errors.length>0){var s=n.errors[0][0];r[i]={message:s.message,type:s.code}}else r[i]={message:o,type:a};if("invalid_union"===n.code&&n.errors.forEach(function(t){return t.forEach(function(t){return e.push(t)})}),t){var l=r[i].types,c=l&&l[n.code];r[i]=La(i,t,r,a,c?[].concat(c,n.message):n.message)}e.shift()}return r}function Tl(e,t,r){if(void 0===r&&(r={}),function(e){return"_def"in e&&"object"==typeof e._def&&"typeName"in e._def}(e))return function(n,a,o){try{return Promise.resolve(El(function(){return Promise.resolve(e["sync"===r.mode?"parse":"parseAsync"](n,t)).then(function(e){return o.shouldUseNativeValidation&&ko({},o),{errors:{},values:r.raw?Object.assign({},n):e}})},function(e){if(function(e){return Array.isArray(null==e?void 0:e.issues)}(e))return{values:{},errors:No(Al(e.errors,!o.shouldUseNativeValidation&&"all"===o.criteriaMode),o)};throw e}))}catch(e){return Promise.reject(e)}};if(function(e){return"_zod"in e&&"object"==typeof e._zod}(e))return function(n,a,o){try{return Promise.resolve(El(function(){return Promise.resolve(("sync"===r.mode?si:ci)(e,n,t)).then(function(e){return o.shouldUseNativeValidation&&ko({},o),{errors:{},values:r.raw?Object.assign({},n):e}})},function(e){if(function(e){return e instanceof ai}(e))return{values:{},errors:No(_l(e.issues,!o.shouldUseNativeValidation&&"all"===o.criteriaMode),o)};throw e}))}catch(e){return Promise.reject(e)}};throw new Error("Invalid input: not a Zod schema")}
2
+ import{jsxs as e,jsx as t,Fragment as r}from"react/jsx-runtime";import*as n from"react";import a,{Component as o,useRef as i,useMemo as s,createContext as l,useReducer as c,useEffect as d,useCallback as u,useState as f,useContext as m,Suspense as p,lazy as h,forwardRef as g,createElement as b,useLayoutEffect as y}from"react";import*as v from"react-dom";import w from"react-dom";function x(e){var t,r,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e)){var a=e.length;for(t=0;t<a;t++)e[t]&&(r=x(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function S(){for(var e,t,r=0,n="",a=arguments.length;r<a;r++)(e=arguments[r])&&(t=x(e))&&(n&&(n+=" "),n+=t);return n}const k=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),N="-",C=[],E=e=>{const t=T(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=e;return{getClassGroupId:e=>{if(e.startsWith("[")&&e.endsWith("]"))return _(e);const r=e.split(N),n=""===r[0]&&r.length>1?1:0;return A(r,n,t)},getConflictingClassGroupIds:(e,t)=>{if(t){const t=n[e],a=r[e];return t?a?((e,t)=>{const r=new Array(e.length+t.length);for(let t=0;t<e.length;t++)r[t]=e[t];for(let n=0;n<t.length;n++)r[e.length+n]=t[n];return r})(a,t):t:a||C}return r[e]||C}}},A=(e,t,r)=>{if(0===e.length-t)return r.classGroupId;const n=e[t],a=r.nextPart.get(n);if(a){const r=A(e,t+1,a);if(r)return r}const o=r.validators;if(null===o)return;const i=0===t?e.join(N):e.slice(t).join(N),s=o.length;for(let e=0;e<s;e++){const t=o[e];if(t.validator(i))return t.classGroupId}},_=e=>-1===e.slice(1,-1).indexOf(":")?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),n=t.slice(0,r);return n?"arbitrary.."+n:void 0})(),T=e=>{const{theme:t,classGroups:r}=e;return P(r,t)},P=(e,t)=>{const r=k();for(const n in e){const a=e[n];R(a,r,n,t)}return r},R=(e,t,r,n)=>{const a=e.length;for(let o=0;o<a;o++){const a=e[o];I(a,t,r,n)}},I=(e,t,r,n)=>{"string"!=typeof e?"function"!=typeof e?M(e,t,r,n):D(e,t,r,n):O(e,t,r)},O=(e,t,r)=>{(""===e?t:U(t,e)).classGroupId=r},D=(e,t,r,n)=>{z(e)?R(e(n),t,r,n):(null===t.validators&&(t.validators=[]),t.validators.push(((e,t)=>({classGroupId:e,validator:t}))(r,e)))},M=(e,t,r,n)=>{const a=Object.entries(e),o=a.length;for(let e=0;e<o;e++){const[o,i]=a[e];R(i,U(t,o),r,n)}},U=(e,t)=>{let r=e;const n=t.split(N),a=n.length;for(let e=0;e<a;e++){const t=n[e];let a=r.nextPart.get(t);a||(a=k(),r.nextPart.set(t,a)),r=a}return r},z=e=>"isThemeGetter"in e&&!0===e.isThemeGetter,F=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),n=Object.create(null);const a=(a,o)=>{r[a]=o,t++,t>e&&(t=0,n=r,r=Object.create(null))};return{get(e){let t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(a(e,t),t):void 0},set(e,t){e in r?r[e]=t:a(e,t)}}},L=[],$=(e,t,r,n,a)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:n,isExternal:a}),V=e=>{const{prefix:t,experimentalParseClassName:r}=e;let n=e=>{const t=[];let r,n=0,a=0,o=0;const i=e.length;for(let s=0;s<i;s++){const i=e[s];if(0===n&&0===a){if(":"===i){t.push(e.slice(o,s)),o=s+1;continue}if("/"===i){r=s;continue}}"["===i?n++:"]"===i?n--:"("===i?a++:")"===i&&a--}const s=0===t.length?e:e.slice(o);let l=s,c=!1;s.endsWith("!")?(l=s.slice(0,-1),c=!0):s.startsWith("!")&&(l=s.slice(1),c=!0);return $(t,c,l,r&&r>o?r-o:void 0)};if(t){const e=t+":",r=n;n=t=>t.startsWith(e)?r(t.slice(e.length)):$(L,!1,t,void 0,!0)}if(r){const e=n;n=t=>r({className:t,parseClassName:e})}return n},W=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((e,r)=>{t.set(e,1e6+r)}),e=>{const r=[];let n=[];for(let a=0;a<e.length;a++){const o=e[a],i="["===o[0],s=t.has(o);i||s?(n.length>0&&(n.sort(),r.push(...n),n=[]),r.push(o)):n.push(o)}return n.length>0&&(n.sort(),r.push(...n)),r}},j=/\s+/,B=e=>{if("string"==typeof e)return e;let t,r="";for(let n=0;n<e.length;n++)e[n]&&(t=B(e[n]))&&(r&&(r+=" "),r+=t);return r},G=(e,...t)=>{let r,n,a,o;const i=e=>{const t=n(e);if(t)return t;const o=((e,t)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:a,sortModifiers:o}=t,i=[],s=e.trim().split(j);let l="";for(let e=s.length-1;e>=0;e-=1){const t=s[e],{isExternal:c,modifiers:d,hasImportantModifier:u,baseClassName:f,maybePostfixModifierPosition:m}=r(t);if(c){l=t+(l.length>0?" "+l:l);continue}let p=!!m,h=n(p?f.substring(0,m):f);if(!h){if(!p){l=t+(l.length>0?" "+l:l);continue}if(h=n(f),!h){l=t+(l.length>0?" "+l:l);continue}p=!1}const g=0===d.length?"":1===d.length?d[0]:o(d).join(":"),b=u?g+"!":g,y=b+h;if(i.indexOf(y)>-1)continue;i.push(y);const v=a(h,p);for(let e=0;e<v.length;++e){const t=v[e];i.push(b+t)}l=t+(l.length>0?" "+l:l)}return l})(e,r);return a(e,o),o};return o=s=>{const l=t.reduce((e,t)=>t(e),e());return r=(e=>({cache:F(e.cacheSize),parseClassName:V(e),sortModifiers:W(e),...E(e)}))(l),n=r.cache.get,a=r.cache.set,o=i,i(s)},(...e)=>o(((...e)=>{let t,r,n=0,a="";for(;n<e.length;)(t=e[n++])&&(r=B(t))&&(a&&(a+=" "),a+=r);return a})(...e))},K=[],H=e=>{const t=t=>t[e]||K;return t.isThemeGetter=!0,t},Z=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,q=/^\((?:(\w[\w-]*):)?(.+)\)$/i,J=/^\d+\/\d+$/,Y=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,X=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Q=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,ee=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,te=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,re=e=>J.test(e),ne=e=>!!e&&!Number.isNaN(Number(e)),ae=e=>!!e&&Number.isInteger(Number(e)),oe=e=>e.endsWith("%")&&ne(e.slice(0,-1)),ie=e=>Y.test(e),se=()=>!0,le=e=>X.test(e)&&!Q.test(e),ce=()=>!1,de=e=>ee.test(e),ue=e=>te.test(e),fe=e=>!pe(e)&&!we(e),me=e=>Ae(e,Re,ce),pe=e=>Z.test(e),he=e=>Ae(e,Ie,le),ge=e=>Ae(e,Oe,ne),be=e=>Ae(e,Te,ce),ye=e=>Ae(e,Pe,ue),ve=e=>Ae(e,Me,de),we=e=>q.test(e),xe=e=>_e(e,Ie),Se=e=>_e(e,De),ke=e=>_e(e,Te),Ne=e=>_e(e,Re),Ce=e=>_e(e,Pe),Ee=e=>_e(e,Me,!0),Ae=(e,t,r)=>{const n=Z.exec(e);return!!n&&(n[1]?t(n[1]):r(n[2]))},_e=(e,t,r=!1)=>{const n=q.exec(e);return!!n&&(n[1]?t(n[1]):r)},Te=e=>"position"===e||"percentage"===e,Pe=e=>"image"===e||"url"===e,Re=e=>"length"===e||"size"===e||"bg-size"===e,Ie=e=>"length"===e,Oe=e=>"number"===e,De=e=>"family-name"===e,Me=e=>"shadow"===e,Ue=G(()=>{const e=H("color"),t=H("font"),r=H("text"),n=H("font-weight"),a=H("tracking"),o=H("leading"),i=H("breakpoint"),s=H("container"),l=H("spacing"),c=H("radius"),d=H("shadow"),u=H("inset-shadow"),f=H("text-shadow"),m=H("drop-shadow"),p=H("blur"),h=H("perspective"),g=H("aspect"),b=H("ease"),y=H("animate"),v=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom",we,pe],w=()=>[we,pe,l],x=()=>[re,"full","auto",...w()],S=()=>[ae,"none","subgrid",we,pe],k=()=>["auto",{span:["full",ae,we,pe]},ae,we,pe],N=()=>[ae,"auto",we,pe],C=()=>["auto","min","max","fr",we,pe],E=()=>["auto",...w()],A=()=>[re,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...w()],_=()=>[e,we,pe],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom",ke,be,{position:[we,pe]}],P=()=>["auto","cover","contain",Ne,me,{size:[we,pe]}],R=()=>[oe,xe,he],I=()=>["","none","full",c,we,pe],O=()=>["",ne,xe,he],D=()=>[ne,oe,ke,be],M=()=>["","none",p,we,pe],U=()=>["none",ne,we,pe],z=()=>["none",ne,we,pe],F=()=>[ne,we,pe],L=()=>[re,"full",...w()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ie],breakpoint:[ie],color:[se],container:[ie],"drop-shadow":[ie],ease:["in","out","in-out"],font:[fe],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ie],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ie],shadow:[ie],spacing:["px",ne],text:[ie],"text-shadow":[ie],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",re,pe,we,g]}],container:["container"],columns:[{columns:[ne,pe,we,s]}],"break-after":[{"break-after":["auto","avoid","all","avoid-page","page","left","right","column"]}],"break-before":[{"break-before":["auto","avoid","all","avoid-page","page","left","right","column"]}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:v()}],overflow:[{overflow:["auto","hidden","clip","visible","scroll"]}],"overflow-x":[{"overflow-x":["auto","hidden","clip","visible","scroll"]}],"overflow-y":[{"overflow-y":["auto","hidden","clip","visible","scroll"]}],overscroll:[{overscroll:["auto","contain","none"]}],"overscroll-x":[{"overscroll-x":["auto","contain","none"]}],"overscroll-y":[{"overscroll-y":["auto","contain","none"]}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:x()}],"inset-x":[{"inset-x":x()}],"inset-y":[{"inset-y":x()}],start:[{start:x()}],end:[{end:x()}],top:[{top:x()}],right:[{right:x()}],bottom:[{bottom:x()}],left:[{left:x()}],visibility:["visible","invisible","collapse"],z:[{z:[ae,"auto",we,pe]}],basis:[{basis:[re,"full","auto",s,...w()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,re,"auto","initial","none",pe]}],grow:[{grow:["",ne,we,pe]}],shrink:[{shrink:["",ne,we,pe]}],order:[{order:[ae,"first","last","none",we,pe]}],"grid-cols":[{"grid-cols":S()}],"col-start-end":[{col:k()}],"col-start":[{"col-start":N()}],"col-end":[{"col-end":N()}],"grid-rows":[{"grid-rows":S()}],"row-start-end":[{row:k()}],"row-start":[{"row-start":N()}],"row-end":[{"row-end":N()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":C()}],"auto-rows":[{"auto-rows":C()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe","normal"]}],"justify-items":[{"justify-items":["start","end","center","stretch","center-safe","end-safe","normal"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch","center-safe","end-safe"]}],"align-content":[{content:["normal","start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"]}],"align-items":[{items:["start","end","center","stretch","center-safe","end-safe",{baseline:["","last"]}]}],"align-self":[{self:["auto","start","end","center","stretch","center-safe","end-safe",{baseline:["","last"]}]}],"place-content":[{"place-content":["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"]}],"place-items":[{"place-items":["start","end","center","stretch","center-safe","end-safe","baseline"]}],"place-self":[{"place-self":["auto","start","end","center","stretch","center-safe","end-safe"]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":w()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":w()}],"space-y-reverse":["space-y-reverse"],size:[{size:A()}],w:[{w:[s,"screen",...A()]}],"min-w":[{"min-w":[s,"screen","none",...A()]}],"max-w":[{"max-w":[s,"screen","none","prose",{screen:[i]},...A()]}],h:[{h:["screen","lh",...A()]}],"min-h":[{"min-h":["screen","lh","none",...A()]}],"max-h":[{"max-h":["screen","lh",...A()]}],"font-size":[{text:["base",r,xe,he]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[n,we,ge]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",oe,pe]}],"font-family":[{font:[Se,pe,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[a,we,pe]}],"line-clamp":[{"line-clamp":[ne,"none",we,ge]}],leading:[{leading:[o,...w()]}],"list-image":[{"list-image":["none",we,pe]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",we,pe]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:_()}],"text-color":[{text:_()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:["solid","dashed","dotted","double","wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",we,he]}],"text-decoration-color":[{decoration:_()}],"underline-offset":[{"underline-offset":[ne,"auto",we,pe]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:w()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",we,pe]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",we,pe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:T()}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","space","round"]}]}],"bg-size":[{bg:P()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ae,we,pe],radial:["",we,pe],conic:[ae,we,pe]},Ce,ye]}],"bg-color":[{bg:_()}],"gradient-from-pos":[{from:R()}],"gradient-via-pos":[{via:R()}],"gradient-to-pos":[{to:R()}],"gradient-from":[{from:_()}],"gradient-via":[{via:_()}],"gradient-to":[{to:_()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:O()}],"border-w-x":[{"border-x":O()}],"border-w-y":[{"border-y":O()}],"border-w-s":[{"border-s":O()}],"border-w-e":[{"border-e":O()}],"border-w-t":[{"border-t":O()}],"border-w-r":[{"border-r":O()}],"border-w-b":[{"border-b":O()}],"border-w-l":[{"border-l":O()}],"divide-x":[{"divide-x":O()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":O()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:["solid","dashed","dotted","double","hidden","none"]}],"divide-style":[{divide:["solid","dashed","dotted","double","hidden","none"]}],"border-color":[{border:_()}],"border-color-x":[{"border-x":_()}],"border-color-y":[{"border-y":_()}],"border-color-s":[{"border-s":_()}],"border-color-e":[{"border-e":_()}],"border-color-t":[{"border-t":_()}],"border-color-r":[{"border-r":_()}],"border-color-b":[{"border-b":_()}],"border-color-l":[{"border-l":_()}],"divide-color":[{divide:_()}],"outline-style":[{outline:["solid","dashed","dotted","double","none","hidden"]}],"outline-offset":[{"outline-offset":[ne,we,pe]}],"outline-w":[{outline:["",ne,xe,he]}],"outline-color":[{outline:_()}],shadow:[{shadow:["","none",d,Ee,ve]}],"shadow-color":[{shadow:_()}],"inset-shadow":[{"inset-shadow":["none",u,Ee,ve]}],"inset-shadow-color":[{"inset-shadow":_()}],"ring-w":[{ring:O()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:_()}],"ring-offset-w":[{"ring-offset":[ne,he]}],"ring-offset-color":[{"ring-offset":_()}],"inset-ring-w":[{"inset-ring":O()}],"inset-ring-color":[{"inset-ring":_()}],"text-shadow":[{"text-shadow":["none",f,Ee,ve]}],"text-shadow-color":[{"text-shadow":_()}],opacity:[{opacity:[ne,we,pe]}],"mix-blend":[{"mix-blend":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"]}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ne]}],"mask-image-linear-from-pos":[{"mask-linear-from":D()}],"mask-image-linear-to-pos":[{"mask-linear-to":D()}],"mask-image-linear-from-color":[{"mask-linear-from":_()}],"mask-image-linear-to-color":[{"mask-linear-to":_()}],"mask-image-t-from-pos":[{"mask-t-from":D()}],"mask-image-t-to-pos":[{"mask-t-to":D()}],"mask-image-t-from-color":[{"mask-t-from":_()}],"mask-image-t-to-color":[{"mask-t-to":_()}],"mask-image-r-from-pos":[{"mask-r-from":D()}],"mask-image-r-to-pos":[{"mask-r-to":D()}],"mask-image-r-from-color":[{"mask-r-from":_()}],"mask-image-r-to-color":[{"mask-r-to":_()}],"mask-image-b-from-pos":[{"mask-b-from":D()}],"mask-image-b-to-pos":[{"mask-b-to":D()}],"mask-image-b-from-color":[{"mask-b-from":_()}],"mask-image-b-to-color":[{"mask-b-to":_()}],"mask-image-l-from-pos":[{"mask-l-from":D()}],"mask-image-l-to-pos":[{"mask-l-to":D()}],"mask-image-l-from-color":[{"mask-l-from":_()}],"mask-image-l-to-color":[{"mask-l-to":_()}],"mask-image-x-from-pos":[{"mask-x-from":D()}],"mask-image-x-to-pos":[{"mask-x-to":D()}],"mask-image-x-from-color":[{"mask-x-from":_()}],"mask-image-x-to-color":[{"mask-x-to":_()}],"mask-image-y-from-pos":[{"mask-y-from":D()}],"mask-image-y-to-pos":[{"mask-y-to":D()}],"mask-image-y-from-color":[{"mask-y-from":_()}],"mask-image-y-to-color":[{"mask-y-to":_()}],"mask-image-radial":[{"mask-radial":[we,pe]}],"mask-image-radial-from-pos":[{"mask-radial-from":D()}],"mask-image-radial-to-pos":[{"mask-radial-to":D()}],"mask-image-radial-from-color":[{"mask-radial-from":_()}],"mask-image-radial-to-color":[{"mask-radial-to":_()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"]}],"mask-image-conic-pos":[{"mask-conic":[ne]}],"mask-image-conic-from-pos":[{"mask-conic-from":D()}],"mask-image-conic-to-pos":[{"mask-conic-to":D()}],"mask-image-conic-from-color":[{"mask-conic-from":_()}],"mask-image-conic-to-color":[{"mask-conic-to":_()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:T()}],"mask-repeat":[{mask:["no-repeat",{repeat:["","x","y","space","round"]}]}],"mask-size":[{mask:P()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",we,pe]}],filter:[{filter:["","none",we,pe]}],blur:[{blur:M()}],brightness:[{brightness:[ne,we,pe]}],contrast:[{contrast:[ne,we,pe]}],"drop-shadow":[{"drop-shadow":["","none",m,Ee,ve]}],"drop-shadow-color":[{"drop-shadow":_()}],grayscale:[{grayscale:["",ne,we,pe]}],"hue-rotate":[{"hue-rotate":[ne,we,pe]}],invert:[{invert:["",ne,we,pe]}],saturate:[{saturate:[ne,we,pe]}],sepia:[{sepia:["",ne,we,pe]}],"backdrop-filter":[{"backdrop-filter":["","none",we,pe]}],"backdrop-blur":[{"backdrop-blur":M()}],"backdrop-brightness":[{"backdrop-brightness":[ne,we,pe]}],"backdrop-contrast":[{"backdrop-contrast":[ne,we,pe]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,we,pe]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,we,pe]}],"backdrop-invert":[{"backdrop-invert":["",ne,we,pe]}],"backdrop-opacity":[{"backdrop-opacity":[ne,we,pe]}],"backdrop-saturate":[{"backdrop-saturate":[ne,we,pe]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,we,pe]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",we,pe]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",we,pe]}],ease:[{ease:["linear","initial",b,we,pe]}],delay:[{delay:[ne,we,pe]}],animate:[{animate:["none",y,we,pe]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[h,we,pe]}],"perspective-origin":[{"perspective-origin":v()}],rotate:[{rotate:U()}],"rotate-x":[{"rotate-x":U()}],"rotate-y":[{"rotate-y":U()}],"rotate-z":[{"rotate-z":U()}],scale:[{scale:z()}],"scale-x":[{"scale-x":z()}],"scale-y":[{"scale-y":z()}],"scale-z":[{"scale-z":z()}],"scale-3d":["scale-3d"],skew:[{skew:F()}],"skew-x":[{"skew-x":F()}],"skew-y":[{"skew-y":F()}],transform:[{transform:[we,pe,"","none","gpu","cpu"]}],"transform-origin":[{origin:v()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:L()}],"translate-x":[{"translate-x":L()}],"translate-y":[{"translate-y":L()}],"translate-z":[{"translate-z":L()}],"translate-none":["translate-none"],accent:[{accent:_()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:_()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",we,pe]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",we,pe]}],fill:[{fill:["none",..._()]}],"stroke-w":[{stroke:[ne,xe,he,ge]}],stroke:[{stroke:["none",..._()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function ze(...e){return Ue(S(e))}let Fe=!0;function Le(e,...t){Fe&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}function $e(e,...t){console.error(e,...t)}function Ve(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}async function We(e,t){try{const r=await e.json();return r?.message||r?.error||t}catch{return t}}async function je(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function Be(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await je(e);r=t.message||t.error||r}catch{r=function(e,t){const r={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${r})`)}(e,t).message}throw new Error(r)}try{return await je(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class Ge extends Error{constructor(e,t,r,n){super(e),this.code=t,this.context=r,this.originalError=n,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,Ge)}}const Ke=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(e){this.config={...this.config,...e},void 0!==e.enableConsoleLogging&&function(e){void 0!==e.enableLogging&&(Fe=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(Ve(e))return;const r=e instanceof Error?e:new Ge("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),n=r instanceof Ge?r:new Ge(r.message,"SDK_ERROR",t,r);if(this.config.enableConsoleLogging&&Le(`[SDK Error] ${t.component||"Unknown"}:`,{message:n.message,code:n.code,context:n.context,originalError:n.originalError,stack:n.stack}),this.config.onError)try{this.config.onError(n,t)}catch(e){$e("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(n,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...r)=>e(...r).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...r)=>{try{return e(...r)}catch(e){throw this.handleError(e,t),e}}}};function He(e,t={}){Ke.handleError(e,t)}function Ze(e,t={}){return!Ve(e)&&(Ke.handleError(e,t),!0)}class qe extends o{constructor(e){super(e),this.resetError=()=>{this.setState({hasError:!1,error:null})},this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){if(He(e,{component:"ErrorBoundary",action:"componentDidCatch",metadata:{componentStack:t.componentStack,errorBoundary:this.constructor.name}}),this.props.onError)try{this.props.onError(e,t)}catch(e){$e("[SDK ErrorBoundary] Error in onError callback:",e)}}componentDidUpdate(e){this.state.hasError&&!1!==this.props.resetOnPropsChange&&e.children!==this.props.children&&this.resetError()}render(){return this.state.hasError&&this.state.error?this.props.fallback?"function"==typeof this.props.fallback?this.props.fallback(this.state.error,this.resetError):this.props.fallback:e("div",{style:{padding:"1rem",border:"1px solid #ef4444",borderRadius:"0.5rem",backgroundColor:"#fef2f2",color:"#991b1b"},children:[t("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem",fontWeight:600},children:"Something went wrong"}),t("p",{style:{margin:"0 0 1rem 0",fontSize:"0.875rem"},children:this.state.error.message||"An unexpected error occurred"}),t("button",{onClick:this.resetError,style:{padding:"0.5rem 1rem",backgroundColor:"#ef4444",color:"white",border:"none",borderRadius:"0.25rem",cursor:"pointer",fontSize:"0.875rem"},children:"Try again"})]}):this.props.children}}const Je=()=>({type:"AUTHENTICATION_STARTED"}),Ye=()=>({type:"AUTHENTICATION_PROCESSING"}),Xe=()=>({type:"AUTHENTICATION_FAILED"}),Qe=e=>({type:"SET_SESSION",payload:e}),et=()=>({type:"REMOVE_SESSION"});function tt(e,t,r){const n=i(t),a=i(r),o=i(void 0),l=i(!1);return n.current=t,a.current=r,s(()=>{const t=n.current(e);if(l.current){if(a.current?a.current(o.current,t):Object.is(o.current,t))return o.current}return o.current=t,l.current=!0,t},[e])}function rt({name:e,initialState:r,reducer:n,initializer:o}){const i=l(null),d=l(null),u=l(null),f=a.memo(({children:e})=>{const[a,l]=c(n,r,o||(e=>e)),f=s(()=>({state:a,dispatch:l}),[a,l]);return t(u.Provider,{value:f,children:t(i.Provider,{value:a,children:t(d.Provider,{value:l,children:e})})})});f.displayName=`${e}Provider`;const m=t=>new Error(`use${e}${t} must be used within a ${e}Provider. Make sure SaaSOSProvider is wrapping your application.`),p=()=>{const e=a.useContext(i);if(null===e)throw m("State");return e};return{Provider:f,useContext:()=>{const e=a.useContext(u);if(!e)throw m("Context");return e},useState:p,useDispatch:()=>{const e=a.useContext(d);if(null===e)throw m("Dispatch");return e},useSelector:(e,t)=>{const r=e||(e=>e);return tt(p(),r,t)}}}var nt;function at(e){return{isAuthenticated:e===nt.authenticated,isLoading:e===nt.loading||e===nt.redirecting||e===nt.authenticating,isRedirecting:e===nt.redirecting}}function ot(e,t,r){return{...e,[t]:r}}function it(e,t){return{...e,...t}}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(nt||(nt={}));const st=()=>({session:null,status:nt.loading}),{Provider:lt,useState:ct,useDispatch:dt}=rt({name:"Auth",initialState:st(),reducer:(e,t)=>{switch(t.type){case"AUTHENTICATION_STARTED":return ot(e,"status",nt.redirecting);case"AUTHENTICATION_PROCESSING":return ot(e,"status",nt.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return it(e,{session:null,status:nt.unauthenticated});case"SET_SESSION":return it(e,{session:t.payload,status:nt.authenticated});default:return e}},initializer:st}),ut=lt,ft=ct,mt=dt,pt=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),ht=e=>({type:"SET_SETTINGS",payload:e});var gt;function bt(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}!function(e){e.V1="v1"}(gt||(gt={}));const yt=()=>({serverUrl:"",version:gt.V1,orgId:"",settings:null}),{Provider:vt,useState:wt,useDispatch:xt}=rt({name:"OS",initialState:yt(),reducer:(e,t)=>{switch(t.type){case"SET_SAAS_OS_CONFIG":return it(e,t.payload);case"REMOVE_SAAS_OS_CONFIG":return yt();case"SET_SETTINGS":return ot(e,"settings",t.payload);default:return e}}}),St=vt,kt=wt,Nt=xt,Ct=e=>({type:"SET_WORKSPACES",payload:e}),Et=e=>({type:"ADD_WORKSPACE",payload:e}),At=e=>({type:"UPDATE_WORKSPACE",payload:e}),_t=e=>({type:"REMOVE_WORKSPACE",payload:e}),Tt=e=>({type:"SET_ALL_FEATURES",payload:e}),Pt=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),Rt=()=>({type:"RESET_CURRENT_WORKSPACE"}),It=e=>({type:"SET_IS_INITIALIZED",payload:e}),Ot=e=>({type:"SET_LOADING",payload:e}),Dt=e=>({type:"SET_ERROR",payload:e}),Mt=e=>({type:"SET_REFRESHING",payload:e}),Ut=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:zt,useState:Ft,useDispatch:Lt}=rt({name:"Workspace",initialState:{workspaces:[],loading:!1,error:null,currentWorkspace:null,refreshing:!1,switchingToId:null,isInitialized:!1,allFeatures:[]},reducer:(e,t)=>{switch(t.type){case"SET_WORKSPACES":return ot(e,"workspaces",t.payload);case"ADD_WORKSPACE":return ot(e,"workspaces",[...e.workspaces,t.payload]);case"UPDATE_WORKSPACE":return ot(e,"workspaces",e.workspaces.map(e=>e._id===t.payload._id?t.payload:e));case"REMOVE_WORKSPACE":return ot(e,"workspaces",e.workspaces.filter(e=>e._id!==t.payload));case"SET_ALL_FEATURES":return ot(e,"allFeatures",t.payload);case"SET_CURRENT_WORKSPACE":return ot(e,"currentWorkspace",t.payload);case"RESET_CURRENT_WORKSPACE":return ot(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return ot(e,"isInitialized",t.payload);case"SET_LOADING":return ot(e,"loading",t.payload);case"SET_ERROR":return ot(e,"error",t.payload);case"SET_REFRESHING":return ot(e,"refreshing",t.payload);case"SET_SWITCHING_TO_ID":return ot(e,"switchingToId",t.payload);default:return e}}}),$t=zt,Vt=Ft,Wt=Lt,jt=a.memo(({children:e})=>t(St,{children:t(ut,{children:t($t,{children:e})})}));function Bt(e,t){const r=e.pricingVariants;if(!r?.length)return null;const n=t.toLowerCase();return r.find(e=>e.currency?.toLowerCase()===n)??null}function Gt(e,t,r){const n=Bt(e,t);if(!n?.basePricing)return null;const a=n.basePricing[r];return null!=a?a:null}function Kt(e,t,r,n){const a=Bt(e,t),o=a?.quotaOverages?.[r];if(o)return o[n]}function Ht(e,t,r,n){const a=e.quotas?.[r];if(null==a)return null;const o=a[n];if(!o)return null;const i=Kt(e,t,r,n);return{included:o.included,...void 0!==o.unitSize&&{unitSize:o.unitSize},...void 0!==i&&{overage:i}}}function Zt(e,t){if(!e)return null;for(const r of t){const t=r.pricingVariants;if(t?.length)for(const r of t){const t=r.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:r.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:r.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:r.currency}}}}return null}function qt(e,t){const r=Bt(e,t);return r?.seatPricing?.enabled?r.seatPricing:null}function Jt(e,t,r){const n=qt(e,t);return n?.perSeat?n.perSeat[r]??null:null}function Yt(e){const{planVersion:t,currency:r="usd",settingsMaxUsers:n}=e;if(t){const e=qt(t,r);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=n&&n>0?{maxUsers:n,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function Xt(e){const{memberCount:t,maxUsersConfig:r,hasSubscription:n=!0,requireSubscription:a=!1}=e;if(a&&!n)return{canInvite:!1,blockReason:"no_subscription",blockMessage:"A subscription is required to invite members."};const{maxUsers:o,source:i}=r;if(o<=0)return{canInvite:!0,blockReason:null,blockMessage:null};if(t>=o){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[i]??"seat_limit_reached",blockMessage:{seat_pricing:`Your plan allows up to ${o} members. Upgrade for more seats.`,settings:`This workspace allows up to ${o} members.`}[i]??`Member limit of ${o} reached.`}}return{canInvite:!0,blockReason:null,blockMessage:null}}jt.displayName="SDKContextProvider";const Qt=new Set;function er(){Qt.forEach(e=>e())}const tr=new class{constructor(){this.callbacks=null}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,t){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,t)}catch(t){He(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit("user:created",{user:e})}async emitUserUpdated(e,t){await this.emit("user:updated",{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit("workspace:changed",{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit("workspace:updated",{workspace:e})}async emitWorkspaceUserAdded(e,t,r){await this.emit("workspace:user-added",{userId:e,workspace:t,role:r})}async emitWorkspaceUserRemoved(e,t,r){await this.emit("workspace:user-removed",{userId:e,workspace:t,role:r})}async emitWorkspaceUserRoleChanged(e,t,r,n){await this.emit("workspace:user-role-changed",{userId:e,workspace:t,previousRole:r,newRole:n})}async emitWorkspaceCreated(e){await this.emit("workspace:created",{workspace:e})}async emitWorkspaceDeleted(e){await this.emit("workspace:deleted",{workspace:e})}};function rr(e,t,r){d(()=>{const t=new AbortController;return e(t.signal).catch(e=>{Ve(e)||(r?.onError?r.onError(e):He(e,{component:"useAsyncEffect",action:"effect",metadata:{note:"Unhandled rejection - consider passing onError"}}))}),()=>t.abort()},t)}function nr(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return He(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function ar(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){He(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}function or(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){He(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}const ir="saas-session-id",sr="code";function lr(e){ar(ir,e)}function cr(){return function(){if("undefined"==typeof window)return null;try{return nr(ir)}catch(e){return He(e,{component:"auth-utils",action:"getSessionId",metadata:{key:ir}}),null}}()}function dr(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(sr)}catch(e){return He(e,{component:"auth-utils",action:"getTokenFromUrl",metadata:{param:sr}}),null}}const ur="SDK is not ready (missing serverUrl, version, or orgId)";class fr{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(ur);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(ur)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=cr(),t={};return e&&(t["x-session-id"]=e),t}()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}async executeFetch(e,t){const r=this.url(e),n=(t.method??"GET").toUpperCase(),a=this.buildHeaders(t),o={...t,headers:a};let i;if(this._timeout>0){const e=new AbortController;i=setTimeout(()=>e.abort(),this._timeout),o.signal=t.signal?AbortSignal.any([t.signal,e.signal]):e.signal}const s=async t=>{try{const e=this._fetch.bind(globalThis),a=await e(r,o);if(this._debug&&console.log(`[BuildBase] ${n} ${r} → ${a.status}`),a.status>=500&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),s(t+1)}return a}catch(r){if(r instanceof Error&&"AbortError"===r.name){if(void 0!==i){const t=new Error(`Request timeout after ${this._timeout}ms: ${n} ${e}`);throw this._onError?.(t,{method:n,path:e}),t}throw r}if(t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),s(t+1)}throw r instanceof Error&&this._onError?.(r,{method:n,path:e}),r}};try{return await s(0)}finally{void 0!==i&&clearTimeout(i)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const n=await this.executeFetch(e,t);return await Be(n,r)}catch(r){throw r instanceof Error&&this._onError?.(r,{method:(t.method??"GET").toUpperCase(),path:e}),r}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}}class mr extends fr{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}function pr(){return qr(e=>e.os)}let hr=null;function gr(){const e=Jr(),t=pr(),{serverUrl:r,version:n,orgId:a,settings:o}=t,i=s(()=>bt(t)?new mr({serverUrl:r,version:n,orgId:a}):null,[r,n,a]),l=u(async t=>i?hr||(hr=(async()=>{try{const r=await i.getSettings(t);return e.os(ht(r)),r}catch(e){return Ze(e,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:r,version:n,orgId:a}}),null}finally{hr=null}})(),hr):null,[i,e,r,n,a]);return rr(async e=>{o||bt(t)&&await l(e)},[r,n,a],{onError:e=>Ze(e,{component:"useSaaSSettings",action:"fetchSettings",metadata:{serverUrl:r,version:n,orgId:a}})}),s(()=>({settings:o,getSettings:l}),[o,l])}class br extends fr{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(){return this.fetchJson("workspaces",{},"Failed to fetch workspaces")}async createWorkspace(e){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e)},"Failed to create workspace")}async updateWorkspace(e,t){return this.fetchJson(`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,r){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r)},"Failed to update user")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,t,r){return this.fetchJson(`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(`workspaces/${e}`,{},"Failed to fetch workspace")}async getProfile(){return this.fetchJson("profile",{},"Failed to fetch profile")}async updateUserProfile(e){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e)},"Failed to update user profile")}async getCurrentSubscription(e){const t=await this.fetchResponse(`workspaces/${e}/subscription`);if(!t.ok){let e="Failed to fetch subscription";try{e=(await t.json()).message||e}catch{e=404===t.status?"Workspace not found or no subscription available":401===t.status?"Unauthorized - Please check your session":`Failed to fetch subscription (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch subscription");return r.data||r}return r}async getPlanGroup(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/plan-group`);if(!t.ok){let e="Failed to fetch plan group";try{e=(await t.json()).message||e}catch{e=404===t.status?"No plan group found for this workspace":401===t.status?"Unauthorized - Please check your session":`Failed to fetch plan group (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch plan group");return r.data||r}return r}async getPlanGroupByVersion(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/plan-group?groupVersionId=${t}`);if(!r.ok){let e="Failed to fetch plan group version";try{e=(await r.json()).message||e}catch{e=404===r.status?"Plan group version not found":401===r.status?"Unauthorized - Please check your session":`Failed to fetch plan group version (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to fetch plan group version");return n.data||n}return n}async getPlanGroupVersions(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/plan-group/versions`);if(!t.ok){let e="Failed to fetch plan group versions";try{e=(await t.json()).message||e}catch{e=404===t.status?"No plan group versions found":401===t.status?"Unauthorized - Please check your session":`Failed to fetch plan group versions (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch plan group versions");return r.data||r}return r}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const t=await this.fetchResponse(`${this.orgId}/plans/${encodeURIComponent(e)}`);if(!t.ok){let r="Failed to fetch plans";try{r=(await t.json()).message||r}catch{r=404===t.status?`Plans "${e}" not found`:`Failed to fetch plans (${t.status}: ${t.statusText})`}throw new Error(r)}const r=await t.json();if(void 0!==r.success&&!r.success)throw new Error(r.message||"Failed to fetch plans");return r.data??r}async getPlanGroupVersion(e){const t=await this.fetchResponse(`plan-group-versions/${e}`);if(!t.ok){let e="Failed to fetch plan group version";try{e=(await t.json()).message||e}catch{e=404===t.status?"Plan group version not found":401===t.status?"Unauthorized - Please check your session":`Failed to fetch plan group version (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch plan group version");return r.data||r}return r}async createCheckoutSession(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});if(!r.ok){let e="Failed to create checkout session";try{e=(await r.json()).message||e}catch{e=`Failed to create checkout session (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to create checkout session");return n.data||n}return n}async updateSubscription(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});if(!r.ok){let e="Failed to update subscription";try{e=(await r.json()).message||e}catch{e=`Failed to update subscription (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to update subscription");return n.data?.checkoutUrl||n.checkoutUrl,n.data||n}return n.checkoutUrl,n}async createBillingPortalSession(e,t){return this.fetchJson(`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,r){const n=new URLSearchParams;n.append("limit",t.toString()),r&&n.append("starting_after",r);const a=await this.fetchResponse(`workspaces/${e}/subscription/invoices?${n.toString()}`,{});if(!a.ok){let e="Failed to fetch invoices";try{e=(await a.json()).message||e}catch{e=404===a.status?"Workspace not found or no invoices available":401===a.status?"Unauthorized - Please check your session":`Failed to fetch invoices (${a.status}: ${a.statusText})`}throw new Error(e)}const o=await a.json();if(void 0!==o.success){if(!o.success)throw new Error(o.message||"Failed to fetch invoices");return o}return o}async getInvoice(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/invoices/${t}`,{});if(!r.ok){let e="Failed to fetch invoice";try{e=(await r.json()).message||e}catch{e=404===r.status?"Invoice not found":401===r.status?"Unauthorized - Please check your session":`Failed to fetch invoice (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to fetch invoice");return n}return n}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});if(!t.ok){let e="Failed to cancel subscription";try{e=(await t.json()).message||e}catch{e=404===t.status?"Subscription not found":401===t.status?"Unauthorized - Please check your session":`Failed to cancel subscription (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to cancel subscription");return r.data||r}return r}async resumeSubscription(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/resume`,{method:"POST"});if(!t.ok){let e="Failed to resume subscription";try{e=(await t.json()).message||e}catch{e=404===t.status?"Subscription not found":401===t.status?"Unauthorized - Please check your session":`Failed to resume subscription (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to resume subscription");return r.data||r}return r}async recordUsage(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});if(!r.ok){let e="Failed to record usage";try{e=(await r.json()).message||e}catch{e=`Failed to record usage (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to record usage");return n.data||n}return n}async getQuotaUsageStatus(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/usage/status?quotaSlug=${encodeURIComponent(t)}`);if(!r.ok){let e="Failed to fetch quota usage status";try{e=(await r.json()).message||e}catch{e=404===r.status?"Workspace not found or no subscription available":401===r.status?"Unauthorized - Please check your session":`Failed to fetch quota usage status (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to fetch quota usage status");return n.data||n}return n}async getAllQuotaUsage(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/usage/all`);if(!t.ok){let e="Failed to fetch all quota usage";try{e=(await t.json()).message||e}catch{e=404===t.status?"Workspace not found or no subscription available":401===t.status?"Unauthorized - Please check your session":`Failed to fetch all quota usage (${t.status}: ${t.statusText})`}throw new Error(e)}const r=await t.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch all quota usage");return r.data||r}return r}async getUsageLogs(e,t){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const n=r.toString(),a=`workspaces/${e}/subscription/usage/logs${n?`?${n}`:""}`,o=await this.fetchResponse(a);if(!o.ok){let e="Failed to fetch usage logs";try{e=(await o.json()).message||e}catch{e=404===o.status?"Workspace not found":401===o.status?"Unauthorized - Please check your session":`Failed to fetch usage logs (${o.status}: ${o.statusText})`}throw new Error(e)}const i=await o.json();if(void 0!==i.success){if(!i.success)throw new Error(i.message||"Failed to fetch usage logs");return i.data||i}return i}}const yr="saas-workspace-current",vr=e=>{e?ar(yr,e._id):or(yr)},wr=()=>nr(yr),xr=()=>{or(yr)},Sr=(e,t)=>!!e&&t.some(t=>t._id===e);function kr(e,t){if(!t)return!1;const r=(n=e.createdBy)?"string"==typeof n?n:"object"==typeof n&&"_id"in n&&"string"==typeof n._id?n._id:null:null;var n;return null!==r&&r===t}function Nr(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const r=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return r&&"object"==typeof r&&"role"in r&&"string"==typeof r.role?r.role:null}function Cr(){const e=pr(),t=function(e){return s(()=>new br(e),[e.serverUrl,e.version,e.orgId])}(e);return s(()=>({os:e,api:t}),[e,t])}const Er=()=>{const e=Jr(),{os:t,api:r}=Cr(),{settings:n}=gr(),o=qr(e=>e.workspaces),i=qr(e=>e.auth.session?.user),s=u((t,r)=>{if((!(t._id===o.currentWorkspace?._id)||r?.forceEmit)&&t){const r=o.currentWorkspace;vr(t),e.workspaces(Pt(t)),tr.emitWorkspaceChanged(t,r).catch(e=>{He(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceChanged",metadata:{workspaceId:t._id}})})}},[o.currentWorkspace,e]),l=u(async(r,n)=>{const a=++p.current;e.workspaces(Ut(r._id));try{const e=t.auth?.callbacks?.onWorkspaceChange;if(e){const t=Nr(r,i?.id);try{await e({workspace:r,user:i??null,role:t})}catch(e){throw He(e,{component:"useSaaSWorkspaces",action:"onWorkspaceChange",metadata:{workspaceId:r._id}}),e}if(a!==p.current)return}s(r,n)}finally{a===p.current&&e.workspaces(Ut(null))}},[e,t.auth?.callbacks?.onWorkspaceChange,s,i]);d(()=>{if(!o.isInitialized){const t=wr();if(e.workspaces(It(!0)),t){const e=o.workspaces.find(e=>e._id===t);e&&l(e,{forceEmit:!0}).catch(()=>{})}}},[o.isInitialized,o.workspaces,o.currentWorkspace,e,l]);const c=u(()=>{xr(),e.workspaces(Rt())},[e]),f=a.useRef(!1),m=a.useRef(!1),p=a.useRef(0),h=u(async()=>{if(!o.loading&&!f.current){f.current=!0,e.workspaces(Ot(!0)),e.workspaces(Dt(null));try{const t=await r.getWorkspaces();if(e.workspaces(Ct(t)),t.length>0){const e=wr();if(e&&Sr(e,t)){const r=t.find(t=>t._id===e);if(r)try{await l(r,{forceEmit:!0})}catch{}}else{const e=t[0];try{await l(e,{forceEmit:!0})}catch{}}}}catch(t){e.workspaces(Dt(t instanceof Error?t.message:"Failed to fetch workspaces"))}finally{e.workspaces(Ot(!1)),f.current=!1}}},[r,o.loading,e,l]),g=u(async()=>{if(!o.refreshing&&!f.current){f.current=!0,e.workspaces(Mt(!0));try{const t=await r.getWorkspaces();e.workspaces(Ct(t))}catch(e){}finally{e.workspaces(Mt(!1)),f.current=!1}}},[r,o.refreshing,e]),b=u(async(t,n)=>{const a=await r.createWorkspace({name:t,image:n});e.workspaces(Et(a)),tr.emitWorkspaceCreated(a).catch(e=>{He(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceCreated",metadata:{workspaceId:a._id}})})},[r,e]),y=u(async(t,n)=>{const a=await r.updateWorkspace(t._id,n);e.workspaces(At(a)),tr.emitWorkspaceUpdated(a).catch(e=>{He(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceUpdated",metadata:{workspaceId:a._id}})})},[r,e]),v=u(async()=>{if(m.current)return o.allFeatures.length>0?o.allFeatures:null;if(o.allFeatures.length>0)return o.allFeatures;m.current=!0;try{const t=await r.getFeatures();return e.workspaces(Tt(t)),t}catch(e){return He(e,{component:"useSaaSWorkspaces",action:"getFeatures"}),null}finally{m.current=!1}},[r,e,o.allFeatures]),w=u(async(e,t,n)=>await r.updateFeature(e,t,n),[r]);d(()=>{if(!o.currentWorkspace?._id||0===o.workspaces.length)return;const t=o.currentWorkspace._id,r=o.workspaces.find(e=>e._id===t);if(r)r!==o.currentWorkspace&&(vr(r),e.workspaces(Pt(r)));else if(o.workspaces.length>0){const e=o.workspaces[0];e._id!==t&&l(e).catch(()=>{})}},[o.workspaces,o.currentWorkspace,e,l]);const x=u(async e=>await r.getWorkspaceUsers(e),[r]),S=u(async(e,t,a)=>{const i=o.workspaces.find(t=>t._id===e);if(i){const e=Yt({settingsMaxUsers:n?.workspace?.maxWorkspaceUsers}),t=Xt({memberCount:i.users?.length??0,maxUsersConfig:e});if(!t.canInvite)throw new Error(t.blockMessage||"Member limit reached")}const s=await r.addUser(e,{email:t,role:a});return i&&tr.emitWorkspaceUserAdded(s.userId,i,a).catch(t=>{He(t,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserAdded",metadata:{workspaceId:e,userId:s.userId,role:a}})}),g().catch(()=>{}),er(),s},[r,o.workspaces,g,n]),k=u(async(e,t)=>{const n=o.workspaces.find(t=>t._id===e);if(n&&kr(n,t))throw new Error("Cannot remove the workspace owner");const a=(await r.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t),i=await r.removeUser(e,t);if(n&&a){const t=a.role;tr.emitWorkspaceUserRemoved(i.userId,n,t).catch(r=>{He(r,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserRemoved",metadata:{workspaceId:e,userId:i.userId,role:t}})})}return g().catch(()=>{}),er(),i},[r,o.workspaces,g]),N=u(async(e,t,n)=>{if(n.role){const r=o.workspaces.find(t=>t._id===e);if(r&&kr(r,t))throw new Error("Cannot change the role of the workspace owner")}let a;if(n.role){const n=(await r.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t);a=n?.role}const i=await r.updateUser(e,t,n);return n.role&&a&&a!==n.role&&tr.emitWorkspaceUserRoleChanged(i.userId,i.workspace,a,n.role).catch(r=>{He(r,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserRoleChanged",metadata:{workspaceId:e,userId:t,previousRole:a,newRole:n.role}})}),i},[r,o.workspaces]),C=u(async e=>{const t=await r.getProfile().catch(()=>null),n=await r.updateUserProfile(e);return tr.emitUserUpdated(n,t||void 0).catch(e=>{He(e,{component:"useSaaSWorkspaces",action:"emitUserUpdated",metadata:{userId:n._id}})}),n},[r]),E=u(async()=>await r.getProfile(),[r]),A=u(async e=>await r.getWorkspace(e),[r]),_=u(async t=>{if(!i)throw new Error("User must be authenticated to delete a workspace");const n=o.workspaces.find(e=>e._id===t);if(!n)throw new Error("Workspace not found");if(!kr(n,i.id))throw new Error("Only the workspace creator can delete the workspace");const a=await r.deleteWorkspace(t);return e.workspaces(_t(t)),o.currentWorkspace?._id===t&&(xr(),e.workspaces(Rt())),n&&tr.emitWorkspaceDeleted(n).catch(e=>{He(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceDeleted",metadata:{workspaceId:t}})}),a},[r,o.workspaces,o.currentWorkspace,e,i]);return{workspaces:o.workspaces,loading:o.loading,error:o.error,fetchWorkspaces:h,refreshWorkspaces:g,refreshing:o.refreshing,currentWorkspace:o.currentWorkspace,setCurrentWorkspace:s,switchToWorkspace:l,resetCurrentWorkspace:c,createWorkspace:b,allFeatures:o.allFeatures,getFeatures:v,updateFeature:w,getWorkspace:A,updateWorkspace:y,getUsers:x,addUser:S,removeUser:k,updateUser:N,getProfile:E,updateUserProfile:C,deleteWorkspace:_,switching:null!==o.switchingToId,switchingToId:o.switchingToId}},Ar=new Set;function _r(){Ar.forEach(e=>e())}const Tr=e=>{const{os:t,api:r}=Cr(),n=bt(t),[a,o]=f(null),[i,s]=f(!1),[l,c]=f(null),m=u(async()=>{if(e&&n){s(!0),c(null);try{const t=await r.getPublicPlans(e);o(t)}catch(t){const r=t instanceof Error?t.message:"Failed to fetch plans";c(r),He(t,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{s(!1)}}else o(null)},[r,e,n]);d(()=>{m()},[m]);const p=e&&!n||i;return{items:a?.items??[],plans:a?.plans??[],notes:a?.notes,loading:p,error:l,refetch:m}},Pr=e=>{const{api:t}=Cr(),[r,n]=f(null),[a,o]=f(!1),[i,s]=f(null),l=u(async()=>{if(e){o(!0),s(null);try{const r=await t.getPlanGroupVersion(e);n(r)}catch(t){const r=t instanceof Error?t.message:"Failed to fetch plan group version";s(r),He(t,{component:"usePublicPlanGroupVersion",action:"fetchVersion",metadata:{groupVersionId:e}})}finally{o(!1)}}else n(null)},[t,e]);return d(()=>{l()},[l]),{planGroupVersion:r,loading:a,error:i,refetch:l}},Rr=e=>{const{api:t}=Cr(),[r,n]=f(null),[a,o]=f(!1),[i,s]=f(null),l=u(async()=>{if(e){o(!0),s(null);try{const r=await t.getCurrentSubscription(e);n(r)}catch(t){const r=t instanceof Error?t.message:"Failed to fetch subscription";s(r),He(t,{component:"useSubscription",action:"fetchSubscription",metadata:{workspaceId:e}})}finally{o(!1)}}else n(null)},[t,e]);return d(()=>{l()},[l]),{subscription:r,loading:a,error:i,refetch:l}},Ir=(e,t)=>{const{api:r}=Cr(),[n,a]=f(null),[o,i]=f(!1),[s,l]=f(null),c=u(async()=>{if(e){i(!0),l(null);try{const n=t?await r.getPlanGroupByVersion(e,t):await r.getPlanGroup(e);a(n)}catch(r){const n=r instanceof Error?r.message:"Failed to fetch plan group";l(n),He(r,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:t}})}finally{i(!1)}}else a(null)},[r,e,t]);return d(()=>{c()},[c]),{planGroup:n,loading:o,error:s,refetch:c}},Or=e=>{const{api:t}=Cr(),[r,n]=f(null),[a,o]=f(!1),[i,s]=f(null),l=u(async()=>{if(e){o(!0),s(null);try{const r=await t.getPlanGroupVersions(e);n(r)}catch(t){const r=t instanceof Error?t.message:"Failed to fetch plan group versions";s(r),He(t,{component:"usePlanGroupVersions",action:"fetchVersions",metadata:{workspaceId:e}})}finally{o(!1)}}else n(null)},[t,e]);return d(()=>{l()},[l]),{versions:r,loading:a,error:i,refetch:l}},Dr=e=>{const{api:t}=Cr(),[r,n]=f(!1),[a,o]=f(null);return{createCheckoutSession:u(async r=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const n=await t.createCheckoutSession(e,r);return"trial_started"===n.type&&(er(),_r()),n}catch(t){const n=t instanceof Error?t.message:"Failed to create checkout session";throw o(n),He(t,{component:"useCreateCheckoutSession",action:"createCheckoutSession",metadata:{workspaceId:e,request:r}}),t}finally{n(!1)}},[t,e]),loading:r,error:a}},Mr=e=>{const{api:t}=Cr(),[r,n]=f(!1),[a,o]=f(null),i=u(async(r,a)=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const n={planVersionId:r,...a?.billingInterval&&{billingInterval:a.billingInterval},...a?.successUrl&&{successUrl:a.successUrl},...a?.cancelUrl&&{cancelUrl:a.cancelUrl}},o=await t.updateSubscription(e,n);return er(),o}catch(t){const n=t instanceof Error?t.message:"Failed to update subscription";throw o(n),He(t,{component:"useUpdateSubscription",action:"updateSubscription",metadata:{workspaceId:e,planVersionId:r,options:a}}),t}finally{n(!1)}},[t,e]);return{updateSubscription:i,loading:r,error:a}},Ur=(e,t)=>{const r=Rr(e),n=Ir(e,t),a=Mr(e),o=u(async()=>{await Promise.all([r.refetch(),n.refetch()])},[r.refetch,n.refetch]);return{subscription:r.subscription,planGroup:n.planGroup,loading:r.loading||n.loading||a.loading,error:r.error||n.error||a.error,updateSubscription:a.updateSubscription,refetch:o}},zr=(e,t=10,r)=>{const{api:n}=Cr(),[a,o]=f([]),[i,s]=f(!1),[l,c]=f(!1),[m,p]=f(null),h=u(async()=>{if(!e)return o([]),void s(!1);c(!0),p(null);try{const a=await n.listInvoices(e,t,r);o(a.invoices||[]),s(a.has_more||!1)}catch(n){const a=n instanceof Error?n.message:"Failed to fetch invoices";p(a),He(n,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:t,startingAfter:r}})}finally{c(!1)}},[n,e,t,r]);return d(()=>{h()},[h]),{invoices:a,hasMore:i,loading:l,error:m,refetch:h}},Fr=e=>{const{api:t}=Cr(),[r,n]=f(!1),[a,o]=f(null);return{openBillingPortal:u(async r=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const n=r||window.location.href,a=await t.createBillingPortalSession(e,n);return a.url&&window.open(a.url,"_blank","noopener,noreferrer"),a}catch(t){const r=t instanceof Error?t.message:"Failed to open billing portal";throw o(r),He(t,{component:"useBillingPortal",action:"openBillingPortal",metadata:{workspaceId:e}}),t}finally{n(!1)}},[e,t]),loading:r,error:a}},Lr=(e,t)=>{const{api:r}=Cr(),[n,a]=f(null),[o,i]=f(!1),[s,l]=f(null),c=u(async()=>{if(e&&t){i(!0),l(null);try{const n=await r.getInvoice(e,t);a(n.invoice)}catch(r){const n=r instanceof Error?r.message:"Failed to fetch invoice";l(n),He(r,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:t}})}finally{i(!1)}}else a(null)},[r,e,t]);return d(()=>{c()},[c]),{invoice:n,loading:o,error:s,refetch:c}},$r=e=>{const{api:t}=Cr(),[r,n]=f(!1),[a,o]=f(null);return{cancelSubscription:u(async()=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const r=await t.cancelSubscriptionAtPeriodEnd(e);return er(),r}catch(t){const r=t instanceof Error?t.message:"Failed to cancel subscription";throw o(r),He(t,{component:"useCancelSubscription",action:"cancelSubscription",metadata:{workspaceId:e}}),t}finally{n(!1)}},[t,e]),loading:r,error:a}},Vr=e=>{const{api:t}=Cr(),[r,n]=f(!1),[a,o]=f(null);return{resumeSubscription:u(async()=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const r=await t.resumeSubscription(e);return er(),r}catch(t){const r=t instanceof Error?t.message:"Failed to resume subscription";throw o(r),He(t,{component:"useResumeSubscription",action:"resumeSubscription",metadata:{workspaceId:e}}),t}finally{n(!1)}},[t,e]),loading:r,error:a}},Wr=e=>{const{api:t}=Cr(),[r,n]=f(!1),[a,o]=f(null);return{recordUsage:u(async r=>{if(!e)throw new Error("Workspace ID is required");n(!0),o(null);try{const n=await t.recordUsage(e,r);return _r(),n}catch(t){const n=t instanceof Error?t.message:"Failed to record usage";throw o(n),He(t,{component:"useRecordUsage",action:"recordUsage",metadata:{workspaceId:e,request:r}}),t}finally{n(!1)}},[t,e]),loading:r,error:a}},jr=(e,t)=>{const{api:r}=Cr(),[n,a]=f(null),[o,i]=f(!1),[s,l]=f(null),c=u(async()=>{if(e&&t){i(!0),l(null);try{const n=await r.getQuotaUsageStatus(e,t);a(n)}catch(r){const n=r instanceof Error?r.message:"Failed to fetch quota usage status";l(n),He(r,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:t}})}finally{i(!1)}}else a(null)},[r,e,t]);return d(()=>{c()},[c]),{status:n,loading:o,error:s,refetch:c}},Br=e=>{const{api:t}=Cr(),[r,n]=f(null),[a,o]=f(!1),[i,s]=f(null),l=u(async()=>{if(e){o(!0),s(null);try{const r=await t.getAllQuotaUsage(e);n(r.quotas)}catch(t){const r=t instanceof Error?t.message:"Failed to fetch all quota usage";s(r),He(t,{component:"useAllQuotaUsage",action:"fetchAllUsage",metadata:{workspaceId:e}})}finally{o(!1)}}else n(null)},[t,e]);return d(()=>{l()},[l]),{quotas:r,loading:a,error:i,refetch:l}},Gr=(e,t,r)=>{const{api:n}=Cr(),[a,o]=f([]),[i,s]=f(0),[l,c]=f(0),[m,p]=f(1),[h,g]=f(!1),[b,y]=f(!1),[v,w]=f(!1),[x,S]=f(null),k=r?.from,N=r?.to,C=r?.source,E=r?.page,A=r?.limit,_=u(async()=>{if(!e)return o([]),s(0),c(0),p(1),g(!1),void y(!1);w(!0),S(null);try{const r={...t&&{quotaSlug:t},...k&&{from:k},...N&&{to:N},...C&&{source:C},...E&&{page:E},...A&&{limit:A}},a=await n.getUsageLogs(e,r);o(a.docs||[]),s(a.totalDocs||0),c(a.totalPages||0),p(a.page||1),g(a.hasNextPage||!1),y(a.hasPrevPage||!1)}catch(r){const n=r instanceof Error?r.message:"Failed to fetch usage logs";S(n),He(r,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:t}})}finally{w(!1)}},[n,e,t,k,N,C,E,A]);return d(()=>{_()},[_]),{logs:a,totalDocs:i,totalPages:l,page:m,hasNextPage:h,hasPrevPage:b,loading:v,error:x,refetch:_}},Kr=l(null);Kr.displayName="SubscriptionContext";const Hr=a.memo(function({children:e}){const{currentWorkspace:r}=Er(),{subscription:n,loading:a,error:o,refetch:i}=Rr(r?._id);d(()=>{return e=i,Qt.add(e),()=>{Qt.delete(e)};var e},[i]);const l=s(()=>({response:n,loading:a,error:o,refetch:i}),[n,a,o,i]);return t(Kr.Provider,{value:l,children:e})});function Zr(){const e=m(Kr);if(null===e)throw new Error("useSubscriptionContext must be used within SubscriptionContextProvider. Make sure SubscriptionContextProvider is wrapping your application (or the tree that uses subscription gates).");return e}function qr(e,t){const r=kt(),n=ft(),a=Vt(),o=e||(e=>e);return tt(s(()=>({os:r,auth:n,workspaces:a}),[r,n,a]),o,t)}function Jr(){const e=mt(),t=Nt(),r=Wt();return s(()=>({auth:e,os:t,workspaces:r}),[e,t,r])}Hr.displayName="SubscriptionContextProvider";const Yr=l(null);Yr.displayName="QuotaUsageContext";const Xr=a.memo(function({children:e}){const{currentWorkspace:r}=Er(),{quotas:n,loading:a,error:o,refetch:i}=Br(r?._id);d(()=>{return e=i,Ar.add(e),()=>{Ar.delete(e)};var e},[i]);const l=s(()=>({quotas:n,loading:a,error:o,refetch:i}),[n,a,o,i]);return t(Yr.Provider,{value:l,children:e})});function Qr(){const e=m(Yr);if(null===e)throw new Error("useQuotaUsageContext must be used within QuotaUsageContextProvider. Make sure QuotaUsageContextProvider is wrapping your application (or the tree that uses quota gates).");return e}Xr.displayName="QuotaUsageContextProvider";class en extends fr{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let e="Failed to initiate authentication";try{e=(await r.json()).message||e}catch{e=`Failed to initiate authentication (${r.status}: ${r.statusText})`}throw new Error(e)}return r.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}}const tn=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:"profile"}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getState(){return{...this.currentState}}openWorkspaceSettings(e){this.currentState={open:!0,section:e||"profile"},this.notifyListeners()}closeSettings(){this.currentState={...this.currentState,open:!1},this.notifyListeners()}setSection(e){this.currentState={...this.currentState,section:e},this.notifyListeners()}notifyListeners(){this.listeners.forEach(e=>{e(this.currentState.open,this.currentState.section)})}};function rn(e,t,r){const n=e._id||e.id;if(!n||"string"!=typeof n)throw new Error("User data missing required ID field");if(!e.email||"string"!=typeof e.email)throw new Error("User data missing required email field");return{id:n,name:e.name||"",org:t,email:e.email,emailVerified:!0,clientId:r,role:e.role||"",image:e.image}}function nn(e,t){return{user:e,sessionId:t,expires:new Date(Date.now()+864e5).toISOString()}}function an(){return qr(e=>e.auth)}function on(){const e=Jr(),t=an(),r=pr(),{serverUrl:n,orgId:a,auth:o}=r,{resetCurrentWorkspace:i,currentWorkspace:l}=Er(),c=s(()=>new en({serverUrl:n,version:r.version}),[n,r.version]),d=u(async()=>{e.auth(Je());try{const t=await c.requestAuth({orgId:a,clientId:o?.clientId??"",redirect:{success:o?.redirectUrl||window.location.href,error:o?.redirectUrl||window.location.href}});if(!t.success)throw e.auth(Xe()),new Error(t.message||"Authentication failed");window.location.href=t.data.redirectUrl}catch(t){throw e.auth(Xe()),He(t,{component:"useSaaSAuth",action:"signIn"}),t}},[c,a,o,e]),f=u(async()=>{try{o?.callbacks?.onSignOut&&"function"==typeof o.callbacks.onSignOut&&await o.callbacks.onSignOut()}catch(e){He(e,{component:"useSaaSAuth",action:"signOut"})}finally{or(ir),e.auth(et()),i()}},[e,i,o?.callbacks?.onSignOut]),m=u(e=>{l?tn.openWorkspaceSettings(e):He(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),p=s(()=>at(t.status),[t.status]);return s(()=>({user:t.session?.user,session:t.session,status:t.status,...p,signIn:d,signOut:f,openWorkspaceSettings:m}),[t.session,t.status,p,d,f,m])}class sn extends fr{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}const ln=l(null);function cn(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r.charCodeAt(e);return n}const dn=a.memo(function({children:e,serviceWorkerPath:r="/push-sw.js",autoSubscribe:n=!1}){const a=pr(),{isAuthenticated:o}=on(),i="undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,l=s(()=>new sn({serverUrl:a.serverUrl,version:a.version,orgId:a.orgId}),[a.serverUrl,a.version,a.orgId]),[c,m]=f({permission:i?Notification.permission:"default",isSubscribed:!1,isSupported:i,loading:!1,error:null});d(()=>{o&&i&&async function(){try{const e=await navigator.serviceWorker.getRegistration(r);if(!e)return void m(e=>({...e,isSubscribed:!1}));const t=await e.pushManager.getSubscription();m(e=>({...e,isSubscribed:!!t,permission:Notification.permission}))}catch{m(e=>({...e,isSubscribed:!1}))}}()},[o,i]);const p=u(async()=>{if(!i)return!1;const e=await Notification.requestPermission();return m(t=>({...t,permission:e})),"granted"===e},[i]),h=u(async()=>{if(i&&o){m(e=>({...e,loading:!0,error:null}));try{if(!await p())return void m(e=>({...e,loading:!1,error:"Notification permission denied"}));const{publicKey:e}=await l.getVapidPublicKey(),t=await navigator.serviceWorker.register(r);await navigator.serviceWorker.ready;const n=(await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:cn(e)})).toJSON();await l.subscribe({endpoint:n.endpoint,keys:{p256dh:n.keys.p256dh,auth:n.keys.auth}},navigator.userAgent),m(e=>({...e,isSubscribed:!0,loading:!1}))}catch(e){const t=e instanceof Error?e.message:"Failed to subscribe to push notifications";m(e=>({...e,loading:!1,error:t})),He(e,{component:"PushNotificationProvider",action:"subscribe"})}}},[i,o,l,r,p]),g=u(async()=>{if(i){m(e=>({...e,loading:!0,error:null}));try{const e=await navigator.serviceWorker.getRegistration(r);if(e){const t=await e.pushManager.getSubscription();if(t){const e=t.endpoint;await t.unsubscribe(),await l.unsubscribe(e)}}m(e=>({...e,isSubscribed:!1,loading:!1}))}catch(e){const t=e instanceof Error?e.message:"Failed to unsubscribe";m(e=>({...e,loading:!1,error:t})),He(e,{component:"PushNotificationProvider",action:"unsubscribe"})}}},[i,l,r]),b=s(()=>({...c,requestPermission:p,subscribe:h,unsubscribe:g}),[c,p,h,g]);return t(ln.Provider,{value:b,children:e})});function un(){const e=m(ln);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e}let fn=!1,mn=null;const pn=a.memo(({children:e,callbacks:n})=>{const o=Jr(),i=an(),l=pr(),c=at(i.status).isAuthenticated,f=a.useRef(!1),m=a.useRef(null);a.useEffect(()=>{c||(fn=!1,mn=null)},[]);const p=s(()=>n,[n]),h=u(async e=>{try{if(p?.handleAuthentication){const{sessionId:t}=await p.handleAuthentication(e);if(!t||"string"!=typeof t||""===t.trim())throw new Error("Invalid sessionId received from authentication callback");const r=l;if(!bt(r))throw new Error("OS configuration is not available");const{serverUrl:n,version:a,orgId:i}=r,s=new en({serverUrl:n,version:a}),c=await s.getProfile(t),d=nn(rn(c,i,r.auth?.clientId||""),t);lr(d.sessionId),o.auth(Qe(d)),function(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.delete(sr),window.history.replaceState({},"",e.toString())}catch(e){He(e,{component:"auth-utils",action:"removeTokenFromUrl",metadata:{param:sr}})}}()}}catch(t){throw He(t,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),o.auth(Xe()),t}},[o,p,l]);return a.useEffect(()=>{if("undefined"==typeof window)return;if(c)return;if(fn)return;if(mn)return;if(!bt(l))return;if(dr())return;if(!p?.getSession)return fn=!0,void o.auth(Xe());const e=p.getSession,{serverUrl:t,version:r,orgId:n}=l,a=l.auth?.clientId||"";mn=(async()=>{let i=null;try{i=await e()}catch(e){He(e,{component:"AuthProviderWrapper",action:"getSession"})}if(!i)return fn=!0,void o.auth(Xe());try{const e=new en({serverUrl:t,version:r}),s=await e.getProfile(i),l=nn(rn(s,n,a),i);lr(l.sessionId),fn=!0,o.auth(Qe(l))}catch(e){He(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}),fn=!0,o.auth(Xe())}finally{mn=null}})()},[c,o,l,p]),d(()=>{const e=dr();if(!e)return;if(f.current||m.current===e)return;if(!bt(l))return;f.current=!0,m.current=e;let t=!1;return o.auth(Ye()),h(e).then(()=>{t||(m.current=null)}).catch(e=>{t||(He(e,{component:"AuthProviderWrapper",action:"handleAuthRedirectEffect",metadata:{hasCode:!0}}),m.current=null)}).finally(()=>{f.current=!1}),()=>{t=!0}},[h,l.serverUrl,l.version,l.orgId]),t(r,{children:e})});pn.displayName="AuthProviderWrapper";const hn=a.memo(({config:e,auth:n,children:o})=>{const i=Jr(),l=pr(),c=a.useMemo(()=>({clientId:n?.clientId||"",redirectUrl:n?.redirectUrl||"",callbacks:n?.callbacks}),[n?.clientId,n?.redirectUrl,n?.callbacks]);d(()=>{i.os(pt({...e,auth:c}))},[e,c,i]);const u=s(()=>bt(l)?new mr(l):null,[l.serverUrl,l.version,l.orgId]);return rr(async e=>{if(!u||l.settings)return;const t=await u.getSettings(e);i.os(ht(t))},[u,l.settings,i],{onError:e=>He(e,{component:"ContextConfigProvider",action:"fetchSettings",metadata:{serverUrl:l.serverUrl,version:l.version,orgId:l.orgId}})}),t(r,{children:o})});hn.displayName="ContextConfigProvider";const gn=l({container:null,setContainer:()=>{}}),bn=a.memo(({children:r})=>{const[n,o]=a.useState(null),i=a.useMemo(()=>({container:n,setContainer:o}),[n]),s=a.useMemo(()=>r,[r]);return e(gn.Provider,{value:i,children:[s,t("div",{ref:o,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});bn.displayName="PortalProvider";class yn extends fr{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});if(!t.ok)throw new Error(await We(t,"Failed to fetch user attributes"));const r=await t.json();return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});if(!t.ok)throw new Error(await We(t,"Failed to fetch user features"));const r=await t.json();return"object"==typeof r&&null!==r?r:{}}}const vn=a.createContext(void 0),wn=a.memo(({children:e})=>{const r=pr(),n=function(){const e=pr();return s(()=>new yn(e),[e.serverUrl,e.version])}(),{isAuthenticated:o}=on(),{serverUrl:i,version:l}=r,[c,d]=f({}),[m,p]=f({}),[h,g]=f(!1),[b,y]=f(null),v=u(async e=>{if(i&&l&&o)try{const t=await n.getAttributes(e);d(t)}catch(e){if(Ve(e))return;const t=e instanceof Error?e:new Error("Failed to fetch user attributes");y(t),He(e,{component:"UserProvider",action:"fetchAttributes"})}else d({})},[n,i,l,o]),w=u(async()=>{if(i&&l&&o){g(!0),y(null);try{await v()}finally{g(!1)}}},[i,l,o,v]),x=u(async e=>{g(!0),y(null);try{const t=await n.updateAttributes(e);return await v(),t}catch(t){const r=t instanceof Error?t:new Error("Failed to update user attributes");throw y(r),He(t,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),t}finally{g(!1)}},[n,v]),S=u(async(e,t)=>{g(!0),y(null);try{const r=await n.updateAttribute(e,t);return await v(),r}catch(r){const n=r instanceof Error?r:new Error("Failed to update user attribute");throw y(n),He(r,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:t}}),r}finally{g(!1)}},[n,v]),k=u(async e=>{if(i&&l&&o)try{const t=await n.getFeatures(e);p(t)}catch(e){if(Ve(e))return;const t=e instanceof Error?e:new Error("Failed to fetch user features");y(t),He(e,{component:"UserProvider",action:"fetchFeatures"})}else p({})},[n,i,l,o]),N=u(async()=>{if(i&&l&&o){g(!0),y(null);try{await k()}finally{g(!1)}}},[i,l,o,k]);rr(async e=>{if(!o||!i||!l)return d({}),void p({});g(!0),y(null);try{await Promise.all([v(e),k(e)])}finally{g(!1)}},[o,i,l,v,k],{onError:e=>He(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const C=a.useMemo(()=>({attributes:c,features:m,isLoading:h,error:b,updateAttributes:x,updateAttribute:S,refreshAttributes:w,refreshFeatures:N}),[c,m,h,b,x,S,w,N]);return t(vn.Provider,{value:C,children:e})});wn.displayName="UserProvider";const xn=h(()=>Promise.resolve().then(function(){return HS}).then(e=>({default:e.default}))),Sn=({children:n})=>{const{currentWorkspace:a}=Er(),[o,i]=f(!1),[s,l]=f("profile");return d(()=>{const e=tn.getState();i(e.open),l(e.section);return tn.subscribe((e,t)=>{i(e),l(t)})},[]),e(r,{children:[n,a&&o&&t(p,{fallback:null,children:t(xn,{workspace:a,open:o,onOpenChange:e=>{e||tn.closeSettings()},section:s,onSectionChange:e=>{tn.setSection(e)},showTrigger:!1})})]})},kn=(e,t,r)=>{if(t!==gt.V1)throw new Error(`Invalid version: "${t}". Only "${gt.V1}" is currently supported.`);if(!e||"string"!=typeof e)throw new Error("serverUrl is required and must be a string");if(!(e=>{try{return new URL(e),!0}catch{return!1}})(e))throw new Error(`Invalid serverUrl: "${e}". Must be a valid URL.`);if(!r||"string"!=typeof r)throw new Error("orgId is required and must be a string");if(!/^[0-9a-fA-F]{24}$/.test(r))throw new Error(`Invalid orgId: "${r}". Must be a valid MongoDB ObjectId (24 hexadecimal characters).`)},Nn=a.memo(({serverUrl:e,version:r,orgId:n,auth:o,children:i})=>{kn(e,r,n);const s=a.useMemo(()=>({serverUrl:e,version:r,orgId:n}),[e,r,n]),l=a.useMemo(()=>o?.callbacks,[o?.callbacks?.handleAuthentication,o?.callbacks?.onSignOut,o?.callbacks?.handleEvent,o?.callbacks?.onWorkspaceChange]),c=o?.callbacks?.handleEvent;return d(()=>(tr.setCallbacks(c?{handleEvent:c}:null),()=>{tr.setCallbacks(null)}),[c]),t(jt,{children:t(pn,{callbacks:l,children:t(bn,{children:t(hn,{config:s,auth:o,children:t(wn,{children:t(Hr,{children:t(Xr,{children:t(dn,{children:t(Sn,{children:i})})})})})})})})})});Nn.displayName="SaaSOSProviderInner";const Cn=({children:e,...r})=>t(qe,{children:t(Nn,{...r,children:e})});Cn.displayName="SaaSOSProvider";const En=e=>{const{children:t}=e,{status:r}=on();return r!==nt.authenticated?null:t},An=e=>{const{children:t}=e,{status:r}=on();return r!==nt.unauthenticated?null:t};En.displayName="WhenAuthenticated",An.displayName="WhenUnauthenticated";const _n=e=>{const{children:t,fallback:r,roles:n}=e,{user:a}=on();return n.includes(a?.role??"")?t:r||null},Tn=e=>{const{children:t,fallback:r,roles:n}=e,{user:a}=on(),{currentWorkspace:o}=Er(),i=o?.users.find(e=>e._id===a?.id);return i&&n.includes(i?.role??"")?t:r||null};function Pn(){const e=m(vn);if(void 0===e)throw new Error("useUserAttributes must be used within a UserProvider");return e}function Rn(){const e=m(vn);if(void 0===e)throw new Error("useUserFeatures must be used within a UserProvider");return{features:e.features,isLoading:e.isLoading,error:e.error,refreshFeatures:e.refreshFeatures,isFeatureEnabled:t=>Boolean(e.features[t])}}_n.displayName="WhenRoles",Tn.displayName="WhenWorkspaceRoles";const In=e=>{const{children:t,slug:r}=e,{currentWorkspace:n}=Er(),a=n?.features?.[r];return a?t:null},On=e=>{const{children:t,slug:r}=e,{currentWorkspace:n}=Er(),a=n?.features?.[r];return a?null:t},Dn=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:n}=Rn();return n(r)?t:null},Mn=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:n}=Rn();return n(r)?null:t};In.displayName="WhenWorkspaceFeatureEnabled",On.displayName="WhenWorkspaceFeatureDisabled",Dn.displayName="WhenUserFeatureEnabled",Mn.displayName="WhenUserFeatureDisabled";const Un=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{response:a,loading:o}=Zr();return o?r??null:a?.subscription?t:n??null},zn=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{response:a,loading:o}=Zr();return o?r??null:a?.subscription?n??null:t},Fn=e=>{const{children:t,plans:r,loadingComponent:n,fallbackComponent:a}=e,{response:o,loading:i}=Zr();if(i)return n??null;if(!o?.subscription)return a??null;const s=o.plan??o.subscription?.plan;if(!s)return a??null;const l=r.map(e=>e.trim().toLowerCase()),c=(s.slug??"").toLowerCase();return l.includes(c)?t:a??null},Ln=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{response:a,loading:o}=Zr();return o?r??null:"trialing"!==a?.subscription?.subscriptionStatus?n??null:t},$n=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{response:a,loading:o}=Zr();return o?r??null:"trialing"===a?.subscription?.subscriptionStatus?n??null:t},Vn=e=>{const{children:t,loadingComponent:r,fallbackComponent:n,daysThreshold:a=3}=e,{response:o,loading:i}=Zr();if(i)return r??null;const s=o?.subscription;if(!s||"trialing"!==s.subscriptionStatus)return n??null;const l=s.trialEnd||s.stripeCurrentPeriodEnd;if(!l)return n??null;const c=new Date(l);if(isNaN(c.getTime()))return n??null;return Math.max(0,Math.ceil((c.getTime()-Date.now())/864e5))>a?n??null:t};Un.displayName="WhenSubscription",zn.displayName="WhenNoSubscription",Fn.displayName="WhenSubscriptionToPlans",Ln.displayName="WhenTrialing",$n.displayName="WhenNotTrialing",Vn.displayName="WhenTrialEnding";const Wn=e=>{const{slug:t,children:r,loadingComponent:n,fallbackComponent:a}=e,{quotas:o,loading:i}=Qr();if(i)return n??null;const s=o?.[t];return s?s.available<=0?a??null:r:a??null},jn=e=>{const{slug:t,children:r,loadingComponent:n,fallbackComponent:a}=e,{quotas:o,loading:i}=Qr();if(i)return n??null;const s=o?.[t];return s?s.available>0?a??null:r:a??null},Bn=e=>{const{slug:t,children:r,loadingComponent:n,fallbackComponent:a}=e,{quotas:o,loading:i}=Qr();if(i)return n??null;const s=o?.[t];return s&&s.hasOverage?r:a??null},Gn=e=>{const{slug:t,threshold:r,children:n,loadingComponent:a,fallbackComponent:o}=e,{quotas:i,loading:s}=Qr();if(s)return a??null;const l=i?.[t];if(!l)return o??null;return(l.included>0?l.consumed/l.included*100:l.consumed>0?100:0)<r?o??null:n};function Kn(e){if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t}function Hn(){const{response:e}=Zr();return s(()=>{const t=e?.subscription;if(!t||"trialing"!==t.subscriptionStatus)return{isTrialing:!1,daysRemaining:0,trialEndsAt:null,trialStartedAt:null,isTrialEnding:!1};const r=Kn(t.trialEnd)??Kn(t.stripeCurrentPeriodEnd),n=Kn(t.trialStart),a=r?Math.max(0,Math.ceil((r.getTime()-Date.now())/864e5)):0;return{isTrialing:!0,daysRemaining:a,trialEndsAt:r,trialStartedAt:n,isTrialEnding:a<=3}},[e])}function Zn(e,t){const{response:r}=Zr();return s(()=>{if(!e)return{hasSeatPricing:!1,memberCount:0,includedSeats:0,maxUsers:0,maxSeats:0,limitSource:"none",billableSeats:0,availableSeats:1/0,isAtMax:!1,isNearMax:!1,perSeatPriceCents:null,currency:"",canInvite:!0,inviteBlockReason:null,inviteBlockMessage:null};const n=e.users?.length??0,a=r?.planVersion,o=r?.subscription,i=e.billingCurrency||"usd",s=Yt({planVersion:a,currency:i,settingsMaxUsers:t?.settingsMaxUsers}),{maxUsers:l,hasSeatPricing:c,includedSeats:d}=s,u=c?Math.max(0,n-d):0,f=l>0?Math.max(0,l-n):1/0,m=l>0&&n>=l,p=l>0&&n>=.8*l&&!m,h=c&&a?Jt(a,i,o?.billingInterval??"monthly"):null,g=Xt({memberCount:n,maxUsersConfig:s});return{hasSeatPricing:c,memberCount:n,includedSeats:d,maxUsers:l,maxSeats:l,limitSource:s.source,billableSeats:u,availableSeats:f,isAtMax:m,isNearMax:p,perSeatPriceCents:h,currency:i,canInvite:g.canInvite,inviteBlockReason:g.blockReason,inviteBlockMessage:g.blockMessage}},[r,e,t?.settingsMaxUsers])}Wn.displayName="WhenQuotaAvailable",jn.displayName="WhenQuotaExhausted",Bn.displayName="WhenQuotaOverage",Gn.displayName="WhenQuotaThreshold";var qn=e=>"checkbox"===e.type,Jn=e=>e instanceof Date,Yn=e=>null==e;const Xn=e=>"object"==typeof e;var Qn=e=>!Yn(e)&&!Array.isArray(e)&&Xn(e)&&!Jn(e),ea=e=>Qn(e)&&e.target?qn(e.target)?e.target.checked:e.target.value:e,ta=(e,t)=>e.has((e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e)(t)),ra="undefined"!=typeof window&&void 0!==window.HTMLElement&&"undefined"!=typeof document;function na(e){if(e instanceof Date)return new Date(e);const t="undefined"!=typeof FileList&&e instanceof FileList;if(ra&&(e instanceof Blob||t))return e;const r=Array.isArray(e);if(!(r||Qn(e)&&(e=>{const t=e.constructor&&e.constructor.prototype;return Qn(t)&&t.hasOwnProperty("isPrototypeOf")})(e)))return e;const n=r?[]:Object.create(Object.getPrototypeOf(e));for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=na(e[t]));return n}var aa=e=>/^\w*$/.test(e),oa=e=>void 0===e,ia=e=>Array.isArray(e)?e.filter(Boolean):[],sa=e=>ia(e.replace(/["|']|\]/g,"").split(/\.|\[/)),la=(e,t,r)=>{if(!t||!Qn(e))return r;const n=(aa(t)?[t]:sa(t)).reduce((e,t)=>Yn(e)?e:e[t],e);return oa(n)||n===e?oa(e[t])?r:e[t]:n},ca=e=>"boolean"==typeof e,da=e=>"function"==typeof e,ua=(e,t,r)=>{let n=-1;const a=aa(t)?[t]:sa(t),o=a.length,i=o-1;for(;++n<o;){const t=a[n];let o=r;if(n!==i){const r=e[t];o=Qn(r)||Array.isArray(r)?r:isNaN(+a[n+1])?{}:[]}if("__proto__"===t||"constructor"===t||"prototype"===t)return;e[t]=o,e=e[t]}};const fa="blur",ma="focusout",pa="change",ha="onBlur",ga="onChange",ba="onSubmit",ya="onTouched",va="all",wa="max",xa="min",Sa="maxLength",ka="minLength",Na="pattern",Ca="required",Ea="validate",Aa=a.createContext(null);Aa.displayName="HookFormControlContext";const _a=()=>a.useContext(Aa);var Ta=(e,t,r,n=!0)=>{const a={defaultValues:t._defaultValues};for(const o in e)Object.defineProperty(a,o,{get:()=>{const a=o;return t._proxyFormState[a]!==va&&(t._proxyFormState[a]=!n||va),r&&(r[a]=!0),e[a]}});return a};const Pa="undefined"!=typeof window?a.useLayoutEffect:a.useEffect;var Ra=e=>"string"==typeof e,Ia=(e,t,r,n,a)=>Ra(e)?(n&&t.watch.add(e),la(r,e,a)):Array.isArray(e)?e.map(e=>(n&&t.watch.add(e),la(r,e))):(n&&(t.watchAll=!0),r),Oa=e=>Yn(e)||!Xn(e);function Da(e,t,r=new WeakSet){if(Oa(e)||Oa(t))return Object.is(e,t);if(Jn(e)&&Jn(t))return Object.is(e.getTime(),t.getTime());const n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length)return!1;if(r.has(e)||r.has(t))return!0;r.add(e),r.add(t);for(const o of n){const n=e[o];if(!a.includes(o))return!1;if("ref"!==o){const e=t[o];if(Jn(n)&&Jn(e)||Qn(n)&&Qn(e)||Array.isArray(n)&&Array.isArray(e)?!Da(n,e,r):!Object.is(n,e))return!1}}return!0}function Ma(e){const t=_a(),{name:r,disabled:n,control:o=t,shouldUnregister:i,defaultValue:s,exact:l=!0}=e,c=ta(o._names.array,r),d=a.useMemo(()=>la(o._formValues,r,la(o._defaultValues,r,s)),[o,r,s]),u=function(e){const t=_a(),{control:r=t,name:n,defaultValue:o,disabled:i,exact:s,compute:l}=e||{},c=a.useRef(o),d=a.useRef(l),u=a.useRef(void 0),f=a.useRef(r),m=a.useRef(n);d.current=l;const[p,h]=a.useState(()=>{const e=r._getWatch(n,c.current);return d.current?d.current(e):e}),g=a.useCallback(e=>{const t=Ia(n,r._names,e||r._formValues,!1,c.current);return d.current?d.current(t):t},[r._formValues,r._names,n]),b=a.useCallback(e=>{if(!i){const t=Ia(n,r._names,e||r._formValues,!1,c.current);if(d.current){const e=d.current(t);Da(e,u.current)||(h(e),u.current=e)}else h(t)}},[r._formValues,r._names,i,n]);Pa(()=>(f.current===r&&Da(m.current,n)||(f.current=r,m.current=n,b()),r._subscribe({name:n,formState:{values:!0},exact:s,callback:e=>{b(e.values)}})),[r,s,n,b]),a.useEffect(()=>r._removeUnmounted());const y=f.current!==r,v=m.current,w=a.useMemo(()=>{if(i)return null;const e=!y&&!Da(v,n);return y||e?g():null},[i,y,n,v,g]);return null!==w?w:p}({control:o,name:r,defaultValue:d,exact:l}),f=function(e){const t=_a(),{control:r=t,disabled:n,name:o,exact:i}=e||{},[s,l]=a.useState(r._formState),c=a.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return Pa(()=>r._subscribe({name:o,formState:c.current,exact:i,callback:e=>{!n&&l({...r._formState,...e})}}),[o,n,i]),a.useEffect(()=>{c.current.isValid&&r._setValid(!0)},[r]),a.useMemo(()=>Ta(s,r,c.current,!1),[s,r])}({control:o,name:r,exact:l}),m=a.useRef(e),p=a.useRef(void 0),h=a.useRef(o.register(r,{...e.rules,value:u,...ca(e.disabled)?{disabled:e.disabled}:{}}));m.current=e;const g=a.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!la(f.errors,r)},isDirty:{enumerable:!0,get:()=>!!la(f.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!la(f.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!la(f.validatingFields,r)},error:{enumerable:!0,get:()=>la(f.errors,r)}}),[f,r]),b=a.useCallback(e=>h.current.onChange({target:{value:ea(e),name:r},type:pa}),[r]),y=a.useCallback(()=>h.current.onBlur({target:{value:la(o._formValues,r),name:r},type:fa}),[r,o._formValues]),v=a.useCallback(e=>{const t=la(o._fields,r);t&&t._f&&e&&(t._f.ref={focus:()=>da(e.focus)&&e.focus(),select:()=>da(e.select)&&e.select(),setCustomValidity:t=>da(e.setCustomValidity)&&e.setCustomValidity(t),reportValidity:()=>da(e.reportValidity)&&e.reportValidity()})},[o._fields,r]),w=a.useMemo(()=>({name:r,value:u,...ca(n)||f.disabled?{disabled:f.disabled||n}:{},onChange:b,onBlur:y,ref:v}),[r,n,f.disabled,b,y,v,u]);return a.useEffect(()=>{const e=o._options.shouldUnregister||i,t=p.current;t&&t!==r&&!c&&o.unregister(t),o.register(r,{...m.current.rules,...ca(m.current.disabled)?{disabled:m.current.disabled}:{}});const n=(e,t)=>{const r=la(o._fields,e);r&&r._f&&(r._f.mount=t)};if(n(r,!0),e){const e=na(la(o._options.defaultValues,r,m.current.defaultValue));ua(o._defaultValues,r,e),oa(la(o._formValues,r))&&ua(o._formValues,r,e)}return!c&&o.register(r),p.current=r,()=>{(c?e&&!o._state.action:e)?o.unregister(r):n(r,!1)}},[r,o,c,i]),a.useEffect(()=>{o._setDisabledField({disabled:n,name:r})},[n,r,o]),a.useMemo(()=>({field:w,formState:f,fieldState:g}),[w,f,g])}const Ua=e=>e.render(Ma(e)),za=a.createContext(null);za.displayName="HookFormContext";const Fa=e=>{const{children:t,watch:r,getValues:n,getFieldState:o,setError:i,clearErrors:s,setValue:l,trigger:c,formState:d,resetField:u,reset:f,handleSubmit:m,unregister:p,control:h,register:g,setFocus:b,subscribe:y}=e;return a.createElement(za.Provider,{value:a.useMemo(()=>({watch:r,getValues:n,getFieldState:o,setError:i,clearErrors:s,setValue:l,trigger:c,formState:d,resetField:u,reset:f,handleSubmit:m,unregister:p,control:h,register:g,setFocus:b,subscribe:y}),[s,h,d,o,n,m,g,f,u,i,b,l,y,c,p,r])},a.createElement(Aa.Provider,{value:h},t))};var La=(e,t,r,n,a)=>t?{...r[e],types:{...r[e]&&r[e].types?r[e].types:{},[n]:a||!0}}:{},$a=e=>Array.isArray(e)?e:[e],Va=()=>{let e=[];return{get observers(){return e},next:t=>{for(const r of e)r.next&&r.next(t)},subscribe:t=>(e.push(t),{unsubscribe:()=>{e=e.filter(e=>e!==t)}}),unsubscribe:()=>{e=[]}}};function Wa(e,t){const r={};for(const n in e)if(e.hasOwnProperty(n)){const a=e[n],o=t[n];if(a&&Qn(a)&&o){const e=Wa(a,o);Qn(e)&&(r[n]=e)}else e[n]&&(r[n]=o)}return r}var ja=e=>Qn(e)&&!Object.keys(e).length,Ba=e=>"file"===e.type,Ga=e=>{if(!ra)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Ka=e=>"select-multiple"===e.type,Ha=e=>"radio"===e.type,Za=e=>Ga(e)&&e.isConnected;function qa(e,t){const r=Array.isArray(t)?t:aa(t)?[t]:sa(t),n=1===r.length?e:function(e,t){const r=t.slice(0,-1).length;let n=0;for(;n<r;)e=oa(e)?n++:e[t[n++]];return e}(e,r),a=r.length-1,o=r[a];return n&&delete n[o],0!==a&&(Qn(n)&&ja(n)||Array.isArray(n)&&function(e){for(const t in e)if(e.hasOwnProperty(t)&&!oa(e[t]))return!1;return!0}(n))&&qa(e,r.slice(0,-1)),e}function Ja(e){return Array.isArray(e)||Qn(e)&&!(e=>{for(const t in e)if(da(e[t]))return!0;return!1})(e)}function Ya(e,t={}){for(const r in e){const n=e[r];Ja(n)?(t[r]=Array.isArray(n)?[]:{},Ya(n,t[r])):oa(n)||(t[r]=!0)}return t}function Xa(e,t,r){r||(r=Ya(t));for(const n in e){const a=e[n];if(Ja(a))oa(t)||Oa(r[n])?r[n]=Ya(a,Array.isArray(a)?[]:{}):Xa(a,Yn(t)?{}:t[n],r[n]);else{const e=t[n];r[n]=!Da(a,e)}}return r}const Qa={value:!1,isValid:!1},eo={value:!0,isValid:!0};var to=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(e=>e&&e.checked&&!e.disabled).map(e=>e.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!oa(e[0].attributes.value)?oa(e[0].value)||""===e[0].value?eo:{value:e[0].value,isValid:!0}:eo:Qa}return Qa},ro=(e,{valueAsNumber:t,valueAsDate:r,setValueAs:n})=>oa(e)?e:t?""===e?NaN:e?+e:e:r&&Ra(e)?new Date(e):n?n(e):e;const no={isValid:!1,value:null};var ao=e=>Array.isArray(e)?e.reduce((e,t)=>t&&t.checked&&!t.disabled?{isValid:!0,value:t.value}:e,no):no;function oo(e){const t=e.ref;return Ba(t)?t.files:Ha(t)?ao(e.refs).value:Ka(t)?[...t.selectedOptions].map(({value:e})=>e):qn(t)?to(e.refs).value:ro(oa(t.value)?e.ref.value:t.value,e)}var io=e=>e instanceof RegExp,so=e=>oa(e)?e:io(e)?e.source:Qn(e)?io(e.value)?e.value.source:e.value:e,lo=e=>({isOnSubmit:!e||e===ba,isOnBlur:e===ha,isOnChange:e===ga,isOnAll:e===va,isOnTouch:e===ya});const co="AsyncFunction";var uo=e=>!!e&&!!e.validate&&!!(da(e.validate)&&e.validate.constructor.name===co||Qn(e.validate)&&Object.values(e.validate).find(e=>e.constructor.name===co)),fo=(e,t,r)=>!r&&(t.watchAll||t.watch.has(e)||[...t.watch].some(t=>e.startsWith(t)&&/^\.\w+/.test(e.slice(t.length))));const mo=(e,t,r,n)=>{for(const a of r||Object.keys(e)){const r=la(e,a);if(r){const{_f:e,...o}=r;if(e){if(e.refs&&e.refs[0]&&t(e.refs[0],a)&&!n)return!0;if(e.ref&&t(e.ref,e.name)&&!n)return!0;if(mo(o,t))break}else if(Qn(o)&&mo(o,t))break}}};function po(e,t,r){const n=la(e,r);if(n||aa(r))return{error:n,name:r};const a=r.split(".");for(;a.length;){const n=a.join("."),o=la(t,n),i=la(e,n);if(o&&!Array.isArray(o)&&r!==n)return{name:r};if(i&&i.type)return{name:n,error:i};if(i&&i.root&&i.root.type)return{name:`${n}.root`,error:i.root};a.pop()}return{name:r}}var ho=(e,t,r)=>{const n=$a(la(e,r));return ua(n,"root",t[r]),ua(e,r,n),e};function go(e,t,r="validate"){if(Ra(e)||Array.isArray(e)&&e.every(Ra)||ca(e)&&!e)return{type:r,message:Ra(e)?e:"",ref:t}}var bo=e=>Qn(e)&&!io(e)?e:{value:e,message:""},yo=async(e,t,r,n,a,o)=>{const{ref:i,refs:s,required:l,maxLength:c,minLength:d,min:u,max:f,pattern:m,validate:p,name:h,valueAsNumber:g,mount:b}=e._f,y=la(r,h);if(!b||t.has(h))return{};const v=s?s[0]:i,w=e=>{a&&v.reportValidity&&(v.setCustomValidity(ca(e)?"":e||""),v.reportValidity())},x={},S=Ha(i),k=qn(i),N=S||k,C=(g||Ba(i))&&oa(i.value)&&oa(y)||Ga(i)&&""===i.value||""===y||Array.isArray(y)&&!y.length,E=La.bind(null,h,n,x),A=(e,t,r,n=Sa,a=ka)=>{const o=e?t:r;x[h]={type:e?n:a,message:o,ref:i,...E(e?n:a,o)}};if(o?!Array.isArray(y)||!y.length:l&&(!N&&(C||Yn(y))||ca(y)&&!y||k&&!to(s).isValid||S&&!ao(s).isValid)){const{value:e,message:t}=Ra(l)?{value:!!l,message:l}:bo(l);if(e&&(x[h]={type:Ca,message:t,ref:v,...E(Ca,t)},!n))return w(t),x}if(!(C||Yn(u)&&Yn(f))){let e,t;const r=bo(f),a=bo(u);if(Yn(y)||isNaN(y)){const n=i.valueAsDate||new Date(y),o=e=>new Date((new Date).toDateString()+" "+e),s="time"==i.type,l="week"==i.type;Ra(r.value)&&y&&(e=s?o(y)>o(r.value):l?y>r.value:n>new Date(r.value)),Ra(a.value)&&y&&(t=s?o(y)<o(a.value):l?y<a.value:n<new Date(a.value))}else{const n=i.valueAsNumber||(y?+y:y);Yn(r.value)||(e=n>r.value),Yn(a.value)||(t=n<a.value)}if((e||t)&&(A(!!e,r.message,a.message,wa,xa),!n))return w(x[h].message),x}if((c||d)&&!C&&(Ra(y)||o&&Array.isArray(y))){const e=bo(c),t=bo(d),r=!Yn(e.value)&&y.length>+e.value,a=!Yn(t.value)&&y.length<+t.value;if((r||a)&&(A(r,e.message,t.message),!n))return w(x[h].message),x}if(m&&!C&&Ra(y)){const{value:e,message:t}=bo(m);if(io(e)&&!y.match(e)&&(x[h]={type:Na,message:t,ref:i,...E(Na,t)},!n))return w(t),x}if(p)if(da(p)){const e=go(await p(y,r),v);if(e&&(x[h]={...e,...E(Ea,e.message)},!n))return w(e.message),x}else if(Qn(p)){let e={};for(const t in p){if(!ja(e)&&!n)break;const a=go(await p[t](y,r),v,t);a&&(e={...a,...E(t,a.message)},w(a.message),n&&(x[h]=e))}if(!ja(e)&&(x[h]={ref:v,...e},!n))return x}return w(!0),x};const vo={mode:ba,reValidateMode:ga,shouldFocusError:!0};function wo(e={}){let t,r={...vo,...e},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:da(r.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:r.errors||{},disabled:r.disabled||!1},a={},o=(Qn(r.defaultValues)||Qn(r.values))&&na(r.defaultValues||r.values)||{},i=r.shouldUnregister?{}:na(o),s={action:!1,mount:!1,watch:!1,keepIsValid:!1},l={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},c=0;const d={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},u={...d};let f={...u};const m={array:Va(),state:Va()},p=r.criteriaMode===va,h=async e=>{if(!s.keepIsValid&&!r.disabled&&(u.isValid||f.isValid||e)){let e;r.resolver?(e=ja((await w()).errors),g()):e=await x(a,!0),e!==n.isValid&&m.state.next({isValid:e})}},g=(e,t)=>{!r.disabled&&(u.isValidating||u.validatingFields||f.isValidating||f.validatingFields)&&((e||Array.from(l.mount)).forEach(e=>{e&&(t?ua(n.validatingFields,e,t):qa(n.validatingFields,e))}),m.state.next({validatingFields:n.validatingFields,isValidating:!ja(n.validatingFields)}))},b=(e,t,r,n)=>{const l=la(a,e);if(l){const a=la(i,e,oa(r)?la(o,e):r);oa(a)||n&&n.defaultChecked||t?ua(i,e,t?a:oo(l._f)):N(e,a),s.mount&&!s.action&&h()}},y=(e,t,a,i,s)=>{let l=!1,c=!1;const d={name:e};if(!r.disabled){if(!a||i){(u.isDirty||f.isDirty)&&(c=n.isDirty,n.isDirty=d.isDirty=S(),l=c!==d.isDirty);const r=Da(la(o,e),t);c=!!la(n.dirtyFields,e),r?qa(n.dirtyFields,e):ua(n.dirtyFields,e,!0),d.dirtyFields=n.dirtyFields,l=l||(u.dirtyFields||f.dirtyFields)&&c!==!r}if(a){const t=la(n.touchedFields,e);t||(ua(n.touchedFields,e,a),d.touchedFields=n.touchedFields,l=l||(u.touchedFields||f.touchedFields)&&t!==a)}l&&s&&m.state.next(d)}return l?d:{}},v=(e,a,o,i)=>{const s=la(n.errors,e),l=(u.isValid||f.isValid)&&ca(a)&&n.isValid!==a;var d;if(r.delayError&&o?(d=()=>((e,t)=>{ua(n.errors,e,t),m.state.next({errors:n.errors})})(e,o),t=e=>{clearTimeout(c),c=setTimeout(d,e)},t(r.delayError)):(clearTimeout(c),t=null,o?ua(n.errors,e,o):qa(n.errors,e)),(o?!Da(s,o):s)||!ja(i)||l){const t={...i,...l&&ca(a)?{isValid:a}:{},errors:n.errors,name:e};n={...n,...t},m.state.next(t)}},w=async e=>{g(e,!0);const t=await r.resolver(i,r.context,((e,t,r,n)=>{const a={};for(const r of e){const e=la(t,r);e&&ua(a,r,e._f)}return{criteriaMode:r,names:[...e],fields:a,shouldUseNativeValidation:n}})(e||l.mount,a,r.criteriaMode,r.shouldUseNativeValidation));return t},x=async(t,a,o={valid:!0})=>{for(const s in t){const c=t[s];if(c){const{_f:t,...s}=c;if(t){const s=l.array.has(t.name),d=c._f&&uo(c._f);d&&u.validatingFields&&g([t.name],!0);const f=await yo(c,l.disabled,i,p,r.shouldUseNativeValidation&&!a,s);if(d&&u.validatingFields&&g([t.name]),f[t.name]&&(o.valid=!1,a||e.shouldUseNativeValidation))break;!a&&(la(f,t.name)?s?ho(n.errors,f,t.name):ua(n.errors,t.name,f[t.name]):qa(n.errors,t.name))}!ja(s)&&await x(s,a,o)}}return o.valid},S=(e,t)=>!r.disabled&&(e&&t&&ua(i,e,t),!Da(P(),o)),k=(e,t,r)=>Ia(e,l,{...s.mount?i:oa(t)?o:Ra(e)?{[e]:t}:t},r,t),N=(e,t,r={})=>{const n=la(a,e);let o=t;if(n){const r=n._f;r&&(!r.disabled&&ua(i,e,ro(t,r)),o=Ga(r.ref)&&Yn(t)?"":t,Ka(r.ref)?[...r.ref.options].forEach(e=>e.selected=o.includes(e.value)):r.refs?qn(r.ref)?r.refs.forEach(e=>{e.defaultChecked&&e.disabled||(Array.isArray(o)?e.checked=!!o.find(t=>t===e.value):e.checked=o===e.value||!!o)}):r.refs.forEach(e=>e.checked=e.value===o):Ba(r.ref)?r.ref.value="":(r.ref.value=o,r.ref.type||m.state.next({name:e,values:na(i)})))}(r.shouldDirty||r.shouldTouch)&&y(e,o,r.shouldTouch,r.shouldDirty,!0),r.shouldValidate&&T(e)},C=(e,t,r)=>{for(const n in t){if(!t.hasOwnProperty(n))return;const o=t[n],i=e+"."+n,s=la(a,i);(l.array.has(e)||Qn(o)||s&&!s._f)&&!Jn(o)?C(i,o,r):N(i,o,r)}},E=(e,t,r={})=>{const c=la(a,e),d=l.array.has(e),p=na(t);ua(i,e,p),d?(m.array.next({name:e,values:na(i)}),(u.isDirty||u.dirtyFields||f.isDirty||f.dirtyFields)&&r.shouldDirty&&m.state.next({name:e,dirtyFields:Xa(o,i),isDirty:S(e,p)})):!c||c._f||Yn(p)?N(e,p,r):C(e,p,r),fo(e,l)?m.state.next({...n,name:e,values:na(i)}):m.state.next({name:s.mount?e:void 0,values:na(i)})},A=async e=>{s.mount=!0;const o=e.target;let c=o.name,d=!0;const b=la(a,c),S=e=>{d=Number.isNaN(e)||Jn(e)&&isNaN(e.getTime())||Da(e,la(i,c,e))},k=lo(r.mode),N=lo(r.reValidateMode);if(b){let s,C;const E=o.type?oo(b._f):ea(e),A=e.type===fa||e.type===ma,_=!(e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate))(b._f)&&!r.resolver&&!la(n.errors,c)&&!b._f.deps||((e,t,r,n,a)=>!a.isOnAll&&(!r&&a.isOnTouch?!(t||e):(r?n.isOnBlur:a.isOnBlur)?!e:!(r?n.isOnChange:a.isOnChange)||e))(A,la(n.touchedFields,c),n.isSubmitted,N,k),P=fo(c,l,A);ua(i,c,E),A?o&&o.readOnly||(b._f.onBlur&&b._f.onBlur(e),t&&t(0)):b._f.onChange&&b._f.onChange(e);const R=y(c,E,A),I=!ja(R)||P;if(!A&&m.state.next({name:c,type:e.type,values:na(i)}),_)return(u.isValid||f.isValid)&&("onBlur"===r.mode?A&&h():A||h()),I&&m.state.next({name:c,...P?{}:R});if(!A&&P&&m.state.next({...n}),r.resolver){const{errors:e}=await w([c]);if(g([c]),S(E),d){const t=po(n.errors,a,c),r=po(e,a,t.name||c);s=r.error,c=r.name,C=ja(e)}}else g([c],!0),s=(await yo(b,l.disabled,i,p,r.shouldUseNativeValidation))[c],g([c]),S(E),d&&(s?C=!1:(u.isValid||f.isValid)&&(C=await x(a,!0)));d&&(b._f.deps&&(!Array.isArray(b._f.deps)||b._f.deps.length>0)&&T(b._f.deps),v(c,C,s,R))}},_=(e,t)=>{if(la(n.errors,t)&&e.focus)return e.focus(),1},T=async(e,t={})=>{let o,i;const s=$a(e);if(r.resolver){const t=await(async e=>{const{errors:t}=await w(e);if(g(e),e)for(const r of e){const e=la(t,r);e?ua(n.errors,r,e):qa(n.errors,r)}else n.errors=t;return t})(oa(e)?e:s);o=ja(t),i=e?!s.some(e=>la(t,e)):o}else e?(i=(await Promise.all(s.map(async e=>{const t=la(a,e);return await x(t&&t._f?{[e]:t}:t)}))).every(Boolean),(i||n.isValid)&&h()):i=o=await x(a);return m.state.next({...!Ra(e)||(u.isValid||f.isValid)&&o!==n.isValid?{}:{name:e},...r.resolver||!e?{isValid:o}:{},errors:n.errors}),t.shouldFocus&&!i&&mo(a,_,e?s:l.mount),i},P=(e,t)=>{let r={...s.mount?i:o};return t&&(r=Wa(t.dirtyFields?n.dirtyFields:n.touchedFields,r)),oa(e)?r:Ra(e)?la(r,e):e.map(e=>la(r,e))},R=(e,t)=>({invalid:!!la((t||n).errors,e),isDirty:!!la((t||n).dirtyFields,e),error:la((t||n).errors,e),isValidating:!!la(n.validatingFields,e),isTouched:!!la((t||n).touchedFields,e)}),I=(e,t,r)=>{const o=(la(a,e,{_f:{}})._f||{}).ref,i=la(n.errors,e)||{},{ref:s,message:l,type:c,...d}=i;ua(n.errors,e,{...d,...t,ref:o}),m.state.next({name:e,errors:n.errors,isValid:!1}),r&&r.shouldFocus&&o&&o.focus&&o.focus()},O=e=>m.state.subscribe({next:t=>{var r,a,s;r=e.name,a=t.name,s=e.exact,r&&a&&r!==a&&!$a(r).some(e=>e&&(s?e===a:e.startsWith(a)||a.startsWith(e)))||!((e,t,r,n)=>{r(e);const{name:a,...o}=e;return ja(o)||Object.keys(o).length>=Object.keys(t).length||Object.keys(o).find(e=>t[e]===(!n||va))})(t,e.formState||u,V,e.reRenderRoot)||e.callback({values:{...i},...n,...t,defaultValues:o})}}).unsubscribe,D=(e,t={})=>{for(const s of e?$a(e):l.mount)l.mount.delete(s),l.array.delete(s),t.keepValue||(qa(a,s),qa(i,s)),!t.keepError&&qa(n.errors,s),!t.keepDirty&&qa(n.dirtyFields,s),!t.keepTouched&&qa(n.touchedFields,s),!t.keepIsValidating&&qa(n.validatingFields,s),!r.shouldUnregister&&!t.keepDefaultValue&&qa(o,s);m.state.next({values:na(i)}),m.state.next({...n,...t.keepDirty?{isDirty:S()}:{}}),!t.keepIsValid&&h()},M=({disabled:e,name:t})=>{if(ca(e)&&s.mount||e||l.disabled.has(t)){const r=l.disabled.has(t)!==!!e;e?l.disabled.add(t):l.disabled.delete(t),r&&s.mount&&!s.action&&h()}},U=(e,t={})=>{let n=la(a,e);const i=ca(t.disabled)||ca(r.disabled);return ua(a,e,{...n||{},_f:{...n&&n._f?n._f:{ref:{name:e}},name:e,mount:!0,...t}}),l.mount.add(e),n?M({disabled:ca(t.disabled)?t.disabled:r.disabled,name:e}):b(e,!0,t.value),{...i?{disabled:t.disabled||r.disabled}:{},...r.progressive?{required:!!t.required,min:so(t.min),max:so(t.max),minLength:so(t.minLength),maxLength:so(t.maxLength),pattern:so(t.pattern)}:{},name:e,onChange:A,onBlur:A,ref:i=>{if(i){U(e,t),n=la(a,e);const r=oa(i.value)&&i.querySelectorAll&&i.querySelectorAll("input,select,textarea")[0]||i,s=(e=>Ha(e)||qn(e))(r),l=n._f.refs||[];if(s?l.find(e=>e===r):r===n._f.ref)return;ua(a,e,{_f:{...n._f,...s?{refs:[...l.filter(Za),r,...Array.isArray(la(o,e))?[{}]:[]],ref:{type:r.type,name:e}}:{ref:r}}}),b(e,!1,void 0,r)}else n=la(a,e,{}),n._f&&(n._f.mount=!1),(r.shouldUnregister||t.shouldUnregister)&&(!ta(l.array,e)||!s.action)&&l.unMount.add(e)}}},z=()=>r.shouldFocusError&&mo(a,_,l.mount),F=(e,t)=>async o=>{let s;o&&(o.preventDefault&&o.preventDefault(),o.persist&&o.persist());let c=na(i);if(m.state.next({isSubmitting:!0}),r.resolver){const{errors:e,values:t}=await w();g(),n.errors=e,c=na(t)}else await x(a);if(l.disabled.size)for(const e of l.disabled)qa(c,e);if(qa(n.errors,"root"),ja(n.errors)){m.state.next({errors:{}});try{await e(c,o)}catch(e){s=e}}else t&&await t({...n.errors},o),z(),setTimeout(z);if(m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:ja(n.errors)&&!s,submitCount:n.submitCount+1,errors:n.errors}),s)throw s},L=(e,t={})=>{const c=e?na(e):o,d=na(c),f=ja(e),p=f?o:d;if(t.keepDefaultValues||(o=c),!t.keepValues){if(t.keepDirtyValues){const e=new Set([...l.mount,...Object.keys(Xa(o,i))]);for(const t of Array.from(e)){const e=la(n.dirtyFields,t),r=la(i,t),a=la(p,t);e&&!oa(r)?ua(p,t,r):e||oa(a)||E(t,a)}}else{if(ra&&oa(e))for(const e of l.mount){const t=la(a,e);if(t&&t._f){const e=Array.isArray(t._f.refs)?t._f.refs[0]:t._f.ref;if(Ga(e)){const t=e.closest("form");if(t){t.reset();break}}}}if(t.keepFieldsRef)for(const e of l.mount)E(e,la(p,e));else a={}}i=r.shouldUnregister?t.keepDefaultValues?na(o):{}:na(p),m.array.next({values:{...p}}),m.state.next({values:{...p}})}l={mount:t.keepDirtyValues?l.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},s.mount=!u.isValid||!!t.keepIsValid||!!t.keepDirtyValues||!r.shouldUnregister&&!ja(p),s.watch=!!r.shouldUnregister,s.keepIsValid=!!t.keepIsValid,s.action=!1,t.keepErrors||(n.errors={}),m.state.next({submitCount:t.keepSubmitCount?n.submitCount:0,isDirty:!f&&(t.keepDirty?n.isDirty:!(!t.keepDefaultValues||Da(e,o))),isSubmitted:!!t.keepIsSubmitted&&n.isSubmitted,dirtyFields:f?{}:t.keepDirtyValues?t.keepDefaultValues&&i?Xa(o,i):n.dirtyFields:t.keepDefaultValues&&e?Xa(o,e):t.keepDirty?n.dirtyFields:{},touchedFields:t.keepTouched?n.touchedFields:{},errors:t.keepErrors?n.errors:{},isSubmitSuccessful:!!t.keepIsSubmitSuccessful&&n.isSubmitSuccessful,isSubmitting:!1,defaultValues:o})},$=(e,t)=>L(da(e)?e(i):e,{...r.resetOptions,...t}),V=e=>{n={...n,...e}},W={control:{register:U,unregister:D,getFieldState:R,handleSubmit:F,setError:I,_subscribe:O,_runSchema:w,_updateIsValidating:g,_focusError:z,_getWatch:k,_getDirty:S,_setValid:h,_setFieldArray:(e,t=[],l,c,d=!0,p=!0)=>{if(c&&l&&!r.disabled){if(s.action=!0,p&&Array.isArray(la(a,e))){const t=l(la(a,e),c.argA,c.argB);d&&ua(a,e,t)}if(p&&Array.isArray(la(n.errors,e))){const t=l(la(n.errors,e),c.argA,c.argB);d&&ua(n.errors,e,t),((e,t)=>{!ia(la(e,t)).length&&qa(e,t)})(n.errors,e)}if((u.touchedFields||f.touchedFields)&&p&&Array.isArray(la(n.touchedFields,e))){const t=l(la(n.touchedFields,e),c.argA,c.argB);d&&ua(n.touchedFields,e,t)}(u.dirtyFields||f.dirtyFields)&&(n.dirtyFields=Xa(o,i)),m.state.next({name:e,isDirty:S(e,t),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else ua(i,e,t)},_setDisabledField:M,_setErrors:e=>{n.errors=e,m.state.next({errors:n.errors,isValid:!1})},_getFieldArray:e=>ia(la(s.mount?i:o,e,r.shouldUnregister?la(o,e,[]):[])),_reset:L,_resetDefaultValues:()=>da(r.defaultValues)&&r.defaultValues().then(e=>{$(e,r.resetOptions),m.state.next({isLoading:!1})}),_removeUnmounted:()=>{for(const e of l.unMount){const t=la(a,e);t&&(t._f.refs?t._f.refs.every(e=>!Za(e)):!Za(t._f.ref))&&D(e)}l.unMount=new Set},_disableForm:e=>{ca(e)&&(m.state.next({disabled:e}),mo(a,(t,r)=>{const n=la(a,r);n&&(t.disabled=n._f.disabled||e,Array.isArray(n._f.refs)&&n._f.refs.forEach(t=>{t.disabled=n._f.disabled||e}))},0,!1))},_subjects:m,_proxyFormState:u,get _fields(){return a},get _formValues(){return i},get _state(){return s},set _state(e){s=e},get _defaultValues(){return o},get _names(){return l},set _names(e){l=e},get _formState(){return n},get _options(){return r},set _options(e){r={...r,...e}}},subscribe:e=>(s.mount=!0,f={...f,...e.formState},O({...e,formState:{...d,...e.formState}})),trigger:T,register:U,handleSubmit:F,watch:(e,t)=>da(e)?m.state.subscribe({next:r=>"values"in r&&e(k(void 0,t),r)}):k(e,t,!0),setValue:E,getValues:P,reset:$,resetField:(e,t={})=>{la(a,e)&&(oa(t.defaultValue)?E(e,na(la(o,e))):(E(e,t.defaultValue),ua(o,e,na(t.defaultValue))),t.keepTouched||qa(n.touchedFields,e),t.keepDirty||(qa(n.dirtyFields,e),n.isDirty=t.defaultValue?S(e,na(la(o,e))):S()),t.keepError||(qa(n.errors,e),u.isValid&&h()),m.state.next({...n}))},clearErrors:e=>{e&&$a(e).forEach(e=>qa(n.errors,e)),m.state.next({errors:e?n.errors:{}})},unregister:D,setError:I,setFocus:(e,t={})=>{const r=la(a,e),n=r&&r._f;if(n){const e=n.refs?n.refs[0]:n.ref;e.focus&&setTimeout(()=>{e.focus(),t.shouldSelect&&da(e.select)&&e.select()})}},getFieldState:R};return{...W,formControl:W}}function xo(e={}){const t=a.useRef(void 0),r=a.useRef(void 0),[n,o]=a.useState({isDirty:!1,isValidating:!1,isLoading:da(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,isReady:!1,defaultValues:da(e.defaultValues)?void 0:e.defaultValues});if(!t.current)if(e.formControl)t.current={...e.formControl,formState:n},e.defaultValues&&!da(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:r,...a}=wo(e);t.current={...a,formState:n}}const i=t.current.control;return i._options=e,Pa(()=>{const e=i._subscribe({formState:i._proxyFormState,callback:()=>o({...i._formState}),reRenderRoot:!0});return o(e=>({...e,isReady:!0})),i._formState.isReady=!0,e},[i]),a.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),a.useEffect(()=>{e.mode&&(i._options.mode=e.mode),e.reValidateMode&&(i._options.reValidateMode=e.reValidateMode)},[i,e.mode,e.reValidateMode]),a.useEffect(()=>{e.errors&&(i._setErrors(e.errors),i._focusError())},[i,e.errors]),a.useEffect(()=>{e.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,e.shouldUnregister]),a.useEffect(()=>{if(i._proxyFormState.isDirty){const e=i._getDirty();e!==n.isDirty&&i._subjects.state.next({isDirty:e})}},[i,n.isDirty]),a.useEffect(()=>{var t;e.values&&!Da(e.values,r.current)?(i._reset(e.values,{keepFieldsRef:!0,...i._options.resetOptions}),(null===(t=i._options.resetOptions)||void 0===t?void 0:t.keepIsValid)||i._setValid(),r.current=e.values,o(e=>({...e}))):i._resetDefaultValues()},[i,e.values]),a.useEffect(()=>{i._state.mount||(i._setValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=a.useMemo(()=>Ta(n,i),[i,n]),t.current}const So=(e,t,r)=>{if(e&&"reportValidity"in e){const n=la(r,t);e.setCustomValidity(n&&n.message||""),e.reportValidity()}},ko=(e,t)=>{for(const r in t.fields){const n=t.fields[r];n&&n.ref&&"reportValidity"in n.ref?So(n.ref,r,e):n&&n.refs&&n.refs.forEach(t=>So(t,r,e))}},No=(e,t)=>{t.shouldUseNativeValidation&&ko(e,t);const r={};for(const n in e){const a=la(t.fields,n),o=Object.assign(e[n]||{},{ref:a&&a.ref});if(Co(t.names||Object.keys(e),n)){const e=Object.assign({},la(r,n));ua(e,"root",o),ua(r,n,e)}else ua(r,n,o)}return r},Co=(e,t)=>{const r=Eo(t);return e.some(e=>Eo(e).match(`^${r}\\.\\d+`))};function Eo(e){return e.replace(/\]|\[/g,"")}function Ao(e,t,r){function n(r,n){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:n,constr:i,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,n);const a=i.prototype,o=Object.keys(a);for(let e=0;e<o.length;e++){const t=o[e];t in r||(r[t]=a[t].bind(r))}}const a=r?.Parent??Object;class o extends a{}function i(e){var t;const a=r?.Parent?new o:this;n(a,e),(t=a._zod).deferred??(t.deferred=[]);for(const e of a._zod.deferred)e();return a}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class _o extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class To extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Po={};function Ro(e){return Po}function Io(e){const t=Object.values(e).filter(e=>"number"==typeof e),r=Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t);return r}function Oo(e,t){return"bigint"==typeof t?t.toString():t}function Do(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Mo(e){return null==e}function Uo(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const zo=Symbol("evaluating");function Fo(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==zo)return void 0===n&&(n=zo,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Lo(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function $o(...e){const t={};for(const r of e){const e=Object.getOwnPropertyDescriptors(r);Object.assign(t,e)}return Object.defineProperties({},t)}function Vo(e){return JSON.stringify(e)}const Wo="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function jo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Bo=Do(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Go(e){if(!1===jo(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const r=t.prototype;return!1!==jo(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function Ko(e){return Go(e)?{...e}:Array.isArray(e)?[...e]:e}const Ho=new Set(["string","number","symbol"]);function Zo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qo(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function Jo(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function Yo(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function Xo(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function Qo(e){return"string"==typeof e?e:e?.message}function ei(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const a=Qo(e.inst?._zod.def?.error?.(e))??Qo(t?.error?.(e))??Qo(r.customError?.(e))??Qo(r.localeError?.(e))??"Invalid input";n.message=a}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function ti(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function ri(...e){const[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}const ni=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Oo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ai=Ao("$ZodError",ni),oi=Ao("$ZodError",ni,{Parent:Error});const ii=e=>(t,r,n,a)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new _o;if(i.issues.length){const t=new(a?.Err??e)(i.issues.map(e=>ei(e,o,Ro())));throw Wo(t,a?.callee),t}return i.value},si=ii(oi),li=e=>async(t,r,n,a)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){const t=new(a?.Err??e)(i.issues.map(e=>ei(e,o,Ro())));throw Wo(t,a?.callee),t}return i.value},ci=li(oi),di=e=>(t,r,n)=>{const a=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},a);if(o instanceof Promise)throw new _o;return o.issues.length?{success:!1,error:new(e??ai)(o.issues.map(e=>ei(e,a,Ro())))}:{success:!0,data:o.value}},ui=di(oi),fi=e=>async(t,r,n)=>{const a=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},a);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>ei(e,a,Ro())))}:{success:!0,data:o.value}},mi=fi(oi),pi=e=>(t,r,n)=>{const a=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ii(e)(t,r,a)},hi=e=>(t,r,n)=>ii(e)(t,r,n),gi=e=>async(t,r,n)=>{const a=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return li(e)(t,r,a)},bi=e=>async(t,r,n)=>li(e)(t,r,n),yi=e=>(t,r,n)=>{const a=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return di(e)(t,r,a)},vi=e=>(t,r,n)=>di(e)(t,r,n),wi=e=>async(t,r,n)=>{const a=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return fi(e)(t,r,a)},xi=e=>async(t,r,n)=>fi(e)(t,r,n),Si=/^[cC][^\s-]{8,}$/,ki=/^[0-9a-z]+$/,Ni=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ci=/^[0-9a-vA-V]{20}$/,Ei=/^[A-Za-z0-9]{27}$/,Ai=/^[a-zA-Z0-9_-]{21}$/,_i=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ti=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Pi=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ri=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;const Ii=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Oi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Di=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Mi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ui=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,zi=/^[A-Za-z0-9_-]*$/,Fi=/^\+[1-9]\d{6,14}$/,Li="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",$i=new RegExp(`^${Li}$`);function Vi(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const Wi=/^[^A-Z]*$/,ji=/^[^a-z]*$/,Bi=Ao("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Gi=Ao("$ZodCheckMaxLength",(e,t)=>{var r;Bi.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!Mo(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const n=r.value;if(n.length<=t.maximum)return;const a=ti(n);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Ki=Ao("$ZodCheckMinLength",(e,t)=>{var r;Bi.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!Mo(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const n=r.value;if(n.length>=t.minimum)return;const a=ti(n);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Hi=Ao("$ZodCheckLengthEquals",(e,t)=>{var r;Bi.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!Mo(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{const n=r.value,a=n.length;if(a===t.length)return;const o=ti(n),i=a>t.length;r.issues.push({origin:o,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Zi=Ao("$ZodCheckStringFormat",(e,t)=>{var r,n;Bi.init(e,t),e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),qi=Ao("$ZodCheckRegex",(e,t)=>{Zi.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ji=Ao("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Wi),Zi.init(e,t)}),Yi=Ao("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ji),Zi.init(e,t)}),Xi=Ao("$ZodCheckIncludes",(e,t)=>{Bi.init(e,t);const r=Zo(t.includes),n=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Qi=Ao("$ZodCheckStartsWith",(e,t)=>{Bi.init(e,t);const r=new RegExp(`^${Zo(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),es=Ao("$ZodCheckEndsWith",(e,t)=>{Bi.init(e,t);const r=new RegExp(`.*${Zo(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),ts=Ao("$ZodCheckOverwrite",(e,t)=>{Bi.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class rs{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length)),n=t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e);for(const e of n)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const ns={major:4,minor:3,patch:6},as=Ao("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ns;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let n,a=Yo(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(a)continue;const t=e.issues.length,i=o._zod.check(e);if(i instanceof Promise&&!1===r?.async)throw new _o;if(n||i instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await i;e.issues.length!==t&&(a||(a=Yo(e,t)))});else{if(e.issues.length===t)continue;a||(a=Yo(e,t))}}return n?n.then(()=>e):e},r=(r,a,o)=>{if(Yo(r))return r.aborted=!0,r;const i=t(a,n,o);if(i instanceof Promise){if(!1===o.async)throw new _o;return i.then(t=>e._zod.parse(t,o))}return e._zod.parse(i,o)};e._zod.run=(a,o)=>{if(o.skipChecks)return e._zod.parse(a,o);if("backward"===o.direction){const t=e._zod.parse({value:a.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,a,o)):r(t,a,o)}const i=e._zod.parse(a,o);if(i instanceof Promise){if(!1===o.async)throw new _o;return i.then(e=>t(e,n,o))}return t(i,n,o)}}Fo(e,"~standard",()=>({validate:t=>{try{const r=ui(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return mi(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),os=Ao("$ZodString",(e,t)=>{var r;as.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(r=e._zod.bag,new RegExp(`^${r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),is=Ao("$ZodStringFormat",(e,t)=>{Zi.init(e,t),os.init(e,t)}),ss=Ao("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ti),is.init(e,t)}),ls=Ao("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Pi(e))}else t.pattern??(t.pattern=Pi());is.init(e,t)}),cs=Ao("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ri),is.init(e,t)}),ds=Ao("$ZodURL",(e,t)=>{is.init(e,t),e._zod.check=r=>{try{const n=r.value.trim(),a=new URL(n);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(a.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),void(t.normalize?r.value=a.href:r.value=n)}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),us=Ao("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),is.init(e,t)}),fs=Ao("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ai),is.init(e,t)}),ms=Ao("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Si),is.init(e,t)}),ps=Ao("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ki),is.init(e,t)}),hs=Ao("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ni),is.init(e,t)}),gs=Ao("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ci),is.init(e,t)}),bs=Ao("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ei),is.init(e,t)}),ys=Ao("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=Vi({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Li}T(?:${n})$`)}(t)),is.init(e,t)}),vs=Ao("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=$i),is.init(e,t)}),ws=Ao("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${Vi(t)}$`)),is.init(e,t)}),xs=Ao("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=_i),is.init(e,t)}),Ss=Ao("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ii),is.init(e,t),e._zod.bag.format="ipv4"}),ks=Ao("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Oi),is.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Ns=Ao("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Di),is.init(e,t)}),Cs=Ao("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Mi),is.init(e,t),e._zod.check=r=>{const n=r.value.split("/");try{if(2!==n.length)throw new Error;const[e,t]=n;if(!t)throw new Error;const r=Number(t);if(`${r}`!==t)throw new Error;if(r<0||r>128)throw new Error;new URL(`http://[${e}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Es(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const As=Ao("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ui),is.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{Es(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});const _s=Ao("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=zi),is.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{(function(e){if(!zi.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return Es(t.padEnd(4*Math.ceil(t.length/4),"="))})(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Ts=Ao("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Fi),is.init(e,t)});const Ps=Ao("$ZodJWT",(e,t)=>{is.init(e,t),e._zod.check=r=>{(function(e,t=null){try{const r=e.split(".");if(3!==r.length)return!1;const[n]=r;if(!n)return!1;const a=JSON.parse(atob(n));return!("typ"in a&&"JWT"!==a?.typ||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}})(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Rs=Ao("$ZodUnknown",(e,t)=>{as.init(e,t),e._zod.parse=e=>e}),Is=Ao("$ZodNever",(e,t)=>{as.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Os(e,t,r){e.issues.length&&t.issues.push(...Xo(r,e.issues)),t.value[r]=e.value}const Ds=Ao("$ZodArray",(e,t)=>{as.init(e,t),e._zod.parse=(r,n)=>{const a=r.value;if(!Array.isArray(a))return r.issues.push({expected:"array",code:"invalid_type",input:a,inst:e}),r;r.value=Array(a.length);const o=[];for(let e=0;e<a.length;e++){const i=a[e],s=t.element._zod.run({value:i,issues:[]},n);s instanceof Promise?o.push(s.then(t=>Os(t,r,e))):Os(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function Ms(e,t,r,n,a){if(e.issues.length){if(a&&!(r in n))return;t.issues.push(...Xo(r,e.issues))}void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function Us(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=(n=e.shape,Object.keys(n).filter(e=>"optional"===n[e]._zod.optin&&"optional"===n[e]._zod.optout));var n;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function zs(e,t,r,n,a,o){const i=[],s=a.keySet,l=a.catchall._zod,c=l.def.type,d="optional"===l.optout;for(const a in t){if(s.has(a))continue;if("never"===c){i.push(a);continue}const o=l.run({value:t[a],issues:[]},n);o instanceof Promise?e.push(o.then(e=>Ms(e,r,a,t,d))):Ms(o,r,a,t,d)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:o}),e.length?Promise.all(e).then(()=>r):r}const Fs=Ao("$ZodObject",(e,t)=>{as.init(e,t);const r=Object.getOwnPropertyDescriptor(t,"shape");if(!r?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}const n=Do(()=>Us(t));Fo(e._zod,"propValues",()=>{const e=t.shape,r={};for(const t in e){const n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(const e of n.values)r[t].add(e)}}return r});const a=jo,o=t.catchall;let i;e._zod.parse=(t,r)=>{i??(i=n.value);const s=t.value;if(!a(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};const l=[],c=i.shape;for(const e of i.keys){const n=c[e],a="optional"===n._zod.optout,o=n._zod.run({value:s[e],issues:[]},r);o instanceof Promise?l.push(o.then(r=>Ms(r,t,e,s,a))):Ms(o,t,e,s,a)}return o?zs(l,s,t,r,n.value,e):l.length?Promise.all(l).then(()=>t):t}}),Ls=Ao("$ZodObjectJIT",(e,t)=>{Fs.init(e,t);const r=e._zod.parse,n=Do(()=>Us(t));let a;const o=jo,i=!Po.jitless,s=i&&Bo.value,l=t.catchall;let c;e._zod.parse=(d,u)=>{c??(c=n.value);const f=d.value;return o(f)?i&&s&&!1===u?.async&&!0!==u.jitless?(a||(a=(e=>{const t=new rs(["shape","payload","ctx"]),r=n.value,a=e=>{const t=Vo(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let i=0;for(const e of r.keys)o[e]="key_"+i++;t.write("const newResult = {};");for(const n of r.keys){const r=o[n],i=Vo(n),s=e[n],l="optional"===s?._zod?.optout;t.write(`const ${r} = ${a(n)};`),l?t.write(`\n if (${r}.issues.length) {\n if (${i} in input) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${i}, ...iss.path] : [${i}]\n })));\n }\n }\n \n if (${r}.value === undefined) {\n if (${i} in input) {\n newResult[${i}] = undefined;\n }\n } else {\n newResult[${i}] = ${r}.value;\n }\n \n `):t.write(`\n if (${r}.issues.length) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${i}, ...iss.path] : [${i}]\n })));\n }\n \n if (${r}.value === undefined) {\n if (${i} in input) {\n newResult[${i}] = undefined;\n }\n } else {\n newResult[${i}] = ${r}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const s=t.compile();return(t,r)=>s(e,t,r)})(t.shape)),d=a(d,u),l?zs([],f,d,u,c,e):d):r(d,u):(d.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),d)}});function $s(e,t,r,n){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;const a=e.filter(e=>!Yo(e));return 1===a.length?(t.value=a[0].value,a[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>ei(e,n,Ro())))}),t)}const Vs=Ao("$ZodUnion",(e,t)=>{as.init(e,t),Fo(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Fo(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Fo(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Fo(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>Uo(e.source)).join("|")})$`)}});const r=1===t.options.length,n=t.options[0]._zod.run;e._zod.parse=(a,o)=>{if(r)return n(a,o);let i=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:a.value,issues:[]},o);if(t instanceof Promise)s.push(t),i=!0;else{if(0===t.issues.length)return t;s.push(t)}}return i?Promise.all(s).then(t=>$s(t,a,e,o)):$s(s,a,e,o)}}),Ws=Ao("$ZodIntersection",(e,t)=>{as.init(e,t),e._zod.parse=(e,r)=>{const n=e.value,a=t.left._zod.run({value:n,issues:[]},r),o=t.right._zod.run({value:n,issues:[]},r);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([t,r])=>Bs(e,t,r)):Bs(e,a,o)}});function js(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Go(e)&&Go(t)){const r=Object.keys(t),n=Object.keys(e).filter(e=>-1!==r.indexOf(e)),a={...e,...t};for(const r of n){const n=js(e[r],t[r]);if(!n.valid)return{valid:!1,mergeErrorPath:[r,...n.mergeErrorPath]};a[r]=n.data}return{valid:!0,data:a}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const a=js(e[n],t[n]);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Bs(e,t,r){const n=new Map;let a;for(const r of t.issues)if("unrecognized_keys"===r.code){a??(a=r);for(const e of r.keys)n.has(e)||n.set(e,{}),n.get(e).l=!0}else e.issues.push(r);for(const t of r.issues)if("unrecognized_keys"===t.code)for(const e of t.keys)n.has(e)||n.set(e,{}),n.get(e).r=!0;else e.issues.push(t);const o=[...n].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length&&a&&e.issues.push({...a,keys:o}),Yo(e))return e;const i=js(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const Gs=Ao("$ZodEnum",(e,t)=>{as.init(e,t);const r=Io(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(e=>Ho.has(typeof e)).map(e=>"string"==typeof e?Zo(e):e.toString()).join("|")})$`),e._zod.parse=(t,a)=>{const o=t.value;return n.has(o)||t.issues.push({code:"invalid_value",values:r,input:o,inst:e}),t}}),Ks=Ao("$ZodTransform",(e,t)=>{as.init(e,t),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new To(e.constructor.name);const a=t.transform(r.value,r);if(n.async){return(a instanceof Promise?a:Promise.resolve(a)).then(e=>(r.value=e,r))}if(a instanceof Promise)throw new _o;return r.value=a,r}});function Hs(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Zs=Ao("$ZodOptional",(e,t)=>{as.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Fo(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Fo(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Uo(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>Hs(t,e.value)):Hs(n,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}}),qs=Ao("$ZodExactOptional",(e,t)=>{Zs.init(e,t),Fo(e._zod,"values",()=>t.innerType._zod.values),Fo(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,r)=>t.innerType._zod.run(e,r)}),Js=Ao("$ZodNullable",(e,t)=>{as.init(e,t),Fo(e._zod,"optin",()=>t.innerType._zod.optin),Fo(e._zod,"optout",()=>t.innerType._zod.optout),Fo(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Uo(e.source)}|null)$`):void 0}),Fo(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),Ys=Ao("$ZodDefault",(e,t)=>{as.init(e,t),e._zod.optin="optional",Fo(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);if(void 0===e.value)return e.value=t.defaultValue,e;const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(e=>Xs(e,t)):Xs(n,t)}});function Xs(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Qs=Ao("$ZodPrefault",(e,t)=>{as.init(e,t),e._zod.optin="optional",Fo(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>("backward"===r.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),el=Ao("$ZodNonOptional",(e,t)=>{as.init(e,t),Fo(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,n)=>{const a=t.innerType._zod.run(r,n);return a instanceof Promise?a.then(t=>tl(t,e)):tl(a,e)}});function tl(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const rl=Ao("$ZodCatch",(e,t)=>{as.init(e,t),Fo(e._zod,"optin",()=>t.innerType._zod.optin),Fo(e._zod,"optout",()=>t.innerType._zod.optout),Fo(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>ei(e,r,Ro()))},input:e.value}),e.issues=[]),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>ei(e,r,Ro()))},input:e.value}),e.issues=[]),e)}}),nl=Ao("$ZodPipe",(e,t)=>{as.init(e,t),Fo(e._zod,"values",()=>t.in._zod.values),Fo(e._zod,"optin",()=>t.in._zod.optin),Fo(e._zod,"optout",()=>t.out._zod.optout),Fo(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("backward"===r.direction){const n=t.out._zod.run(e,r);return n instanceof Promise?n.then(e=>al(e,t.in,r)):al(n,t.in,r)}const n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>al(e,t.out,r)):al(n,t.out,r)}});function al(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}const ol=Ao("$ZodReadonly",(e,t)=>{as.init(e,t),Fo(e._zod,"propValues",()=>t.innerType._zod.propValues),Fo(e._zod,"values",()=>t.innerType._zod.values),Fo(e._zod,"optin",()=>t.innerType?._zod?.optin),Fo(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(il):il(n)}});function il(e){return e.value=Object.freeze(e.value),e}const sl=Ao("$ZodCustom",(e,t)=>{Bi.init(e,t),as.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const n=r.value,a=t.fn(n);if(a instanceof Promise)return a.then(t=>ll(t,r,n,e));ll(a,r,n,e)}});function ll(e,t,r,n){if(!e){const e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(ri(e))}}var cl;class dl{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];return this._map.set(e,r),r&&"object"==typeof r&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(cl=globalThis).__zod_globalRegistry??(cl.__zod_globalRegistry=new dl);const ul=globalThis.__zod_globalRegistry;function fl(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Jo(t)})}function ml(e,t){return new Gi({check:"max_length",...Jo(t),maximum:e})}function pl(e,t){return new Ki({check:"min_length",...Jo(t),minimum:e})}function hl(e,t){return new Hi({check:"length_equals",...Jo(t),length:e})}function gl(e){return new ts({check:"overwrite",tx:e})}function bl(e){const t=function(e,t){const r=new Bi({check:"custom",...Jo(t)});return r._zod.check=e,r}(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(ri(e,r.value,t._zod.def));else{const n=e;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(ri(n))}},e(r.value,r)));return t}function yl(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??ul,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function vl(e,t,r={path:[],schemaPath:[]}){var n;const a=e._zod.def,o=t.seen.get(e);if(o){o.count++;return r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema}const i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);const s=e._zod.toJSONSchema?.();if(s)i.schema=s;else{const n={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,n);else{const r=i.schema,o=t.processors[a.type];if(!o)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);o(e,t,r,n)}const o=e._zod.parent;o&&(i.ref||(i.ref=o),vl(o,t,n),t.seen.get(o).isParent=!0)}const l=t.metadataRegistry.get(e);l&&Object.assign(i.schema,l),"input"===t.io&&Sl(e)&&(delete i.schema.examples,delete i.schema.default),"input"===t.io&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault;return t.seen.get(e).schema}function wl(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const t of e.seen.entries()){const r=e.metadataRegistry.get(t[0])?.id;if(r){const e=n.get(r);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${r}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(r,t[0])}}const a=t=>{if(t[1].schema.$ref)return;const n=t[1],{ref:a,defId:o}=(t=>{const n="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const r=e.external.registry.get(t[0])?.id,a=e.external.uri??(e=>e);if(r)return{ref:a(r)};const o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${a("__shared")}#/${n}/${o}`}}if(t[1]===r)return{ref:"#"};const a=`#/${n}/`,o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:a+o}})(t);n.def={...n.schema},o&&(n.defId=o);const i=n.schema;for(const e in i)delete i[e];i.$ref=a};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const r of e.seen.entries()){const n=r[1];if(t===r[0]){a(r);continue}if(e.external){const n=e.external.registry.get(r[0])?.id;if(t!==r[0]&&n){a(r);continue}}const o=e.metadataRegistry.get(r[0])?.id;o?a(r):(n.cycle||n.count>1&&"ref"===e.reused)&&a(r)}}function xl(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=t=>{const r=e.seen.get(t);if(null===r.ref)return;const a=r.def??r.schema,o={...a},i=r.ref;if(r.ref=null,i){n(i);const r=e.seen.get(i),s=r.schema;!s.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(a,s):(a.allOf=a.allOf??[],a.allOf.push(s)),Object.assign(a,o);if(t._zod.parent===i)for(const e in a)"$ref"!==e&&"allOf"!==e&&(e in o||delete a[e]);if(s.$ref&&r.def)for(const e in a)"$ref"!==e&&"allOf"!==e&&e in r.def&&JSON.stringify(a[e])===JSON.stringify(r.def[e])&&delete a[e]}const s=t._zod.parent;if(s&&s!==i){n(s);const t=e.seen.get(s);if(t?.schema.$ref&&(a.$ref=t.schema.$ref,t.def))for(const e in a)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(a[e])===JSON.stringify(t.def[e])&&delete a[e]}e.override({zodSchema:t,jsonSchema:a,path:r.path??[]})};for(const t of[...e.seen.entries()].reverse())n(t[0]);const a={};if("draft-2020-12"===e.target?a.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?a.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?a.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const r=e.external.registry.get(t)?.id;if(!r)throw new Error("Schema is missing an `id` property");a.$id=e.external.uri(r)}Object.assign(a,r.def??r.schema);const o=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&("draft-2020-12"===e.target?a.$defs=o:a.definitions=o);try{const r=JSON.parse(JSON.stringify(a));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:kl(t,"input",e.processors),output:kl(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch(e){throw new Error("Error converting schema to JSON.")}}function Sl(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;if("transform"===n.type)return!0;if("array"===n.type)return Sl(n.element,r);if("set"===n.type)return Sl(n.valueType,r);if("lazy"===n.type)return Sl(n.getter(),r);if("promise"===n.type||"optional"===n.type||"nonoptional"===n.type||"nullable"===n.type||"readonly"===n.type||"default"===n.type||"prefault"===n.type)return Sl(n.innerType,r);if("intersection"===n.type)return Sl(n.left,r)||Sl(n.right,r);if("record"===n.type||"map"===n.type)return Sl(n.keyType,r)||Sl(n.valueType,r);if("pipe"===n.type)return Sl(n.in,r)||Sl(n.out,r);if("object"===n.type){for(const e in n.shape)if(Sl(n.shape[e],r))return!0;return!1}if("union"===n.type){for(const e of n.options)if(Sl(e,r))return!0;return!1}if("tuple"===n.type){for(const e of n.items)if(Sl(e,r))return!0;return!(!n.rest||!Sl(n.rest,r))}return!1}const kl=(e,t,r={})=>n=>{const{libraryOptions:a,target:o}=n??{},i=yl({...a??{},target:o,io:t,processors:r});return vl(e,i),wl(i,e),xl(i,e)},Nl={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Cl=(e,t,r,n)=>{const a=e._zod.def;vl(a.innerType,t,n);t.seen.get(e).ref=a.innerType};function El(e,t){try{var r=e()}catch(e){return t(e)}return r&&r.then?r.then(void 0,t):r}function Al(e,t){for(var r={};e.length;){var n=e[0],a=n.code,o=n.message,i=n.path.join(".");if(!r[i])if("unionErrors"in n){var s=n.unionErrors[0].errors[0];r[i]={message:s.message,type:s.code}}else r[i]={message:o,type:a};if("unionErrors"in n&&n.unionErrors.forEach(function(t){return t.errors.forEach(function(t){return e.push(t)})}),t){var l=r[i].types,c=l&&l[n.code];r[i]=La(i,t,r,a,c?[].concat(c,n.message):n.message)}e.shift()}return r}function _l(e,t){for(var r={};e.length;){var n=e[0],a=n.code,o=n.message,i=n.path.join(".");if(!r[i])if("invalid_union"===n.code&&n.errors.length>0){var s=n.errors[0][0];r[i]={message:s.message,type:s.code}}else r[i]={message:o,type:a};if("invalid_union"===n.code&&n.errors.forEach(function(t){return t.forEach(function(t){return e.push(t)})}),t){var l=r[i].types,c=l&&l[n.code];r[i]=La(i,t,r,a,c?[].concat(c,n.message):n.message)}e.shift()}return r}function Tl(e,t,r){if(void 0===r&&(r={}),function(e){return"_def"in e&&"object"==typeof e._def&&"typeName"in e._def}(e))return function(n,a,o){try{return Promise.resolve(El(function(){return Promise.resolve(e["sync"===r.mode?"parse":"parseAsync"](n,t)).then(function(e){return o.shouldUseNativeValidation&&ko({},o),{errors:{},values:r.raw?Object.assign({},n):e}})},function(e){if(function(e){return Array.isArray(null==e?void 0:e.issues)}(e))return{values:{},errors:No(Al(e.errors,!o.shouldUseNativeValidation&&"all"===o.criteriaMode),o)};throw e}))}catch(e){return Promise.reject(e)}};if(function(e){return"_zod"in e&&"object"==typeof e._zod}(e))return function(n,a,o){try{return Promise.resolve(El(function(){return Promise.resolve(("sync"===r.mode?si:ci)(e,n,t)).then(function(e){return o.shouldUseNativeValidation&&ko({},o),{errors:{},values:r.raw?Object.assign({},n):e}})},function(e){if(function(e){return e instanceof ai}(e))return{values:{},errors:No(_l(e.issues,!o.shouldUseNativeValidation&&"all"===o.criteriaMode),o)};throw e}))}catch(e){return Promise.reject(e)}};throw new Error("Invalid input: not a Zod schema")}
3
3
  /**
4
4
  * @license lucide-react v0.544.0 - ISC
5
5
  *