@medplum/app 5.1.2 → 5.1.3

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.
@@ -53,7 +53,7 @@ ${h}`}function Ra({color:e,theme:t,autoContrast:n}){return(typeof n=="boolean"?n
53
53
  `),s=!1),Object.assign(Object.assign({},e),{allowNegative:s})}function Gz(e){e=qz(e),e.decimalSeparator,e.allowedDecimalSeparators,e.thousandsGroupStyle;var t=e.suffix,n=e.allowNegative,r=e.allowLeadingZeros,i=e.onKeyDown;i===void 0&&(i=hs);var s=e.onBlur;s===void 0&&(s=hs);var c=e.thousandSeparator,u=e.decimalScale,f=e.fixedDecimalScale,h=e.prefix;h===void 0&&(h="");var m=e.defaultValue,g=e.value,y=e.valueIsNumericString,x=e.onValueChange,S=hA(e,["decimalSeparator","allowedDecimalSeparators","thousandsGroupStyle","suffix","allowNegative","allowLeadingZeros","onKeyDown","onBlur","thousandSeparator","decimalScale","fixedDecimalScale","prefix","defaultValue","value","valueIsNumericString","onValueChange"]),w=zm(e),C=w.decimalSeparator,T=w.allowedDecimalSeparators,R=function(L){return bT(L,e)},E=function(L,I){return Fz(L,I,e)},_=Kc(g)?m:g,P=y??Vz(_,h,t);Kc(g)?Kc(m)||(P=P||typeof m=="number"):P=P||typeof g=="number";var O=function(L){return pA(L)?L:(typeof L=="number"&&(L=vA(L)),P&&typeof u=="number"?yT(L,u,!!f):L)},k=xA(O(g),O(m),!!P,R,E,x),A=k[0],z=A.numAsString,U=A.formattedValue,K=k[1],W=function(L){var I=L.target,$=L.key,V=I.selectionStart,X=I.selectionEnd,M=I.value;if(M===void 0&&(M=""),($==="Backspace"||$==="Delete")&&X<h.length){L.preventDefault();return}if(V!==X){i(L);return}$==="Backspace"&&M[0]==="-"&&V===h.length+1&&n&&cl(I,1),u&&f&&($==="Backspace"&&M[V-1]===C?(cl(I,V-1),L.preventDefault()):$==="Delete"&&M[V]===C&&L.preventDefault()),T?.includes($)&&M[V]===C&&cl(I,V+1);var F=c===!0?",":c;$==="Backspace"&&M[V-1]===F&&cl(I,V-1),$==="Delete"&&M[V]===F&&cl(I,V+1),i(L)},ee=function(L){var I=z;if(I.match(/\d/g)||(I=""),r||(I=Dz(I)),f&&u&&(I=yT(I,u,f)),I!==z){var $=bT(I,e);K({formattedValue:$,value:I,floatValue:parseFloat(I)},{event:L,source:Bd.event})}s(L)},B=function(L){return L===C?!0:Vd(L)},G=function(L){var I=L.currentValue,$=L.lastValue,V=L.formattedValue,X=L.currentValueIndex,M=L.formattedValueIndex,F=I[X],ie=V[M],de=yA($,I),Se=de.to,Ce=function(je){return E(je).indexOf(".")+h.length};return g===0&&f&&u&&I[Se.start]===C&&Ce(I)<X&&Ce(V)>M?!1:X>=Se.start&&X<Se.end&&T&&T.includes(F)&&ie===C?!0:F===ie};return Object.assign(Object.assign({},S),{value:U,valueIsNumericString:!1,isValidInputCharacter:B,isCharacterSame:G,onValueChange:K,format:R,removeFormatting:E,getCaretBoundary:function(L){return Hz(L,e)},onKeyDown:W,onBlur:ee})}function Wz(e){var t=Gz(e);return Ln.createElement($z,Object.assign({},t))}var Fx={root:"m_e2f5cd4e",controls:"m_95e17d22",control:"m_80b4b171"};function ST({direction:e,style:t,...n}){return a.jsx("svg",{style:{width:"var(--ni-chevron-size)",height:"var(--ni-chevron-size)",transform:e==="up"?"rotate(180deg)":void 0,...t},viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n,children:a.jsx("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:"currentColor",fillRule:"evenodd",clipRule:"evenodd"})})}const Qz=/^(0\.0*|-0(\.0*)?)$/,Yz=/^-?0\d+(\.\d+)?\.?$/,Kz=/\.\d*0$/,bA=/^-?\d+\.$/;function Hx(e){return typeof e=="string"&&e!==""&&!Number.isNaN(Number(e))}function Ky(e){return typeof e=="number"?e<Number.MAX_SAFE_INTEGER:e===""||Hx(e)&&Number(e)<Number.MAX_SAFE_INTEGER}function Xz(e){return e.toString().replace(".","").length}function Jz(e,t){return(typeof e=="number"?e<Number.MAX_SAFE_INTEGER:!Number.isNaN(Number(e)))&&!Number.isNaN(e)&&Xz(t)<14&&t!==""}function jT(e,t,n){if(e===void 0)return!0;const r=t===void 0||e>=t,i=n===void 0||e<=n;return r&&i}const Zz={step:1,clampBehavior:"blur",allowDecimal:!0,allowNegative:!0,withKeyboardEvents:!0,allowLeadingZeros:!0,trimLeadingZeroesOnBlur:!0,startValue:0,allowedDecimalSeparators:[".",","]},e$=(e,{size:t})=>({controls:{"--ni-chevron-size":ot(t,"ni-chevron-size")}});function t$(e,t,n){const r=e.toString(),i=bA.test(r),s=r.replace(/^0+(?=\d)/,""),c=parseFloat(s);if(Number.isNaN(c))return s;if(c>Number.MAX_SAFE_INTEGER)return t!==void 0?t:s;const u=Dd(c,n,t);return i?`${u.toString().replace(/^0+(?=\d)/,"")}.`:u}const hr=ve((e,t)=>{const n=ae("NumberInput",Zz,e),{className:r,classNames:i,styles:s,unstyled:c,vars:u,onChange:f,onValueChange:h,value:m,defaultValue:g,max:y,min:x,step:S,hideControls:w,rightSection:C,isAllowed:T,clampBehavior:R,onBlur:E,allowDecimal:_,decimalScale:P,onKeyDown:O,onKeyDownCapture:k,handlersRef:A,startValue:z,disabled:U,rightSectionPointerEvents:K,allowNegative:W,readOnly:ee,size:B,rightSectionWidth:G,stepHoldInterval:L,stepHoldDelay:I,allowLeadingZeros:$,withKeyboardEvents:V,trimLeadingZeroesOnBlur:X,allowedDecimalSeparators:M,attributes:F,...ie}=n,de=$e({name:"NumberInput",classes:Fx,props:n,classNames:i,styles:s,unstyled:c,attributes:F,vars:u,varsResolver:e$}),{resolvedClassNames:Se,resolvedStyles:Ce}=Ll({classNames:i,styles:s,props:n}),[je,Ke]=or({value:m,defaultValue:g,finalValue:"",onChange:f}),_e=I!==void 0&&L!==void 0,ht=v.useRef(null),Ct=v.useRef(null),Et=v.useRef(0),qe=(he,ke)=>{ke.source==="event"&&Ke(Jz(he.floatValue,he.value)&&!Qz.test(he.value)&&!($&&Yz.test(he.value))&&!Kz.test(he.value)&&!bA.test(he.value)?he.floatValue:he.value),h?.(he,ke)},ct=he=>{const ke=String(he).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return ke?Math.max(0,(ke[1]?ke[1].length:0)-(ke[2]?+ke[2]:0)):0},Tt=he=>{ht.current&&typeof he<"u"&&ht.current.setSelectionRange(he,he)},It=v.useRef(Np);It.current=()=>{if(!Ky(je))return;let he;const ke=ct(je),Dt=ct(S),Rt=Math.max(ke,Dt),At=10**Rt;if(!Hx(je)&&(typeof je!="number"||Number.isNaN(je)))he=Dd(z,x,y);else if(y!==void 0){const vn=(Math.round(Number(je)*At)+Math.round(S*At))/At;he=vn<=y?vn:y}else he=(Math.round(Number(je)*At)+Math.round(S*At))/At;const ln=he.toFixed(Rt);Ke(parseFloat(ln)),h?.({floatValue:parseFloat(ln),formattedValue:ln,value:ln},{source:"increment"}),setTimeout(()=>Tt(ht.current?.value.length),0)};const Te=v.useRef(Np);Te.current=()=>{if(!Ky(je))return;let he;const ke=x!==void 0?x:W?Number.MIN_SAFE_INTEGER:0,Dt=ct(je),Rt=ct(S),At=Math.max(Dt,Rt),ln=10**At;if(!Hx(je)&&typeof je!="number"||Number.isNaN(je))he=Dd(z,ke,y);else{const lr=(Math.round(Number(je)*ln)-Math.round(S*ln))/ln;he=ke!==void 0&&lr<ke?ke:lr}const vn=he.toFixed(At);Ke(parseFloat(vn)),h?.({floatValue:parseFloat(vn),formattedValue:vn,value:vn},{source:"decrement"}),setTimeout(()=>Tt(ht.current?.value.length),0)};const Oe=he=>{O?.(he),!(ee||!V)&&(he.key==="ArrowUp"&&(he.preventDefault(),It.current?.()),he.key==="ArrowDown"&&(he.preventDefault(),Te.current?.()))},Le=he=>{if(k?.(he),he.key==="Backspace"){const ke=ht.current;ke&&ke.selectionStart===0&&ke.selectionStart===ke.selectionEnd&&(he.preventDefault(),window.setTimeout(()=>Tt(0),0))}},Ie=he=>{let ke=je;R==="blur"&&typeof ke=="number"&&(ke=Dd(ke,x,y)),X&&typeof ke=="string"&&ct(ke)<15&&(ke=t$(ke,y,x)),je!==ke&&Ke(ke),E?.(he)};Ld(A,{increment:It.current,decrement:Te.current});const at=he=>{he?It.current?.():Te.current?.(),Et.current+=1},Ze=he=>{if(at(he),_e){const ke=typeof L=="number"?L:L(Et.current);Ct.current=window.setTimeout(()=>Ze(he),ke)}},dt=(he,ke)=>{he.preventDefault(),ht.current?.focus(),at(ke),_e&&(Ct.current=window.setTimeout(()=>Ze(ke),I))},ft=()=>{Ct.current&&window.clearTimeout(Ct.current),Ct.current=null,Et.current=0},Ee=a.jsxs("div",{...de("controls"),children:[a.jsx(An,{...de("control"),tabIndex:-1,"aria-hidden":!0,disabled:U||typeof je=="number"&&y!==void 0&&je>=y,mod:{direction:"up"},onMouseDown:he=>he.preventDefault(),onPointerDown:he=>{dt(he,!0)},onPointerUp:ft,onPointerLeave:ft,children:a.jsx(ST,{direction:"up"})}),a.jsx(An,{...de("control"),tabIndex:-1,"aria-hidden":!0,disabled:U||typeof je=="number"&&x!==void 0&&je<=x,mod:{direction:"down"},onMouseDown:he=>he.preventDefault(),onPointerDown:he=>{dt(he,!1)},onPointerUp:ft,onPointerLeave:ft,children:a.jsx(ST,{direction:"down"})})]});return a.jsx(Vr,{component:Wz,allowNegative:W,className:Ft(Fx.root,r),size:B,inputMode:"decimal",...ie,readOnly:ee,disabled:U,value:je,getInputRef:Vn(t,ht),onValueChange:qe,rightSection:w||ee||!Ky(je)?C:C||Ee,classNames:Se,styles:Ce,unstyled:c,__staticSelector:"NumberInput",decimalScale:_?P:0,onKeyDown:Oe,onKeyDownCapture:Le,rightSectionPointerEvents:K??(U?"none":void 0),rightSectionWidth:G??`var(--ni-right-section-width-${B||"sm"})`,allowLeadingZeros:$,allowedDecimalSeparators:M,onBlur:Ie,attributes:F,isAllowed:he=>R==="strict"?T?T(he)&&jT(he.floatValue,x,y):jT(he.floatValue,x,y):T?T(he):!0})});hr.classes={...Vr.classes,...Fx};hr.displayName="@mantine/core/NumberInput";var vf={root:"m_4addd315",control:"m_326d024a",dots:"m_4ad7767d"};const[n$,$m]=Or("Pagination.Root component was not found in tree"),r$={withPadding:!0},yf=ve((e,t)=>{const n=ae("PaginationControl",r$,e),{classNames:r,className:i,style:s,styles:c,vars:u,active:f,disabled:h,withPadding:m,mod:g,...y}=n,x=$m(),S=h||x.disabled;return a.jsx(An,{ref:t,disabled:S,mod:[{active:f,disabled:S,"with-padding":m},g],...x.getStyles("control",{className:i,style:s,classNames:r,styles:c,active:!S}),...y})});yf.classes=vf;yf.displayName="@mantine/core/PaginationControl";function xf({style:e,children:t,path:n,...r}){return a.jsx("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",style:{width:"calc(var(--pagination-control-size) / 1.8)",height:"calc(var(--pagination-control-size) / 1.8)",...e},...r,children:a.jsx("path",{d:n,fill:"currentColor"})})}const i$=e=>a.jsx(xf,{...e,path:"M8.781 8l-3.3-3.3.943-.943L10.667 8l-4.243 4.243-.943-.943 3.3-3.3z"}),o$=e=>a.jsx(xf,{...e,path:"M7.219 8l3.3 3.3-.943.943L5.333 8l4.243-4.243.943.943-3.3 3.3z"}),a$=e=>a.jsx(xf,{...e,path:"M6.85355 3.85355C7.04882 3.65829 7.04882 3.34171 6.85355 3.14645C6.65829 2.95118 6.34171 2.95118 6.14645 3.14645L2.14645 7.14645C1.95118 7.34171 1.95118 7.65829 2.14645 7.85355L6.14645 11.8536C6.34171 12.0488 6.65829 12.0488 6.85355 11.8536C7.04882 11.6583 7.04882 11.3417 6.85355 11.1464L3.20711 7.5L6.85355 3.85355ZM12.8536 3.85355C13.0488 3.65829 13.0488 3.34171 12.8536 3.14645C12.6583 2.95118 12.3417 2.95118 12.1464 3.14645L8.14645 7.14645C7.95118 7.34171 7.95118 7.65829 8.14645 7.85355L12.1464 11.8536C12.3417 12.0488 12.6583 12.0488 12.8536 11.8536C13.0488 11.6583 13.0488 11.3417 12.8536 11.1464L9.20711 7.5L12.8536 3.85355Z"}),s$=e=>a.jsx(xf,{...e,path:"M2.14645 11.1464C1.95118 11.3417 1.95118 11.6583 2.14645 11.8536C2.34171 12.0488 2.65829 12.0488 2.85355 11.8536L6.85355 7.85355C7.04882 7.65829 7.04882 7.34171 6.85355 7.14645L2.85355 3.14645C2.65829 2.95118 2.34171 2.95118 2.14645 3.14645C1.95118 3.34171 1.95118 3.65829 2.14645 3.85355L5.79289 7.5L2.14645 11.1464ZM8.14645 11.1464C7.95118 11.3417 7.95118 11.6583 8.14645 11.8536C8.34171 12.0488 8.65829 12.0488 8.85355 11.8536L12.8536 7.85355C13.0488 7.65829 13.0488 7.34171 12.8536 7.14645L8.85355 3.14645C8.65829 2.95118 8.34171 2.95118 8.14645 3.14645C7.95118 3.34171 7.95118 3.65829 8.14645 3.85355L11.7929 7.5L8.14645 11.1464Z"}),l$=e=>a.jsx(xf,{...e,path:"M2 8c0-.733.6-1.333 1.333-1.333.734 0 1.334.6 1.334 1.333s-.6 1.333-1.334 1.333C2.6 9.333 2 8.733 2 8zm9.333 0c0-.733.6-1.333 1.334-1.333C13.4 6.667 14 7.267 14 8s-.6 1.333-1.333 1.333c-.734 0-1.334-.6-1.334-1.333zM6.667 8c0-.733.6-1.333 1.333-1.333s1.333.6 1.333 1.333S8.733 9.333 8 9.333 6.667 8.733 6.667 8z"}),c$={icon:l$},Um=ve((e,t)=>{const n=ae("PaginationDots",c$,e),{classNames:r,className:i,style:s,styles:c,vars:u,icon:f,...h}=n,m=$m();return a.jsx(le,{ref:t,...m.getStyles("dots",{className:i,style:s,styles:c,classNames:r}),...h,children:a.jsx(f,{style:{width:"calc(var(--pagination-control-size) / 1.8)",height:"calc(var(--pagination-control-size) / 1.8)"}})})});Um.classes=vf;Um.displayName="@mantine/core/PaginationDots";function Bm({icon:e,name:t,action:n,type:r}){const i={icon:e},s=v.forwardRef((c,u)=>{const{icon:f,...h}=ae(t,i,c),m=$m(),g=r==="next"?m.active===m.total:m.active===1;return a.jsx(yf,{disabled:m.disabled||g,ref:u,onClick:m[n],withPadding:!1,...h,children:a.jsx(f,{className:"mantine-rotate-rtl",style:{width:"calc(var(--pagination-control-size) / 1.8)",height:"calc(var(--pagination-control-size) / 1.8)"}})})});return s.displayName=`@mantine/core/${t}`,s}const SA=Bm({icon:i$,name:"PaginationNext",action:"onNext",type:"next"}),jA=Bm({icon:o$,name:"PaginationPrevious",action:"onPrevious",type:"previous"}),wA=Bm({icon:a$,name:"PaginationFirst",action:"onFirst",type:"previous"}),CA=Bm({icon:s$,name:"PaginationLast",action:"onLast",type:"next"});function G0({dotsIcon:e}){const t=$m(),n=t.range.map((r,i)=>r==="dots"?a.jsx(Um,{icon:e},i):a.jsx(yf,{active:r===t.active,"aria-current":r===t.active?"page":void 0,onClick:()=>t.onChange(r),disabled:t.disabled,...t.getItemProps?.(r),children:t.getItemProps?.(r)?.children??r},i));return a.jsx(a.Fragment,{children:n})}G0.displayName="@mantine/core/PaginationItems";const u$={siblings:1,boundaries:1},d$=(e,{size:t,radius:n,color:r,autoContrast:i})=>({root:{"--pagination-control-radius":n===void 0?void 0:Ht(n),"--pagination-control-size":ot(t,"pagination-control-size"),"--pagination-control-fz":Kn(t),"--pagination-active-bg":r?Kt(r,e):void 0,"--pagination-active-color":Il(i,e)?Ra({color:r,theme:e,autoContrast:i}):void 0}}),Vm=ve((e,t)=>{const n=ae("PaginationRoot",u$,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,total:h,value:m,defaultValue:g,onChange:y,disabled:x,siblings:S,boundaries:w,color:C,radius:T,onNextPage:R,onPreviousPage:E,onFirstPage:_,onLastPage:P,getItemProps:O,autoContrast:k,attributes:A,...z}=n,U=$e({name:"Pagination",classes:vf,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:A,vars:f,varsResolver:d$}),{range:K,setPage:W,next:ee,previous:B,active:G,first:L,last:I}=zM({page:m,initialPage:g,onChange:y,total:h,siblings:S,boundaries:w}),$=pr(R,ee),V=pr(E,B),X=pr(_,L),M=pr(P,I);return a.jsx(n$,{value:{total:h,range:K,active:G,disabled:x,getItemProps:O,onChange:W,onNext:$,onPrevious:V,onFirst:X,onLast:M,getStyles:U},children:a.jsx(le,{ref:t,...U("root"),...z})})});Vm.classes=vf;Vm.displayName="@mantine/core/PaginationRoot";const f$={withControls:!0,withPages:!0,siblings:1,boundaries:1,gap:8},qi=ve((e,t)=>{const n=ae("Pagination",f$,e),{withEdges:r,withControls:i,getControlProps:s,nextIcon:c,previousIcon:u,lastIcon:f,firstIcon:h,dotsIcon:m,total:g,gap:y,hideWithOnePage:x,withPages:S,...w}=n;return g<=0||x&&g===1?null:a.jsx(Vm,{ref:t,total:g,...w,children:a.jsxs(xe,{gap:y,children:[r&&a.jsx(wA,{icon:h,...s?.("first")}),i&&a.jsx(jA,{icon:u,...s?.("previous")}),S&&a.jsx(G0,{dotsIcon:m}),i&&a.jsx(SA,{icon:c,...s?.("next")}),r&&a.jsx(CA,{icon:f,...s?.("last")})]})})});qi.classes=vf;qi.displayName="@mantine/core/Pagination";qi.Root=Vm;qi.Control=yf;qi.Dots=Um;qi.First=wA;qi.Last=CA;qi.Next=SA;qi.Previous=jA;qi.Items=G0;var qx={root:"m_f61ca620",input:"m_ccf8da4c",innerInput:"m_f2d85dd2",visibilityToggle:"m_b1072d44"};const h$=({reveal:e})=>a.jsx("svg",{viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{width:"var(--psi-icon-size)",height:"var(--psi-icon-size)"},children:a.jsx("path",{d:e?"M13.3536 2.35355C13.5488 2.15829 13.5488 1.84171 13.3536 1.64645C13.1583 1.45118 12.8417 1.45118 12.6464 1.64645L10.6828 3.61012C9.70652 3.21671 8.63759 3 7.5 3C4.30786 3 1.65639 4.70638 0.0760002 7.23501C-0.0253338 7.39715 -0.0253334 7.60288 0.0760014 7.76501C0.902945 9.08812 2.02314 10.1861 3.36061 10.9323L1.64645 12.6464C1.45118 12.8417 1.45118 13.1583 1.64645 13.3536C1.84171 13.5488 2.15829 13.5488 2.35355 13.3536L4.31723 11.3899C5.29348 11.7833 6.36241 12 7.5 12C10.6921 12 13.3436 10.2936 14.924 7.76501C15.0253 7.60288 15.0253 7.39715 14.924 7.23501C14.0971 5.9119 12.9769 4.81391 11.6394 4.06771L13.3536 2.35355ZM9.90428 4.38861C9.15332 4.1361 8.34759 4 7.5 4C4.80285 4 2.52952 5.37816 1.09622 7.50001C1.87284 8.6497 2.89609 9.58106 4.09974 10.1931L9.90428 4.38861ZM5.09572 10.6114L10.9003 4.80685C12.1039 5.41894 13.1272 6.35031 13.9038 7.50001C12.4705 9.62183 10.1971 11 7.5 11C6.65241 11 5.84668 10.8639 5.09572 10.6114Z":"M7.5 11C4.80285 11 2.52952 9.62184 1.09622 7.50001C2.52952 5.37816 4.80285 4 7.5 4C10.1971 4 12.4705 5.37816 13.9038 7.50001C12.4705 9.62183 10.1971 11 7.5 11ZM7.5 3C4.30786 3 1.65639 4.70638 0.0760002 7.23501C-0.0253338 7.39715 -0.0253334 7.60288 0.0760014 7.76501C1.65639 10.2936 4.30786 12 7.5 12C10.6921 12 13.3436 10.2936 14.924 7.76501C15.0253 7.60288 15.0253 7.39715 14.924 7.23501C13.3436 4.70638 10.6921 3 7.5 3ZM7.5 9.5C8.60457 9.5 9.5 8.60457 9.5 7.5C9.5 6.39543 8.60457 5.5 7.5 5.5C6.39543 5.5 5.5 6.39543 5.5 7.5C5.5 8.60457 6.39543 9.5 7.5 9.5Z",fill:"currentColor",fillRule:"evenodd",clipRule:"evenodd"})}),p$={visibilityToggleIcon:h$},m$=(e,{size:t})=>({root:{"--psi-icon-size":ot(t,"psi-icon-size"),"--psi-button-size":ot(t,"psi-button-size")}}),ao=ve((e,t)=>{const n=ae("PasswordInput",p$,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,required:h,error:m,leftSection:g,disabled:y,id:x,variant:S,inputContainer:w,description:C,label:T,size:R,errorProps:E,descriptionProps:_,labelProps:P,withAsterisk:O,inputWrapperOrder:k,wrapperProps:A,radius:z,rightSection:U,rightSectionWidth:K,rightSectionPointerEvents:W,leftSectionWidth:ee,visible:B,defaultVisible:G,onVisibilityChange:L,visibilityToggleIcon:I,visibilityToggleButtonProps:$,rightSectionProps:V,leftSectionProps:X,leftSectionPointerEvents:M,withErrorStyles:F,mod:ie,attributes:de,...Se}=n,Ce=vr(x),[je,Ke]=or({value:B,defaultValue:G,finalValue:!1,onChange:L}),_e=()=>Ke(!je),ht=$e({name:"PasswordInput",classes:qx,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:de,vars:f,varsResolver:m$}),{resolvedClassNames:Ct,resolvedStyles:Et}=Ll({classNames:r,styles:c,props:n}),{styleProps:qe,rest:ct}=_a(Se),Tt=E?.id||`${Ce}-error`,It=_?.id||`${Ce}-description`,Le=`${!!m&&typeof m!="boolean"?Tt:""} ${!!C?It:""}`,Ie=Le.trim().length>0?Le.trim():void 0,at=a.jsx(Pn,{...ht("visibilityToggle"),disabled:y,radius:z,"aria-hidden":!$,"aria-pressed":je,tabIndex:-1,...$,variant:$?.variant??"subtle",color:"gray",unstyled:u,onTouchEnd:Ze=>{Ze.preventDefault(),$?.onTouchEnd?.(Ze),_e()},onMouseDown:Ze=>{Ze.preventDefault(),$?.onMouseDown?.(Ze),_e()},onKeyDown:Ze=>{$?.onKeyDown?.(Ze),Ze.key===" "&&(Ze.preventDefault(),_e())},children:a.jsx(I,{reveal:je})});return a.jsx(mn.Wrapper,{required:h,id:Ce,label:T,error:m,description:C,size:R,classNames:Ct,styles:Et,__staticSelector:"PasswordInput",unstyled:u,withAsterisk:O,inputWrapperOrder:k,inputContainer:w,variant:S,labelProps:{...P,htmlFor:Ce},descriptionProps:{..._,id:It},errorProps:{...E,id:Tt},mod:ie,attributes:de,...ht("root"),...qe,...A,children:a.jsx(mn,{component:"div",error:m,leftSection:g,size:R,classNames:{...Ct,input:Ft(qx.input,Ct.input)},styles:Et,radius:z,disabled:y,__staticSelector:"PasswordInput",rightSectionWidth:K,rightSection:U??at,variant:S,unstyled:u,leftSectionWidth:ee,rightSectionPointerEvents:W||"all",rightSectionProps:V,leftSectionProps:X,leftSectionPointerEvents:M,withAria:!1,withErrorStyles:F,attributes:de,children:a.jsx("input",{required:h,"data-invalid":!!m||void 0,"data-with-left-section":!!g||void 0,...ht("innerInput"),disabled:y,id:Ce,ref:t,...ct,"aria-describedby":Ie,autoComplete:ct.autoComplete||"off",type:je?"text":"password"})})})});ao.classes={...Vr.classes,...qx};ao.displayName="@mantine/core/PasswordInput";var EA={root:"m_f3f1af94",inner:"m_89c4f5e4",icon:"m_f3ed6b2b",radio:"m_8a3dbb89","radio--outline":"m_1bfe9d39"};const[g$,TA]=Fo(),[v$,y$]=Fo();var RA={card:"m_9dc8ae12"};const x$={withBorder:!0},b$=(e,{radius:t})=>({card:{"--card-radius":Ht(t)}}),W0=ve((e,t)=>{const n=ae("RadioCard",x$,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,checked:h,mod:m,withBorder:g,value:y,onClick:x,name:S,onKeyDown:w,attributes:C,...T}=n,R=$e({name:"RadioCard",classes:RA,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:C,vars:f,varsResolver:b$,rootSelector:"card"}),{dir:E}=Rs(),_=TA(),P=typeof h=="boolean"?h:_?.value===y||!1,O=S||_?.name,k=A=>{if(w?.(A),["ArrowDown","ArrowUp","ArrowLeft","ArrowRight"].includes(A.nativeEvent.code)){A.preventDefault();const z=Array.from(document.querySelectorAll(`[role="radio"][name="${O||"__mantine"}"]`)),U=z.findIndex(ee=>ee===A.target),K=U+1>=z.length?0:U+1,W=U-1<0?z.length-1:U-1;A.nativeEvent.code==="ArrowDown"&&(z[K].focus(),z[K].click()),A.nativeEvent.code==="ArrowUp"&&(z[W].focus(),z[W].click()),A.nativeEvent.code==="ArrowLeft"&&(z[E==="ltr"?W:K].focus(),z[E==="ltr"?W:K].click()),A.nativeEvent.code==="ArrowRight"&&(z[E==="ltr"?K:W].focus(),z[E==="ltr"?K:W].click())}};return a.jsx(v$,{value:{checked:P},children:a.jsx(An,{ref:t,mod:[{"with-border":g,checked:P},m],...R("card"),...T,role:"radio","aria-checked":P,name:O,onClick:A=>{x?.(A),_?.onChange(y||"")},onKeyDown:k})})});W0.displayName="@mantine/core/RadioCard";W0.classes=RA;const Q0=ve((e,t)=>{const{value:n,defaultValue:r,onChange:i,size:s,wrapperProps:c,children:u,name:f,readOnly:h,disabled:m,...g}=ae("RadioGroup",null,e),y=vr(f),[x,S]=or({value:n,defaultValue:r,finalValue:"",onChange:i}),w=C=>!h&&S(typeof C=="string"?C:C.currentTarget.value);return a.jsx(g$,{value:{value:x,onChange:w,size:s,name:y,disabled:m},children:a.jsx(mn.Wrapper,{size:s,ref:t,...c,...g,labelElement:"div",__staticSelector:"RadioGroup",children:a.jsx(g0,{role:"radiogroup",children:u})})})});Q0.classes=mn.Wrapper.classes;Q0.displayName="@mantine/core/RadioGroup";function _A({size:e,style:t,...n}){return a.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 5 5",style:{width:ce(e),height:ce(e),...t},"aria-hidden":!0,...n,children:a.jsx("circle",{cx:"2.5",cy:"2.5",r:"2.5",fill:"currentColor"})})}var DA={indicator:"m_717d7ff6",icon:"m_3e4da632","indicator--outline":"m_2980836c"};const S$={icon:_A},j$=(e,{radius:t,color:n,size:r,iconColor:i,variant:s,autoContrast:c})=>{const u=ei({color:n||e.primaryColor,theme:e}),f=u.isThemeColor&&u.shade===void 0?`var(--mantine-color-${u.color}-outline)`:u.color;return{indicator:{"--radio-size":ot(r,"radio-size"),"--radio-radius":t===void 0?void 0:Ht(t),"--radio-color":s==="outline"?f:Kt(n,e),"--radio-icon-size":ot(r,"radio-icon-size"),"--radio-icon-color":i?Kt(i,e):Il(c,e)?Ra({color:n,theme:e,autoContrast:c}):void 0}}},Y0=ve((e,t)=>{const n=ae("RadioIndicator",S$,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,icon:h,radius:m,color:g,iconColor:y,autoContrast:x,checked:S,mod:w,variant:C,disabled:T,attributes:R,...E}=n,_=$e({name:"RadioIndicator",classes:DA,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:R,vars:f,varsResolver:j$,rootSelector:"indicator"}),P=y$(),O=typeof S=="boolean"?S:P?.checked||!1;return a.jsx(le,{ref:t,..._("indicator",{variant:C}),variant:C,mod:[{checked:O,disabled:T},w],...E,children:a.jsx(h,{..._("icon")})})});Y0.displayName="@mantine/core/RadioIndicator";Y0.classes=DA;const w$={labelPosition:"right"},C$=(e,{size:t,radius:n,color:r,iconColor:i,variant:s,autoContrast:c})=>{const u=ei({color:r||e.primaryColor,theme:e}),f=u.isThemeColor&&u.shade===void 0?`var(--mantine-color-${u.color}-outline)`:u.color;return{root:{"--radio-size":ot(t,"radio-size"),"--radio-radius":n===void 0?void 0:Ht(n),"--radio-color":s==="outline"?f:Kt(r,e),"--radio-icon-color":i?Kt(i,e):Il(c,e)?Ra({color:r,theme:e,autoContrast:c}):void 0,"--radio-icon-size":ot(t,"radio-icon-size")}}},Rr=ve((e,t)=>{const n=ae("Radio",w$,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,id:h,size:m,label:g,labelPosition:y,description:x,error:S,radius:w,color:C,variant:T,disabled:R,wrapperProps:E,icon:_=_A,rootRef:P,iconColor:O,onChange:k,mod:A,attributes:z,checked:U,...K}=n,W=$e({name:"Radio",classes:EA,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:z,vars:f,varsResolver:C$}),ee=TA(),B=ee?.size??m,G=n.size?m:B,{styleProps:L,rest:I}=_a(K),$=vr(h),V=ee?ee.value===I.value:void 0,X={checked:V??U,name:ee?.name??I.name,onChange:M=>{ee?.onChange(M),k?.(M)},disabled:ee?.disabled??R};return a.jsx(Em,{...W("root"),__staticSelector:"Radio",__stylesApiProps:n,id:$,size:G,labelPosition:y,label:g,description:x,error:S,disabled:X.disabled,classNames:r,styles:c,unstyled:u,"data-checked":(V??U)||void 0,variant:T,ref:P,mod:A,...L,...E,children:a.jsxs(le,{...W("inner"),mod:{"label-position":y},children:[a.jsx(le,{...W("radio",{focusable:!0,variant:T}),...I,...X,component:"input",mod:{error:!!S},ref:t,id:$,type:"radio"}),a.jsx(_,{...W("icon"),"aria-hidden":!0})]})})});Rr.classes=EA;Rr.displayName="@mantine/core/Radio";Rr.Group=Q0;Rr.Card=W0;Rr.Indicator=Y0;const E$={duration:100,transition:"fade"};function wT(e,t){return{...E$,...t,...e}}var Fm={tooltip:"m_1b3c8819",arrow:"m_f898399f"};function T$({offset:e,position:t,defaultOpened:n}){const[r,i]=v.useState(n),s=v.useRef(null),{x:c,y:u,elements:f,refs:h,update:m,placement:g}=qb({placement:t,middleware:[Bb({crossAxis:!0,padding:5,rootBoundary:"document"})]}),y=g.includes("right")?e:t.includes("left")?e*-1:0,x=g.includes("bottom")?e:t.includes("top")?e*-1:0,S=v.useCallback(({clientX:w,clientY:C})=>{h.setPositionReference({getBoundingClientRect(){return{width:0,height:0,x:w,y:C,left:w+y,top:C+x,right:w,bottom:C}}})},[f.reference]);return v.useEffect(()=>{if(h.floating.current){const w=s.current;w.addEventListener("mousemove",S);const C=xa(h.floating.current);return C.forEach(T=>{T.addEventListener("scroll",m)}),()=>{w.removeEventListener("mousemove",S),C.forEach(T=>{T.removeEventListener("scroll",m)})}}},[f.reference,h.floating.current,m,S,r]),{handleMouseMove:S,x:c,y:u,opened:r,setOpened:i,boundaryRef:s,floating:h.setFloating}}const R$={refProp:"ref",withinPortal:!0,offset:10,position:"right",zIndex:Br("popover")},_$=(e,{radius:t,color:n})=>({tooltip:{"--tooltip-radius":t===void 0?void 0:Ht(t),"--tooltip-bg":n?Kt(n,e):void 0,"--tooltip-color":n?"var(--mantine-color-white)":void 0}}),K0=ve((e,t)=>{const n=ae("TooltipFloating",R$,e),{children:r,refProp:i,withinPortal:s,style:c,className:u,classNames:f,styles:h,unstyled:m,radius:g,color:y,label:x,offset:S,position:w,multiline:C,zIndex:T,disabled:R,defaultOpened:E,variant:_,vars:P,portalProps:O,attributes:k,...A}=n,z=Nn(),U=$e({name:"TooltipFloating",props:n,classes:Fm,className:u,style:c,classNames:f,styles:h,unstyled:m,attributes:k,rootSelector:"tooltip",vars:P,varsResolver:_$}),{handleMouseMove:K,x:W,y:ee,opened:B,boundaryRef:G,floating:L,setOpened:I}=T$({offset:S,position:w,defaultOpened:E}),$=Ml(r);if(!$)throw new Error("[@mantine/core] Tooltip.Floating component children should be an element or a component that accepts ref, fragments, strings, numbers and other primitive values are not supported");const V=Vn(G,um($),t),X=$.props,M=ie=>{X.onMouseEnter?.(ie),K(ie),I(!0)},F=ie=>{X.onMouseLeave?.(ie),I(!1)};return a.jsxs(a.Fragment,{children:[a.jsx(ja,{...O,withinPortal:s,children:a.jsx(le,{...A,...U("tooltip",{style:{...v2(c,z),zIndex:T,display:!R&&B?"block":"none",top:(ee&&Math.round(ee))??"",left:(W&&Math.round(W))??""}}),variant:_,ref:L,mod:{multiline:C},children:x})}),v.cloneElement($,{...X,[i]:V,onMouseEnter:M,onMouseLeave:F})]})});K0.classes=Fm;K0.displayName="@mantine/core/TooltipFloating";const AA=v.createContext(!1),D$=AA.Provider,A$=()=>v.useContext(AA),k$={openDelay:0,closeDelay:0};function X0(e){const{openDelay:t,closeDelay:n,children:r}=ae("TooltipGroup",k$,e);return a.jsx(D$,{value:!0,children:a.jsx(FL,{delay:{open:t,close:n},children:r})})}X0.displayName="@mantine/core/TooltipGroup";X0.extend=e=>e;function P$(e){if(e===void 0)return{shift:!0,flip:!0};const t={...e};return e.shift===void 0&&(t.shift=!0),e.flip===void 0&&(t.flip=!0),t}function N$(e){const t=P$(e.middlewares),n=[O2(e.offset)];return t.shift&&n.push(Bb(typeof t.shift=="boolean"?{padding:8}:{padding:8,...t.shift})),t.flip&&n.push(typeof t.flip=="boolean"?zp():zp(t.flip)),n.push(M2({element:e.arrowRef,padding:e.arrowOffset})),t.inline?n.push(typeof t.inline=="boolean"?Ad():Ad(t.inline)):e.inline&&n.push(Ad()),n}function O$(e){const[t,n]=v.useState(e.defaultOpened),i=typeof e.opened=="boolean"?e.opened:t,s=A$(),c=vr(),u=v.useCallback(P=>{n(P),P&&T(c)},[c]),{x:f,y:h,context:m,refs:g,placement:y,middlewareData:{arrow:{x,y:S}={}}}=qb({strategy:e.strategy,placement:e.position,open:i,onOpenChange:u,middleware:N$(e),whileElementsMounted:zx}),{delay:w,currentId:C,setCurrentId:T}=HL(m,{id:c}),{getReferenceProps:R,getFloatingProps:E}=KL([BL(m,{enabled:e.events?.hover,delay:s?w:{open:e.openDelay,close:e.closeDelay},mouseOnly:!e.events?.touch}),YL(m,{enabled:e.events?.focus,visibleOnly:!0}),JL(m,{role:"tooltip"}),WL(m,{enabled:typeof e.opened>"u"})]);jl(()=>{e.onPositionChange?.(y)},[y]);const _=i&&C&&C!==c;return{x:f,y:h,arrowX:x,arrowY:S,reference:g.setReference,floating:g.setFloating,getFloatingProps:E,getReferenceProps:R,isGroupPhase:_,opened:i,placement:y}}const CT={position:"top",refProp:"ref",withinPortal:!0,arrowSize:4,arrowOffset:5,arrowRadius:0,arrowPosition:"side",offset:5,transitionProps:{duration:100,transition:"fade"},events:{hover:!0,focus:!1,touch:!1},zIndex:Br("popover"),positionDependencies:[],middlewares:{flip:!0,shift:!0,inline:!1}},M$=(e,{radius:t,color:n,variant:r,autoContrast:i})=>{const s=e.variantColorResolver({theme:e,color:n||e.primaryColor,autoContrast:i,variant:r||"filled"});return{tooltip:{"--tooltip-radius":t===void 0?void 0:Ht(t),"--tooltip-bg":n?s.background:void 0,"--tooltip-color":n?s.color:void 0}}},Zr=ve((e,t)=>{const n=ae("Tooltip",CT,e),{children:r,position:i,refProp:s,label:c,openDelay:u,closeDelay:f,onPositionChange:h,opened:m,defaultOpened:g,withinPortal:y,radius:x,color:S,classNames:w,styles:C,unstyled:T,style:R,className:E,withArrow:_,arrowSize:P,arrowOffset:O,arrowRadius:k,arrowPosition:A,offset:z,transitionProps:U,multiline:K,events:W,zIndex:ee,disabled:B,positionDependencies:G,onClick:L,onMouseEnter:I,onMouseLeave:$,inline:V,variant:X,keepMounted:M,vars:F,portalProps:ie,mod:de,floatingStrategy:Se,middlewares:Ce,autoContrast:je,attributes:Ke,target:_e,...ht}=ae("Tooltip",CT,n),{dir:Ct}=Rs(),Et=v.useRef(null),qe=O$({position:eD(Ct,i),closeDelay:f,openDelay:u,onPositionChange:h,opened:m,defaultOpened:g,events:W,arrowRef:Et,arrowOffset:O,offset:typeof z=="number"?z+(_?P/2:0):z,positionDependencies:[...G,_e??r],inline:V,strategy:Se,middlewares:Ce});v.useEffect(()=>{const Le=_e instanceof HTMLElement?_e:typeof _e=="string"?document.querySelector(_e):_e?.current||null;Le&&qe.reference(Le)},[_e,qe]);const ct=$e({name:"Tooltip",props:n,classes:Fm,className:E,style:R,classNames:w,styles:C,unstyled:T,attributes:Ke,rootSelector:"tooltip",vars:F,varsResolver:M$}),Tt=Ml(r);if(!_e&&!Tt)return null;if(_e){const Le=wT(U,{duration:100,transition:"fade"});return a.jsx(a.Fragment,{children:a.jsx(ja,{...ie,withinPortal:y,children:a.jsx(uo,{...Le,keepMounted:M,mounted:!B&&!!qe.opened,duration:qe.isGroupPhase?10:Le.duration,children:Ie=>a.jsxs(le,{...ht,"data-fixed":Se==="fixed"||void 0,variant:X,mod:[{multiline:K},de],...qe.getFloatingProps({ref:qe.floating,className:ct("tooltip").className,style:{...ct("tooltip").style,...Ie,zIndex:ee,top:qe.y??0,left:qe.x??0}}),children:[c,a.jsx($p,{ref:Et,arrowX:qe.arrowX,arrowY:qe.arrowY,visible:_,position:qe.placement,arrowSize:P,arrowOffset:O,arrowRadius:k,arrowPosition:A,...ct("arrow")})]})})})})}const It=Tt.props,Te=Vn(qe.reference,um(Tt),t),Oe=wT(U,{duration:100,transition:"fade"});return a.jsxs(a.Fragment,{children:[a.jsx(ja,{...ie,withinPortal:y,children:a.jsx(uo,{...Oe,keepMounted:M,mounted:!B&&!!qe.opened,duration:qe.isGroupPhase?10:Oe.duration,children:Le=>a.jsxs(le,{...ht,"data-fixed":Se==="fixed"||void 0,variant:X,mod:[{multiline:K},de],...qe.getFloatingProps({ref:qe.floating,className:ct("tooltip").className,style:{...ct("tooltip").style,...Le,zIndex:ee,top:qe.y??0,left:qe.x??0}}),children:[c,a.jsx($p,{ref:Et,arrowX:qe.arrowX,arrowY:qe.arrowY,visible:_,position:qe.placement,arrowSize:P,arrowOffset:O,arrowRadius:k,arrowPosition:A,...ct("arrow")})]})})}),v.cloneElement(Tt,qe.getReferenceProps({onClick:L,onMouseEnter:I,onMouseLeave:$,onMouseMove:n.onMouseMove,onPointerDown:n.onPointerDown,onPointerEnter:n.onPointerEnter,...It,className:Ft(E,It.className),[s]:Te}))]})});Zr.classes=Fm;Zr.displayName="@mantine/core/Tooltip";Zr.Floating=K0;Zr.Group=X0;function L$({size:e,thickness:t,sum:n,value:r,root:i,offset:s}){const c=(e*.9-t*2)/2,u=Math.PI*c*2/100,f=i||r===void 0?`${(100-n)*u}, ${n*u}`:`${r*u}, ${(100-r)*u}`;return{strokeWidth:Number.isNaN(t)?12:t,cx:e/2||0,cy:e/2||0,r:c||0,transform:i?`scale(1, -1) translate(0, -${e})`:void 0,strokeDasharray:f,strokeDashoffset:i?0:s||0}}function kA({size:e,value:t,offset:n,sum:r,thickness:i,root:s,color:c,lineRoundCaps:u,tooltip:f,getStyles:h,display:m,...g}){const y=Nn();return a.jsx(Zr.Floating,{disabled:!f,label:f,children:a.jsx(le,{component:"circle",...g,...h("curve"),__vars:{"--curve-color":c?Kt(c,y):void 0},fill:"none",strokeLinecap:u?"round":"butt",...L$({sum:r,size:e,thickness:i,value:t,offset:n,root:s})})})}kA.displayName="@mantine/core/Curve";function I$({size:e,thickness:t,sections:n,renderRoundedLineCaps:r,rootColor:i}){const s=n.reduce((m,g)=>m+g.value,0),c=Math.PI*((e*.9-t*2)/2)*2;let u=c;const f=[],h=[];for(let m=0;m<n.length;m+=1)f.push({sum:s,offset:u,data:n[m],root:!1}),u-=n[m].value/100*c;if(f.push({sum:s,offset:u,data:{color:i},root:!0}),h.push({...f[f.length-1],lineRoundCaps:!1}),f.length>2){h.push({...f[0],lineRoundCaps:r}),h.push({...f[f.length-2],lineRoundCaps:r});for(let m=1;m<=f.length-3;m+=1)h.push({...f[m],lineRoundCaps:!1})}else h.push({...f[0],lineRoundCaps:r});return h}var PA={root:"m_b32e4812",svg:"m_d43b5134",curve:"m_b1ca1fbf",label:"m_b23f9dc4"};function z$(e,t){return Math.min(e||12,(t||120)/4)}const $$={size:120,thickness:12},U$=(e,{size:t,thickness:n,transitionDuration:r})=>({root:{"--rp-size":ce(t),"--rp-label-offset":ce(n*2),"--rp-transition-duration":r?`${r}ms`:void 0}}),Hm=ve((e,t)=>{const n=ae("RingProgress",$$,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,label:h,sections:m,size:g,thickness:y,roundCaps:x,rootColor:S,transitionDuration:w,attributes:C,...T}=n,R=$e({name:"RingProgress",classes:PA,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:C,vars:f,varsResolver:U$}),E=z$(y,g),_=I$({size:g,thickness:E,sections:m,renderRoundedLineCaps:x,rootColor:S}).map(({data:P,sum:O,root:k,lineRoundCaps:A,offset:z},U)=>v.createElement(kA,{...P,key:U,size:g,thickness:E,sum:O,offset:z,color:P?.color,root:k,lineRoundCaps:A,getStyles:R}));return a.jsxs(le,{...R("root"),size:g,ref:t,...T,children:[a.jsx("svg",{...R("svg"),children:_}),h&&a.jsx("div",{...R("label"),children:h})]})});Hm.classes=PA;Hm.displayName="@mantine/core/RingProgress";var NA={root:"m_cf365364",indicator:"m_9e182ccd",label:"m_1738fcb2",input:"m_1714d588",control:"m_69686b9b",innerLabel:"m_78882f40"};const B$={withItemsBorders:!0},V$=(e,{radius:t,color:n,transitionDuration:r,size:i,transitionTimingFunction:s})=>({root:{"--sc-radius":t===void 0?void 0:Ht(t),"--sc-color":n?Kt(n,e):void 0,"--sc-shadow":n?void 0:"var(--mantine-shadow-xs)","--sc-transition-duration":r===void 0?void 0:`${r}ms`,"--sc-transition-timing-function":s,"--sc-padding":ot(i,"sc-padding"),"--sc-font-size":Kn(i)}}),Cl=ve((e,t)=>{const n=ae("SegmentedControl",B$,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,data:h,value:m,defaultValue:g,onChange:y,size:x,name:S,disabled:w,readOnly:C,fullWidth:T,orientation:R,radius:E,color:_,transitionDuration:P,transitionTimingFunction:O,variant:k,autoContrast:A,withItemsBorders:z,mod:U,attributes:K,...W}=n,ee=$e({name:"SegmentedControl",props:n,classes:NA,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:K,vars:f,varsResolver:V$}),B=Nn(),G=h.map(_e=>typeof _e=="string"?{label:_e,value:_e}:_e),L=KM(),[I,$]=v.useState(Op()),[V,X]=v.useState(null),[M,F]=v.useState({}),ie=(_e,ht)=>{M[ht]=_e,F(M)},[de,Se]=or({value:m,defaultValue:g,finalValue:Array.isArray(h)?G.find(_e=>!_e.disabled)?.value??h[0]?.value??null:null,onChange:y}),Ce=vr(S),je=G.map(_e=>v.createElement(le,{...ee("control"),mod:{active:de===_e.value,orientation:R},key:_e.value},v.createElement("input",{...ee("input"),disabled:w||_e.disabled,type:"radio",name:Ce,value:_e.value,id:`${Ce}-${_e.value}`,checked:de===_e.value,onChange:()=>!C&&Se(_e.value),"data-focus-ring":B.focusRing,key:`${_e.value}-input`}),v.createElement(le,{component:"label",...ee("label"),mod:{active:de===_e.value&&!(w||_e.disabled),disabled:w||_e.disabled,"read-only":C},htmlFor:`${Ce}-${_e.value}`,ref:ht=>ie(ht,_e.value),__vars:{"--sc-label-color":_!==void 0?Ra({color:_,theme:B,autoContrast:A}):void 0},key:`${_e.value}-label`},a.jsx("span",{...ee("innerLabel"),children:_e.label})))),Ke=Vn(t,_e=>X(_e));return BM(()=>{$(Op())},[h.length]),h.length===0?null:a.jsxs(le,{...ee("root"),variant:k,size:x,ref:Ke,mod:[{"full-width":T,orientation:R,initialized:L,"with-items-borders":z},U],...W,role:"radiogroup","data-disabled":w,children:[typeof de=="string"&&a.jsx(Zb,{target:M[de],parent:V,component:"span",transitionDuration:"var(--sc-transition-duration)",...ee("indicator")},I),je]})});Cl.classes=NA;Cl.displayName="@mantine/core/SegmentedControl";var OA={container:"m_925c2d2c",root:"m_2415a157"};function F$({spacing:e,verticalSpacing:t,cols:n,selector:r}){const i=Nn(),s=t===void 0?e:t,c=Es({"--sg-spacing-x":Yn(ro(e)),"--sg-spacing-y":Yn(ro(s)),"--sg-cols":ro(n)?.toString()}),u=hn(i.breakpoints).reduce((m,g)=>(m[g]||(m[g]={}),typeof e=="object"&&e[g]!==void 0&&(m[g]["--sg-spacing-x"]=Yn(e[g])),typeof s=="object"&&s[g]!==void 0&&(m[g]["--sg-spacing-y"]=Yn(s[g])),typeof n=="object"&&n[g]!==void 0&&(m[g]["--sg-cols"]=n[g]),m),{}),h=Md(hn(u),i.breakpoints).filter(m=>hn(u[m.value]).length>0).map(m=>({query:`(min-width: ${i.breakpoints[m.value]})`,styles:u[m.value]}));return a.jsx(zl,{styles:c,media:h,selector:r})}function Xy(e){return typeof e=="object"&&e!==null?hn(e):[]}function H$(e){return e.sort((t,n)=>Od(t)-Od(n))}function q$({spacing:e,verticalSpacing:t,cols:n}){const r=Array.from(new Set([...Xy(e),...Xy(t),...Xy(n)]));return H$(r)}function G$({spacing:e,verticalSpacing:t,cols:n,selector:r}){const i=t===void 0?e:t,s=Es({"--sg-spacing-x":Yn(ro(e)),"--sg-spacing-y":Yn(ro(i)),"--sg-cols":ro(n)?.toString()}),c=q$({spacing:e,verticalSpacing:t,cols:n}),u=c.reduce((h,m)=>(h[m]||(h[m]={}),typeof e=="object"&&e[m]!==void 0&&(h[m]["--sg-spacing-x"]=Yn(e[m])),typeof i=="object"&&i[m]!==void 0&&(h[m]["--sg-spacing-y"]=Yn(i[m])),typeof n=="object"&&n[m]!==void 0&&(h[m]["--sg-cols"]=n[m]),h),{}),f=c.map(h=>({query:`simple-grid (min-width: ${h})`,styles:u[h]}));return a.jsx(zl,{styles:s,container:f,selector:r})}const W$={cols:1,spacing:"md",type:"media"},qm=ve((e,t)=>{const n=ae("SimpleGrid",W$,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,cols:h,verticalSpacing:m,spacing:g,type:y,attributes:x,...S}=n,w=$e({name:"SimpleGrid",classes:OA,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:x,vars:f}),C=sf();return y==="container"?a.jsxs(a.Fragment,{children:[a.jsx(G$,{...n,selector:`.${C}`}),a.jsx("div",{...w("container"),children:a.jsx(le,{ref:t,...w("root",{className:C}),...S})})]}):a.jsxs(a.Fragment,{children:[a.jsx(F$,{...n,selector:`.${C}`}),a.jsx(le,{ref:t,...w("root",{className:C}),...S})]})});qm.classes=OA;qm.displayName="@mantine/core/SimpleGrid";const MA=ve((e,t)=>{const{w:n,h:r,miw:i,mih:s,...c}=ae("Space",null,e);return a.jsx(le,{ref:t,...c,w:n,miw:i??n,h:r,mih:s??r})});MA.displayName="@mantine/core/Space";var LA={root:"m_6d731127"};const Q$={gap:"md",align:"stretch",justify:"flex-start"},Y$=(e,{gap:t,align:n,justify:r})=>({root:{"--stack-gap":Yn(t),"--stack-align":n,"--stack-justify":r}}),Ne=ve((e,t)=>{const n=ae("Stack",Q$,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,align:h,justify:m,gap:g,variant:y,attributes:x,...S}=n,w=$e({name:"Stack",props:n,classes:LA,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:x,vars:f,varsResolver:Y$});return a.jsx(le,{ref:t,...w("root"),variant:y,...S})});Ne.classes=LA;Ne.displayName="@mantine/core/Stack";const[K$,X$]=Or("Stepper component was not found in tree");var J0={root:"m_cbb4ea7e",steps:"m_aaf89d0b",separator:"m_2a371ac9",content:"m_78da155d",step:"m_cbb57068","step--horizontal":"m_f56b1e2c","step--vertical":"m_833edb7e",verticalSeparator:"m_6496b3f3",stepWrapper:"m_818e70b",stepIcon:"m_1959ad01",stepCompletedIcon:"m_a79331dc",stepBody:"m_1956aa2a",stepLabel:"m_12051f6c",stepDescription:"m_164eea74"};const Bp=()=>null;Bp.displayName="@mantine/core/StepperCompleted";const lp=(e,t)=>typeof e=="function"?a.jsx(e,{step:t||0}):e,J$={withIcon:!0,allowStepClick:!0,iconPosition:"left"},Z0=ve((e,t)=>{const{classNames:n,className:r,style:i,styles:s,vars:c,step:u,state:f,color:h,icon:m,completedIcon:g,progressIcon:y,label:x,description:S,withIcon:w,iconSize:C,loading:T,allowStepClick:R,allowStepSelect:E,iconPosition:_,orientation:P,mod:O,...k}=ae("StepperStep",J$,e),A=X$(),z=Nn(),U={classNames:n,styles:s},K=f==="stepCompleted"?null:f==="stepProgress"?y:m,W={"data-progress":f==="stepProgress"||void 0,"data-completed":f==="stepCompleted"||void 0};return a.jsxs(An,{...A.getStyles("step",{className:r,style:i,variant:A.orientation,...U}),mod:[{"icon-position":_||A.iconPosition,"allow-click":R},O],ref:t,...W,...k,__vars:{"--step-color":h?Kt(h,z):void 0},tabIndex:R?0:-1,children:[w&&a.jsxs("span",{...A.getStyles("stepWrapper",U),children:[a.jsxs("span",{...A.getStyles("stepIcon",U),...W,children:[a.jsx(uo,{mounted:f==="stepCompleted",transition:"pop",duration:200,children:ee=>a.jsx("span",{...A.getStyles("stepCompletedIcon",{style:ee,...U}),children:T?a.jsx(Pr,{color:"var(--mantine-color-white)",size:"calc(var(--stepper-icon-size) / 2)",...A.getStyles("stepLoader",U)}):lp(g,u)||a.jsx(pf,{size:"60%"})})}),f!=="stepCompleted"?T?a.jsx(Pr,{...A.getStyles("stepLoader",U),size:"calc(var(--stepper-icon-size) / 2)",color:h}):lp(K||m,u):null]}),P==="vertical"&&a.jsx("span",{...A.getStyles("verticalSeparator",U),"data-active":f==="stepCompleted"||void 0})]}),(x||S)&&a.jsxs("span",{...A.getStyles("stepBody",U),"data-orientation":A.orientation,"data-icon-position":_||A.iconPosition,children:[x&&a.jsx("span",{...A.getStyles("stepLabel",U),children:lp(x,u)}),S&&a.jsx("span",{...A.getStyles("stepDescription",U),children:lp(S,u)})]})]})});Z0.classes=J0;Z0.displayName="@mantine/core/StepperStep";const Z$={orientation:"horizontal",iconPosition:"left",allowNextStepsSelect:!0,wrap:!0},e8=(e,{color:t,iconSize:n,size:r,contentPadding:i,radius:s,autoContrast:c})=>({root:{"--stepper-color":t?Kt(t,e):void 0,"--stepper-icon-color":Il(c,e)?Ra({color:t,theme:e,autoContrast:c}):void 0,"--stepper-icon-size":n===void 0?ot(r,"stepper-icon-size"):ce(n),"--stepper-content-padding":Yn(i),"--stepper-radius":s===void 0?void 0:Ht(s),"--stepper-fz":Kn(r),"--stepper-spacing":Yn(r)}}),ou=ve((e,t)=>{const n=ae("Stepper",Z$,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,children:h,onStepClick:m,active:g,icon:y,completedIcon:x,progressIcon:S,color:w,iconSize:C,contentPadding:T,orientation:R,iconPosition:E,size:_,radius:P,allowNextStepsSelect:O,wrap:k,autoContrast:A,attributes:z,...U}=n,K=$e({name:"Stepper",classes:J0,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:z,vars:f,varsResolver:e8}),W=v.Children.toArray(h),ee=W.filter(V=>V.type!==Bp),B=W.find(V=>V.type===Bp),G=ee.reduce((V,X,M)=>{const F=g===M?"stepProgress":g>M?"stepCompleted":"stepInactive",de=typeof m!="function"?!1:typeof X.props.allowStepSelect=="boolean"?X.props.allowStepSelect:F==="stepCompleted"||O;return V.push(v.cloneElement(X,{icon:X.props.icon||y||M+1,key:M,step:M,state:F,onClick:()=>de&&m?.(M),allowStepClick:de,completedIcon:X.props.completedIcon||x,progressIcon:X.props.progressIcon||S,color:X.props.color||w,iconSize:C,iconPosition:X.props.iconPosition||E,orientation:R})),R==="horizontal"&&M!==ee.length-1&&V.push(v.createElement("div",{...K("separator"),"data-active":M<g||void 0,"data-orientation":R,key:`separator-${M}`})),V},[]),L=ee[g]?.props?.children,I=B?.props?.children,$=g>ee.length-1?I:L;return a.jsx(K$,{value:{getStyles:K,orientation:R,iconPosition:E},children:a.jsxs(le,{...K("root"),ref:t,size:_,...U,children:[a.jsx(le,{...K("steps"),mod:{orientation:R,"icon-position":E,wrap:k&&R!=="vertical"},children:G}),$&&a.jsx("div",{...K("content"),children:$})]})})});ou.classes=J0;ou.displayName="@mantine/core/Stepper";ou.Completed=Bp;ou.Step=Z0;var IA={root:"m_5f93f3bb",input:"m_926b4011",track:"m_9307d992",thumb:"m_93039a1d",trackLabel:"m_8277e082"};const zA=v.createContext(null),t8=zA.Provider,n8=()=>v.useContext(zA),eS=ve((e,t)=>{const{value:n,defaultValue:r,onChange:i,size:s,wrapperProps:c,children:u,readOnly:f,disabled:h,...m}=ae("SwitchGroup",null,e),[g,y]=or({value:n,defaultValue:r,finalValue:[],onChange:i}),x=S=>{const w=S.currentTarget.value;!f&&y(g.includes(w)?g.filter(C=>C!==w):[...g,w])};return a.jsx(t8,{value:{value:g,onChange:x,size:s,disabled:h},children:a.jsx(mn.Wrapper,{size:s,ref:t,...c,...m,labelElement:"div",__staticSelector:"SwitchGroup",children:a.jsx(g0,{role:"group",children:u})})})});eS.classes=mn.Wrapper.classes;eS.displayName="@mantine/core/SwitchGroup";const r8={labelPosition:"right",withThumbIndicator:!0},i8=(e,{radius:t,color:n,size:r})=>({root:{"--switch-radius":t===void 0?void 0:Ht(t),"--switch-height":ot(r,"switch-height"),"--switch-width":ot(r,"switch-width"),"--switch-thumb-size":ot(r,"switch-thumb-size"),"--switch-label-font-size":ot(r,"switch-label-font-size"),"--switch-track-label-padding":ot(r,"switch-track-label-padding"),"--switch-color":n?Kt(n,e):void 0}}),bf=ve((e,t)=>{const n=ae("Switch",r8,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,color:h,label:m,offLabel:g,onLabel:y,id:x,size:S,radius:w,wrapperProps:C,thumbIcon:T,checked:R,defaultChecked:E,onChange:_,labelPosition:P,description:O,error:k,disabled:A,variant:z,rootRef:U,mod:K,withThumbIndicator:W,attributes:ee,...B}=n,G=n8(),L=S||G?.size,I=$e({name:"Switch",props:n,classes:IA,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:ee,vars:f,varsResolver:i8}),{styleProps:$,rest:V}=_a(B),X=vr(x),M={checked:G?.value.includes(V.value)??R,onChange:de=>{G?.onChange(de),_?.(de)},disabled:G?.disabled??A},[F,ie]=or({value:M.checked??R,defaultValue:E,finalValue:!1});return a.jsxs(Em,{...I("root"),__staticSelector:"Switch",__stylesApiProps:n,id:X,size:L,labelPosition:P,label:m,description:O,error:k,disabled:M.disabled,bodyElement:"label",labelElement:"span",classNames:r,styles:c,unstyled:u,"data-checked":M.checked,variant:z,ref:U,mod:K,inert:V.inert,...$,...C,children:[a.jsx("input",{...V,...M,checked:F,"data-checked":M.checked,onChange:de=>{M.onChange?.(de),ie(de.currentTarget.checked)},id:X,ref:t,type:"checkbox",role:"switch",inert:V.inert,...I("input")}),a.jsxs(le,{"aria-hidden":"true",component:"span",mod:{error:k,"label-position":P,"without-labels":!y&&!g},...I("track"),children:[a.jsx(le,{component:"span",mod:{"reduce-motion":!0,"with-thumb-indicator":W&&!T},...I("thumb"),children:T}),a.jsx("span",{...I("trackLabel"),children:F?y:g})]})]})});bf.classes={...IA,...zD};bf.displayName="@mantine/core/Switch";bf.Group=eS;const[o8,a8]=Or("Table component was not found in the tree");var Sf={table:"m_b23fa0ef",th:"m_4e7aa4f3",tr:"m_4e7aa4fd",td:"m_4e7aa4ef",tbody:"m_b2404537",thead:"m_b242d975",caption:"m_9e5a3ac7",scrollContainer:"m_a100c15",scrollContainerInner:"m_62259741"};function s8(e,t){if(!t)return;const n={};return t.columnBorder&&e.withColumnBorders&&(n["data-with-column-border"]=!0),t.rowBorder&&e.withRowBorders&&(n["data-with-row-border"]=!0),t.striped&&e.striped&&(n["data-striped"]=e.striped),t.highlightOnHover&&e.highlightOnHover&&(n["data-hover"]=!0),t.captionSide&&e.captionSide&&(n["data-side"]=e.captionSide),t.stickyHeader&&e.stickyHeader&&(n["data-sticky"]=!0),n}function Bl(e,t){const n=`Table${e.charAt(0).toUpperCase()}${e.slice(1)}`,r=ve((i,s)=>{const c=ae(n,{},i),{classNames:u,className:f,style:h,styles:m,...g}=c,y=a8();return a.jsx(le,{component:e,ref:s,...s8(y,t),...y.getStyles(e,{className:f,classNames:u,style:h,styles:m,props:c}),...g})});return r.displayName=`@mantine/core/${n}`,r.classes=Sf,r}const Gx=Bl("th",{columnBorder:!0}),$A=Bl("td",{columnBorder:!0}),Cp=Bl("tr",{rowBorder:!0,striped:!0,highlightOnHover:!0}),UA=Bl("thead",{stickyHeader:!0}),BA=Bl("tbody"),VA=Bl("tfoot"),FA=Bl("caption",{captionSide:!0});function tS({data:e}){return a.jsxs(a.Fragment,{children:[e.caption&&a.jsx(FA,{children:e.caption}),e.head&&a.jsx(UA,{children:a.jsx(Cp,{children:e.head.map((t,n)=>a.jsx(Gx,{children:t},n))})}),e.body&&a.jsx(BA,{children:e.body.map((t,n)=>a.jsx(Cp,{children:t.map((r,i)=>a.jsx($A,{children:r},i))},n))}),e.foot&&a.jsx(VA,{children:a.jsx(Cp,{children:e.foot.map((t,n)=>a.jsx(Gx,{children:t},n))})})]})}tS.displayName="@mantine/core/TableDataRenderer";const l8={type:"scrollarea"},c8=(e,{minWidth:t,maxHeight:n,type:r})=>({scrollContainer:{"--table-min-width":ce(t),"--table-max-height":ce(n),"--table-overflow":r==="native"?"auto":void 0}}),nS=ve((e,t)=>{const n=ae("TableScrollContainer",l8,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,children:h,minWidth:m,maxHeight:g,type:y,scrollAreaProps:x,attributes:S,...w}=n,C=$e({name:"TableScrollContainer",classes:Sf,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:S,vars:f,varsResolver:c8,rootSelector:"scrollContainer"});return a.jsx(le,{component:y==="scrollarea"?ti:"div",...y==="scrollarea"?g?{offsetScrollbars:"xy",...x}:{offsetScrollbars:"x",...x}:{},ref:t,...C("scrollContainer"),...w,children:a.jsx("div",{...C("scrollContainerInner"),children:h})})});nS.classes=Sf;nS.displayName="@mantine/core/TableScrollContainer";const u8={withRowBorders:!0,verticalSpacing:7},d8=(e,{layout:t,captionSide:n,horizontalSpacing:r,verticalSpacing:i,borderColor:s,stripedColor:c,highlightOnHoverColor:u,striped:f,highlightOnHover:h,stickyHeaderOffset:m,stickyHeader:g})=>({table:{"--table-layout":t,"--table-caption-side":n,"--table-horizontal-spacing":Yn(r),"--table-vertical-spacing":Yn(i),"--table-border-color":s?Kt(s,e):void 0,"--table-striped-color":f&&c?Kt(c,e):void 0,"--table-highlight-on-hover-color":h&&u?Kt(u,e):void 0,"--table-sticky-header-offset":g?ce(m):void 0}}),Z=ve((e,t)=>{const n=ae("Table",u8,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,horizontalSpacing:h,verticalSpacing:m,captionSide:g,stripedColor:y,highlightOnHoverColor:x,striped:S,highlightOnHover:w,withColumnBorders:C,withRowBorders:T,withTableBorder:R,borderColor:E,layout:_,variant:P,data:O,children:k,stickyHeader:A,stickyHeaderOffset:z,mod:U,tabularNums:K,attributes:W,...ee}=n,B=$e({name:"Table",props:n,className:i,style:s,classes:Sf,classNames:r,styles:c,unstyled:u,attributes:W,rootSelector:"table",vars:f,varsResolver:d8});return a.jsx(o8,{value:{getStyles:B,stickyHeader:A,striped:S===!0?"odd":S||void 0,highlightOnHover:w,withColumnBorders:C,withRowBorders:T,captionSide:g||"bottom"},children:a.jsx(le,{component:"table",variant:P,ref:t,mod:[{"data-with-table-border":R,"data-tabular-nums":K},U],...B("table"),...ee,children:k||!!O&&a.jsx(tS,{data:O})})})});Z.classes=Sf;Z.displayName="@mantine/core/Table";Z.Td=$A;Z.Th=Gx;Z.Tr=Cp;Z.Thead=UA;Z.Tbody=BA;Z.Tfoot=VA;Z.Caption=FA;Z.ScrollContainer=nS;Z.DataRenderer=tS;const[f8,rS]=Or("Tabs component was not found in the tree");var jf={root:"m_89d60db1","list--default":"m_576c9d4",list:"m_89d33d6d",tab:"m_4ec4dce6",panel:"m_b0c91715",tabSection:"m_fc420b1f",tabLabel:"m_42bbd1ae","tab--default":"m_539e827b","list--outline":"m_6772fbd5","tab--outline":"m_b59ab47c","tab--pills":"m_c3381914"};const iS=ve((e,t)=>{const n=ae("TabsList",null,e),{children:r,className:i,grow:s,justify:c,classNames:u,styles:f,style:h,mod:m,...g}=n,y=rS();return a.jsx(le,{...g,...y.getStyles("list",{className:i,style:h,classNames:u,styles:f,props:n,variant:y.variant}),ref:t,role:"tablist",variant:y.variant,mod:[{grow:s,orientation:y.orientation,placement:y.orientation==="vertical"&&y.placement,inverted:y.inverted},m],"aria-orientation":y.orientation,__vars:{"--tabs-justify":c},children:r})});iS.classes=jf;iS.displayName="@mantine/core/TabsList";const oS=ve((e,t)=>{const n=ae("TabsPanel",null,e),{children:r,className:i,value:s,classNames:c,styles:u,style:f,mod:h,keepMounted:m,...g}=n,y=rS(),x=y.value===s,S=y.keepMounted||m||x?r:null;return a.jsx(le,{...y.getStyles("panel",{className:i,classNames:c,styles:u,style:[f,x?void 0:{display:"none"}],props:n}),ref:t,mod:[{orientation:y.orientation},h],role:"tabpanel",id:y.getPanelId(s),"aria-labelledby":y.getTabId(s),...g,children:S})});oS.classes=jf;oS.displayName="@mantine/core/TabsPanel";const aS=ve((e,t)=>{const n=ae("TabsTab",null,e),{className:r,children:i,rightSection:s,leftSection:c,value:u,onClick:f,onKeyDown:h,disabled:m,color:g,style:y,classNames:x,styles:S,vars:w,mod:C,tabIndex:T,...R}=n,E=Nn(),{dir:_}=Rs(),P=rS(),O=u===P.value,k=z=>{P.onChange(P.allowTabDeactivation&&u===P.value?null:u),f?.(z)},A={classNames:x,styles:S,props:n};return a.jsxs(An,{...P.getStyles("tab",{className:r,style:y,variant:P.variant,...A}),disabled:m,unstyled:P.unstyled,variant:P.variant,mod:[{active:O,disabled:m,orientation:P.orientation,inverted:P.inverted,placement:P.orientation==="vertical"&&P.placement},C],ref:t,role:"tab",id:P.getTabId(u),"aria-selected":O,tabIndex:T!==void 0?T:O||P.value===null?0:-1,"aria-controls":P.getPanelId(u),onClick:k,__vars:{"--tabs-color":g?Kt(g,E):void 0},onKeyDown:Eb({siblingSelector:'[role="tab"]',parentSelector:'[role="tablist"]',activateOnFocus:P.activateTabWithKeyboard,loop:P.loop,orientation:P.orientation||"horizontal",dir:_,onKeyDown:h}),...R,children:[c&&a.jsx("span",{...P.getStyles("tabSection",A),"data-position":"left",children:c}),i&&a.jsx("span",{...P.getStyles("tabLabel",A),children:i}),s&&a.jsx("span",{...P.getStyles("tabSection",A),"data-position":"right",children:s})]})});aS.classes=jf;aS.displayName="@mantine/core/TabsTab";const ET="Tabs.Tab or Tabs.Panel component was rendered with invalid value or without value",h8={keepMounted:!0,orientation:"horizontal",loop:!0,activateTabWithKeyboard:!0,variant:"default",placement:"left"},p8=(e,{radius:t,color:n,autoContrast:r})=>({root:{"--tabs-radius":Ht(t),"--tabs-color":Kt(n,e),"--tabs-text-color":Il(r,e)?Ra({color:n,theme:e,autoContrast:r}):void 0}}),bn=ve((e,t)=>{const n=ae("Tabs",h8,e),{defaultValue:r,value:i,onChange:s,orientation:c,children:u,loop:f,id:h,activateTabWithKeyboard:m,allowTabDeactivation:g,variant:y,color:x,radius:S,inverted:w,placement:C,keepMounted:T,classNames:R,styles:E,unstyled:_,className:P,style:O,vars:k,autoContrast:A,mod:z,attributes:U,...K}=n,W=vr(h),[ee,B]=or({value:i,defaultValue:r,finalValue:null,onChange:s}),G=$e({name:"Tabs",props:n,classes:jf,className:P,style:O,classNames:R,styles:E,unstyled:_,attributes:U,vars:k,varsResolver:p8});return a.jsx(f8,{value:{placement:C,value:ee,orientation:c,id:W,loop:f,activateTabWithKeyboard:m,getTabId:vE(`${W}-tab`,ET),getPanelId:vE(`${W}-panel`,ET),onChange:B,allowTabDeactivation:g,variant:y,color:x,radius:S,inverted:w,keepMounted:T,unstyled:_,getStyles:G},children:a.jsx(le,{ref:t,id:W,variant:y,mod:[{orientation:c,inverted:c==="horizontal"&&w,placement:c==="vertical"&&C},z],...G("root"),...K,children:u})})});bn.classes=jf;bn.displayName="@mantine/core/Tabs";bn.Tab=aS;bn.Panel=oS;bn.List=iS;const Fe=ve((e,t)=>{const n=ae("TextInput",null,e);return a.jsx(Vr,{component:"input",ref:t,...n,__staticSelector:"TextInput"})});Fe.classes=Vr.classes;Fe.displayName="@mantine/core/TextInput";var HA={root:"m_7341320d"};const m8=(e,{size:t,radius:n,variant:r,gradient:i,color:s,autoContrast:c})=>{const u=e.variantColorResolver({color:s||e.primaryColor,theme:e,gradient:i,variant:r||"filled",autoContrast:c});return{root:{"--ti-size":ot(t,"ti-size"),"--ti-radius":n===void 0?void 0:Ht(n),"--ti-bg":s||r?u.background:void 0,"--ti-color":s||r?u.color:void 0,"--ti-bd":s||r?u.border:void 0}}},sS=ve((e,t)=>{const n=ae("ThemeIcon",null,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,autoContrast:h,attributes:m,...g}=n,y=$e({name:"ThemeIcon",classes:HA,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:m,vars:f,varsResolver:m8});return a.jsx(le,{ref:t,...y("root"),...g})});sS.classes=HA;sS.displayName="@mantine/core/ThemeIcon";const g8=["h1","h2","h3","h4","h5","h6"],v8=["xs","sm","md","lg","xl"];function y8(e,t){const n=t!==void 0?t:`h${e}`;return g8.includes(n)?{fontSize:`var(--mantine-${n}-font-size)`,fontWeight:`var(--mantine-${n}-font-weight)`,lineHeight:`var(--mantine-${n}-line-height)`}:v8.includes(n)?{fontSize:`var(--mantine-font-size-${n})`,fontWeight:`var(--mantine-h${e}-font-weight)`,lineHeight:`var(--mantine-h${e}-line-height)`}:{fontSize:ce(n),fontWeight:`var(--mantine-h${e}-font-weight)`,lineHeight:`var(--mantine-h${e}-line-height)`}}var qA={root:"m_8a5d1357"};const x8={order:1},b8=(e,{order:t,size:n,lineClamp:r,textWrap:i})=>{const s=y8(t||1,n);return{root:{"--title-fw":s.fontWeight,"--title-lh":s.lineHeight,"--title-fz":s.fontSize,"--title-line-clamp":typeof r=="number"?r.toString():void 0,"--title-text-wrap":i}}},ze=ve((e,t)=>{const n=ae("Title",x8,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,order:f,vars:h,size:m,variant:g,lineClamp:y,textWrap:x,mod:S,attributes:w,...C}=n,T=$e({name:"Title",props:n,classes:qA,className:i,style:s,classNames:r,styles:c,unstyled:u,attributes:w,vars:h,varsResolver:b8});return[1,2,3,4,5,6].includes(f)?a.jsx(le,{...T("root"),component:`h${f}`,variant:g,ref:t,mod:[{order:f,"data-line-clamp":typeof y=="number"},S],size:m,...C}):null});ze.classes=qA;ze.displayName="@mantine/core/Title";function GA(e){let t=e,n=!1;const r=new Set;return{getState(){return t},updateState(i){t=typeof i=="function"?i(t):i},setState(i){this.updateState(i),r.forEach(s=>s(t))},initialize(i){n||(t=i,n=!0)},subscribe(i){return r.add(i),()=>r.delete(i)}}}function WA(e){return v.useSyncExternalStore(e.subscribe,()=>e.getState(),()=>e.getState())}function S8(e,t,n){const r=[],i=[],s={};for(const c of e){const u=c.position||t;s[u]=s[u]||0,s[u]+=1,s[u]<=n?i.push(c):r.push(c)}return{notifications:i,queue:r}}const j8=()=>GA({notifications:[],queue:[],defaultPosition:"bottom-right",limit:5}),Vl=j8(),w8=(e=Vl)=>WA(e);function bu(e,t){const n=e.getState(),r=t([...n.notifications,...n.queue]),i=S8(r,n.defaultPosition,n.limit);e.setState({notifications:i.notifications,queue:i.queue,limit:n.limit,defaultPosition:n.defaultPosition})}function Ae(e,t=Vl){const n=e.id||Op();return bu(t,r=>e.id&&r.some(i=>i.id===e.id)?r:[...r,{...e,id:n}]),n}function QA(e,t=Vl){return bu(t,n=>n.filter(r=>r.id===e?(r.onClose?.(r),!1):!0)),e}function hl(e,t=Vl){return bu(t,n=>n.map(r=>r.id===e.id?{...r,...e}:r)),e.id}function C8(e=Vl){bu(e,()=>[])}function E8(e=Vl){bu(e,t=>t.slice(0,e.getState().limit))}const Li={show:Ae,hide:QA,update:hl,clean:C8,cleanQueue:E8,updateState:bu};function Wx(e,t){return Wx=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},Wx(e,t)}function YA(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,Wx(e,t)}var Jy={exports:{}},Zy,TT;function T8(){if(TT)return Zy;TT=1;var e="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";return Zy=e,Zy}var ex,RT;function R8(){if(RT)return ex;RT=1;var e=T8();function t(){}function n(){}return n.resetWarningCache=t,ex=function(){function r(c,u,f,h,m,g){if(g!==e){var y=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw y.name="Invariant Violation",y}}r.isRequired=r;function i(){return r}var s={array:r,bigint:r,bool:r,func:r,number:r,object:r,string:r,symbol:r,any:r,arrayOf:i,element:r,elementType:r,instanceOf:i,node:r,objectOf:i,oneOf:i,oneOfType:i,shape:i,exact:i,checkPropTypes:n,resetWarningCache:t};return s.PropTypes=s,s},ex}var _T;function _8(){return _T||(_T=1,Jy.exports=R8()()),Jy.exports}var D8=_8();const un=sm(D8),DT={disabled:!1},Vp=Ln.createContext(null);var A8=function(t){return t.scrollTop},Td="unmounted",al="exited",sl="entering",Hc="entered",Qx="exiting",ka=(function(e){YA(t,e);function t(r,i){var s;s=e.call(this,r,i)||this;var c=i,u=c&&!c.isMounting?r.enter:r.appear,f;return s.appearStatus=null,r.in?u?(f=al,s.appearStatus=sl):f=Hc:r.unmountOnExit||r.mountOnEnter?f=Td:f=al,s.state={status:f},s.nextCallback=null,s}t.getDerivedStateFromProps=function(i,s){var c=i.in;return c&&s.status===Td?{status:al}:null};var n=t.prototype;return n.componentDidMount=function(){this.updateStatus(!0,this.appearStatus)},n.componentDidUpdate=function(i){var s=null;if(i!==this.props){var c=this.state.status;this.props.in?c!==sl&&c!==Hc&&(s=sl):(c===sl||c===Hc)&&(s=Qx)}this.updateStatus(!1,s)},n.componentWillUnmount=function(){this.cancelNextCallback()},n.getTimeouts=function(){var i=this.props.timeout,s,c,u;return s=c=u=i,i!=null&&typeof i!="number"&&(s=i.exit,c=i.enter,u=i.appear!==void 0?i.appear:c),{exit:s,enter:c,appear:u}},n.updateStatus=function(i,s){if(i===void 0&&(i=!1),s!==null)if(this.cancelNextCallback(),s===sl){if(this.props.unmountOnExit||this.props.mountOnEnter){var c=this.props.nodeRef?this.props.nodeRef.current:Ed.findDOMNode(this);c&&A8(c)}this.performEnter(i)}else this.performExit();else this.props.unmountOnExit&&this.state.status===al&&this.setState({status:Td})},n.performEnter=function(i){var s=this,c=this.props.enter,u=this.context?this.context.isMounting:i,f=this.props.nodeRef?[u]:[Ed.findDOMNode(this),u],h=f[0],m=f[1],g=this.getTimeouts(),y=u?g.appear:g.enter;if(!i&&!c||DT.disabled){this.safeSetState({status:Hc},function(){s.props.onEntered(h)});return}this.props.onEnter(h,m),this.safeSetState({status:sl},function(){s.props.onEntering(h,m),s.onTransitionEnd(y,function(){s.safeSetState({status:Hc},function(){s.props.onEntered(h,m)})})})},n.performExit=function(){var i=this,s=this.props.exit,c=this.getTimeouts(),u=this.props.nodeRef?void 0:Ed.findDOMNode(this);if(!s||DT.disabled){this.safeSetState({status:al},function(){i.props.onExited(u)});return}this.props.onExit(u),this.safeSetState({status:Qx},function(){i.props.onExiting(u),i.onTransitionEnd(c.exit,function(){i.safeSetState({status:al},function(){i.props.onExited(u)})})})},n.cancelNextCallback=function(){this.nextCallback!==null&&(this.nextCallback.cancel(),this.nextCallback=null)},n.safeSetState=function(i,s){s=this.setNextCallback(s),this.setState(i,s)},n.setNextCallback=function(i){var s=this,c=!0;return this.nextCallback=function(u){c&&(c=!1,s.nextCallback=null,i(u))},this.nextCallback.cancel=function(){c=!1},this.nextCallback},n.onTransitionEnd=function(i,s){this.setNextCallback(s);var c=this.props.nodeRef?this.props.nodeRef.current:Ed.findDOMNode(this),u=i==null&&!this.props.addEndListener;if(!c||u){setTimeout(this.nextCallback,0);return}if(this.props.addEndListener){var f=this.props.nodeRef?[this.nextCallback]:[c,this.nextCallback],h=f[0],m=f[1];this.props.addEndListener(h,m)}i!=null&&setTimeout(this.nextCallback,i)},n.render=function(){var i=this.state.status;if(i===Td)return null;var s=this.props,c=s.children;s.in,s.mountOnEnter,s.unmountOnExit,s.appear,s.enter,s.exit,s.timeout,s.addEndListener,s.onEnter,s.onEntering,s.onEntered,s.onExit,s.onExiting,s.onExited,s.nodeRef;var u=A0(s,["children","in","mountOnEnter","unmountOnExit","appear","enter","exit","timeout","addEndListener","onEnter","onEntering","onEntered","onExit","onExiting","onExited","nodeRef"]);return Ln.createElement(Vp.Provider,{value:null},typeof c=="function"?c(i,u):Ln.cloneElement(Ln.Children.only(c),u))},t})(Ln.Component);ka.contextType=Vp;ka.propTypes={};function Lc(){}ka.defaultProps={in:!1,mountOnEnter:!1,unmountOnExit:!1,appear:!1,enter:!0,exit:!0,onEnter:Lc,onEntering:Lc,onEntered:Lc,onExit:Lc,onExiting:Lc,onExited:Lc};ka.UNMOUNTED=Td;ka.EXITED=al;ka.ENTERING=sl;ka.ENTERED=Hc;ka.EXITING=Qx;function k8(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function lS(e,t){var n=function(s){return t&&v.isValidElement(s)?t(s):s},r=Object.create(null);return e&&v.Children.map(e,function(i){return i}).forEach(function(i){r[i.key]=n(i)}),r}function P8(e,t){e=e||{},t=t||{};function n(m){return m in t?t[m]:e[m]}var r=Object.create(null),i=[];for(var s in e)s in t?i.length&&(r[s]=i,i=[]):i.push(s);var c,u={};for(var f in t){if(r[f])for(c=0;c<r[f].length;c++){var h=r[f][c];u[r[f][c]]=n(h)}u[f]=n(f)}for(c=0;c<i.length;c++)u[i[c]]=n(i[c]);return u}function pl(e,t,n){return n[t]!=null?n[t]:e.props[t]}function N8(e,t){return lS(e.children,function(n){return v.cloneElement(n,{onExited:t.bind(null,n),in:!0,appear:pl(n,"appear",e),enter:pl(n,"enter",e),exit:pl(n,"exit",e)})})}function O8(e,t,n){var r=lS(e.children),i=P8(t,r);return Object.keys(i).forEach(function(s){var c=i[s];if(v.isValidElement(c)){var u=s in t,f=s in r,h=t[s],m=v.isValidElement(h)&&!h.props.in;f&&(!u||m)?i[s]=v.cloneElement(c,{onExited:n.bind(null,c),in:!0,exit:pl(c,"exit",e),enter:pl(c,"enter",e)}):!f&&u&&!m?i[s]=v.cloneElement(c,{in:!1}):f&&u&&v.isValidElement(h)&&(i[s]=v.cloneElement(c,{onExited:n.bind(null,c),in:h.props.in,exit:pl(c,"exit",e),enter:pl(c,"enter",e)}))}}),i}var M8=Object.values||function(e){return Object.keys(e).map(function(t){return e[t]})},L8={component:"div",childFactory:function(t){return t}},ds=(function(e){YA(t,e);function t(r,i){var s;s=e.call(this,r,i)||this;var c=s.handleExited.bind(k8(s));return s.state={contextValue:{isMounting:!0},handleExited:c,firstRender:!0},s}var n=t.prototype;return n.componentDidMount=function(){this.mounted=!0,this.setState({contextValue:{isMounting:!1}})},n.componentWillUnmount=function(){this.mounted=!1},t.getDerivedStateFromProps=function(i,s){var c=s.children,u=s.handleExited,f=s.firstRender;return{children:f?N8(i,u):O8(i,c,u),firstRender:!1}},n.handleExited=function(i,s){var c=lS(this.props.children);i.key in c||(i.props.onExited&&i.props.onExited(s),this.mounted&&this.setState(function(u){var f=Up({},u.children);return delete f[i.key],{children:f}}))},n.render=function(){var i=this.props,s=i.component,c=i.childFactory,u=A0(i,["component","childFactory"]),f=this.state.contextValue,h=M8(this.state.children).map(c);return delete u.appear,delete u.enter,delete u.exit,s===null?Ln.createElement(Vp.Provider,{value:f},h):Ln.createElement(Vp.Provider,{value:f},Ln.createElement(s,u,h))},t})(Ln.Component);ds.propTypes={};ds.defaultProps=L8;const KA=["bottom-center","bottom-left","bottom-right","top-center","top-left","top-right"];function I8(e,t){return e.reduce((n,r)=>(n[r.position||t].push(r),n),KA.reduce((n,r)=>(n[r]=[],n),{}))}const AT={left:"translateX(-100%)",right:"translateX(100%)","top-center":"translateY(-100%)","bottom-center":"translateY(100%)"},z8={left:"translateX(0)",right:"translateX(0)","top-center":"translateY(0)","bottom-center":"translateY(0)"};function $8({state:e,maxHeight:t,position:n,transitionDuration:r}){const[i,s]=n.split("-"),c=s==="center"?`${i}-center`:s,u={opacity:0,maxHeight:t,transform:AT[c],transitionDuration:`${r}ms, ${r}ms, ${r}ms`,transitionTimingFunction:"cubic-bezier(.51,.3,0,1.21), cubic-bezier(.51,.3,0,1.21), linear",transitionProperty:"opacity, transform, max-height"},f={opacity:1,transform:z8[c]},h={opacity:0,maxHeight:0,transform:AT[c]};return{...u,...{entering:f,entered:f,exiting:h,exited:h}[e]}}function U8(e,t){return typeof t=="number"?t:t===!1||e===!1?!1:e}const XA=v.forwardRef(({data:e,onHide:t,autoClose:n,...r},i)=>{const{autoClose:s,message:c,...u}=e,f=U8(n,e.autoClose),h=v.useRef(-1),m=()=>window.clearTimeout(h.current),g=()=>{t(e.id),m()},y=()=>{typeof f=="number"&&(h.current=window.setTimeout(g,f))};return v.useEffect(()=>{e.onOpen?.(e)},[]),v.useEffect(()=>(y(),m),[f]),a.jsx(H0,{...r,...u,onClose:g,ref:i,onMouseEnter:m,onMouseLeave:y,children:c})});XA.displayName="@mantine/notifications/NotificationContainer";var JA={root:"m_b37d9ac7",notification:"m_5ed0edd0"};const B8=ka,V8={position:"bottom-right",autoClose:4e3,transitionDuration:250,containerWidth:440,notificationMaxHeight:200,limit:5,zIndex:Br("overlay"),store:Vl,withinPortal:!0},F8=(e,{zIndex:t,containerWidth:n})=>({root:{"--notifications-z-index":t?.toString(),"--notifications-container-width":ce(n)}}),Pa=ve((e,t)=>{const n=ae("Notifications",V8,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,position:h,autoClose:m,transitionDuration:g,containerWidth:y,notificationMaxHeight:x,limit:S,zIndex:w,store:C,portalProps:T,withinPortal:R,...E}=n,_=Nn(),P=w8(C),O=OM(),k=_b(),A=v.useRef({}),z=v.useRef(0),K=(_.respectReducedMotion?k:!1)?1:g,W=$e({name:"Notifications",classes:JA,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:F8});v.useEffect(()=>{C?.updateState(G=>({...G,limit:S||5,defaultPosition:h}))},[S,h]),jl(()=>{P.notifications.length>z.current&&setTimeout(()=>O(),0),z.current=P.notifications.length},[P.notifications]);const ee=I8(P.notifications,h),B=KA.reduce((G,L)=>(G[L]=ee[L].map(({style:I,...$})=>a.jsx(B8,{timeout:K,onEnter:()=>A.current[$.id].offsetHeight,nodeRef:{current:A.current[$.id]},children:V=>a.jsx(XA,{ref:X=>{X&&(A.current[$.id]=X)},data:$,onHide:X=>QA(X,C),autoClose:m,...W("notification",{style:{...$8({state:V,position:L,transitionDuration:K,maxHeight:x}),...I}})})},$.id)),G),{});return a.jsxs(ja,{withinPortal:R,...T,children:[a.jsx(le,{...W("root"),"data-position":"top-center",ref:t,...E,children:a.jsx(ds,{children:B["top-center"]})}),a.jsx(le,{...W("root"),"data-position":"top-left",...E,children:a.jsx(ds,{children:B["top-left"]})}),a.jsx(le,{...W("root",{className:Sl.classNames.fullWidth}),"data-position":"top-right",...E,children:a.jsx(ds,{children:B["top-right"]})}),a.jsx(le,{...W("root",{className:Sl.classNames.fullWidth}),"data-position":"bottom-right",...E,children:a.jsx(ds,{children:B["bottom-right"]})}),a.jsx(le,{...W("root"),"data-position":"bottom-left",...E,children:a.jsx(ds,{children:B["bottom-left"]})}),a.jsx(le,{...W("root"),"data-position":"bottom-center",...E,children:a.jsx(ds,{children:B["bottom-center"]})})]})});Pa.classes=JA;Pa.displayName="@mantine/notifications/Notifications";Pa.show=Li.show;Pa.hide=Li.hide;Pa.update=Li.update;Pa.clean=Li.clean;Pa.cleanQueue=Li.cleanQueue;Pa.updateState=Li.updateState;class cS{max;cache;constructor(t=10){this.max=t,this.cache=new Map}clear(){this.cache.clear()}get(t){const n=this.cache.get(t);return n&&(this.cache.delete(t),this.cache.set(t,n)),n}set(t,n){this.cache.has(t)?this.cache.delete(t):this.cache.size>=this.max&&this.cache.delete(this.first()),this.cache.set(t,n)}delete(t){this.cache.delete(t)}keys(){return this.cache.keys()}first(){return this.cache.keys().next().value}}class H8{operator;child;constructor(t,n){this.operator=t,this.child=n}toString(){return`${this.operator}(${this.child.toString()})`}}class wf{operator;left;right;constructor(t,n,r){this.operator=t,this.left=n,this.right=r}toString(){return`(${this.left.toString()} ${this.operator} ${this.right.toString()})`}}class q8{prefixParselets={};infixParselets={};registerInfix(t,n){return this.infixParselets[t]=n,this}registerPrefix(t,n){return this.prefixParselets[t]=n,this}prefix(t,n,r){return this.registerPrefix(t,{parse(i,s){const c=i.consumeAndParse(n);return r(s,c)}})}infixLeft(t,n,r){return this.registerInfix(t,{parse(i,s,c){const u=i.consumeAndParse(n);return r(s,c,u)},precedence:n})}construct(t){return new G8(t,this.prefixParselets,this.infixParselets)}}class G8{tokens;prefixParselets;infixParselets;constructor(t,n,r){this.tokens=t,this.prefixParselets=n,this.infixParselets=r}hasMore(){return this.tokens.length>0}match(t){return this.peek()?.id!==t?!1:(this.consume(),!0)}consumeAndParse(t=1/0){const n=this.consume(),r=this.prefixParselets[n.id];if(!r)throw new Error(`Parse error at "${n.value}" (line ${n.line}, column ${n.column}). No matching prefix parselet.`);let i=r.parse(this,n);for(;t>this.getPrecedence();){const s=this.consume();i=this.getInfixParselet(s).parse(this,i,s)}return i}getPrecedence(){const t=this.peek();if(!t)return 1/0;const n=this.getInfixParselet(t);return n?n.precedence:1/0}consume(t,n){if(!this.tokens.length)throw new Error("Cant consume unknown more tokens.");if(t&&this.peek()?.id!==t){const r=this.peek();throw new Error(`Expected ${t} but got "${r.id}" (${r.value}) at line ${r.line} column ${r.column}.`)}if(n&&this.peek()?.value!==n){const r=this.peek();throw new Error(`Expected "${n}" but got "${r.value}" at line ${r.line} column ${r.column}.`)}return this.tokens.shift()}peek(){return this.tokens.length>0?this.tokens[0]:void 0}removeComments(){this.tokens=this.tokens.filter(t=>t.id!=="Comment")}getInfixParselet(t){return this.infixParselets[t.id==="Symbol"?t.value:t.id]}}const Gi="http://hl7.org",ZA="ok",W8="created",Q8="gone",Y8="not-modified",K8="not-found",X8="unauthorized",J8="forbidden",Z8="accepted",eU={resourceType:"OperationOutcome",id:ZA,issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},tU={resourceType:"OperationOutcome",id:K8,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},Fd={resourceType:"OperationOutcome",id:X8,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},nU={...Fd,issue:[...Fd.issue,{severity:"error",code:"expired",details:{text:"Token expired"}}]},kT={...Fd,issue:[...Fd.issue,{severity:"error",code:"invalid",details:{text:"Token not issued for this audience"}}]},Cf={resourceType:"OperationOutcome",id:J8,issue:[{severity:"error",code:"forbidden",details:{text:"Forbidden"}}]};function Oo(e,t){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"invalid",details:{text:e},...t?{expression:[t]}:void 0}]}}function Sn(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"structure",details:{text:e}}]}}function rU(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"exception",details:{text:"Internal server error"},diagnostics:e.toString()}]}}function iU(e){return!e||typeof e!="object"?!1:e instanceof Error||typeof DOMException<"u"&&e instanceof DOMException?!0:Object.prototype.toString.call(e)==="[object Error]"}function Ef(e){return typeof e=="object"&&e!==null&&e.resourceType==="OperationOutcome"}function ek(e){return e.id===ZA||e.id===W8||e.id===Y8||e.id===Z8}function oU(e){return e.id===Q8}class ut extends Error{outcome;constructor(t,n){super(tk(t),n),this.name="OperationOutcomeError",this.outcome=t}}function rn(e){return e instanceof ut?e.outcome:Ef(e)?e:Oo(We(e))}function We(e){return e?typeof e=="string"?e:iU(e)?e.message:Ef(e)?tk(e):typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:JSON.stringify(e):"Unknown error"}function tk(e){const t=e.issue?.map(nk)??[];return t.length>0?t.join("; "):"Unknown error"}function nk(e){let t;return e.details?.text?e.diagnostics?t=`${e.details.text} (${e.diagnostics})`:t=e.details.text:e.diagnostics?t=e.diagnostics:t="Unknown error",e.expression?.length&&(t+=` (${e.expression.join(", ")})`),t}function aU(e,t){const n=t.max&&t.max===Number.MAX_SAFE_INTEGER?Number.POSITIVE_INFINITY:t.max;return{path:e,description:"",type:t.type??[],min:t.min??0,max:n??1,isArray:!!n&&n>1,constraints:[]}}function sU(e){const t=Object.create(null);for(const[n,r]of Object.entries(e))t[n]={name:n,type:n,path:n,elements:Object.fromEntries(Object.entries(r.elements).map(([i,s])=>[i,aU(i,s)])),constraints:[],innerTypes:[]};return t}const lU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]}}},cU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]}}},uU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"code"}]},text:{type:[{code:"string"}]},line:{max:9007199254740991,type:[{code:"string"}]},city:{type:[{code:"string"}]},district:{type:[{code:"string"}]},state:{type:[{code:"string"}]},postalCode:{type:[{code:"string"}]},country:{type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},dU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},fU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},"author[x]":{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Organization"]},{code:"string"}]},time:{type:[{code:"dateTime"}]},text:{min:1,type:[{code:"markdown"}]}}},hU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},contentType:{type:[{code:"code"}]},language:{type:[{code:"code"}]},data:{type:[{code:"base64Binary"}]},url:{type:[{code:"url"}]},size:{type:[{code:"unsignedInt"}]},hash:{type:[{code:"base64Binary"}]},title:{type:[{code:"string"}]},creation:{type:[{code:"dateTime"}]}}},pU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},coding:{max:9007199254740991,type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},mU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},system:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},code:{type:[{code:"code"}]},display:{type:[{code:"string"}]},userSelected:{type:[{code:"boolean"}]}}},gU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:9007199254740991,type:[{code:"ContactPoint"}]}}},vU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},system:{type:[{code:"code"}]},value:{type:[{code:"string"}]},use:{type:[{code:"code"}]},rank:{type:[{code:"positiveInt"}]},period:{type:[{code:"Period"}]}}},yU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{min:1,type:[{code:"string"}]},contact:{max:9007199254740991,type:[{code:"ContactDetail"}]}}},xU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},bU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},"subject[x]":{type:[{code:"CodeableConcept"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Group"]}]},mustSupport:{max:9007199254740991,type:[{code:"string"}]},codeFilter:{max:9007199254740991,type:[{code:"DataRequirementCodeFilter"}]},dateFilter:{max:9007199254740991,type:[{code:"DataRequirementDateFilter"}]},limit:{type:[{code:"positiveInt"}]},sort:{max:9007199254740991,type:[{code:"DataRequirementSort"}]}}},SU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]},code:{max:9007199254740991,type:[{code:"Coding"}]}}},jU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},"value[x]":{type:[{code:"dateTime"},{code:"Period"},{code:"Duration"}]}}},wU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},CU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},EU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},sequence:{type:[{code:"integer"}]},text:{type:[{code:"string"}]},additionalInstruction:{max:9007199254740991,type:[{code:"CodeableConcept"}]},patientInstruction:{type:[{code:"string"}]},timing:{type:[{code:"Timing"}]},"asNeeded[x]":{type:[{code:"boolean"},{code:"CodeableConcept"}]},site:{type:[{code:"CodeableConcept"}]},route:{type:[{code:"CodeableConcept"}]},method:{type:[{code:"CodeableConcept"}]},doseAndRate:{max:9007199254740991,type:[{code:"DosageDoseAndRate"}]},maxDosePerPeriod:{type:[{code:"Ratio"}]},maxDosePerAdministration:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},maxDosePerLifetime:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},TU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{type:[{code:"CodeableConcept"}]},"dose[x]":{type:[{code:"Range"},{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},"rate[x]":{type:[{code:"Ratio"},{code:"Range"},{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},RU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},_U={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},representation:{max:9007199254740991,type:[{code:"code"}]},sliceName:{type:[{code:"string"}]},sliceIsConstraining:{type:[{code:"boolean"}]},label:{type:[{code:"string"}]},code:{max:9007199254740991,type:[{code:"Coding"}]},slicing:{type:[{code:"ElementDefinitionSlicing"}]},short:{type:[{code:"string"}]},definition:{type:[{code:"markdown"}]},comment:{type:[{code:"markdown"}]},requirements:{type:[{code:"markdown"}]},alias:{max:9007199254740991,type:[{code:"string"}]},min:{type:[{code:"unsignedInt"}]},max:{type:[{code:"string"}]},base:{type:[{code:"ElementDefinitionBase"}]},contentReference:{type:[{code:"uri"}]},type:{max:9007199254740991,type:[{code:"ElementDefinitionType"}]},"defaultValue[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},meaningWhenMissing:{type:[{code:"markdown"}]},orderMeaning:{type:[{code:"string"}]},"fixed[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},"pattern[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},example:{max:9007199254740991,type:[{code:"ElementDefinitionExample"}]},"minValue[x]":{type:[{code:"date"},{code:"dateTime"},{code:"instant"},{code:"time"},{code:"decimal"},{code:"integer"},{code:"positiveInt"},{code:"unsignedInt"},{code:"Quantity"}]},"maxValue[x]":{type:[{code:"date"},{code:"dateTime"},{code:"instant"},{code:"time"},{code:"decimal"},{code:"integer"},{code:"positiveInt"},{code:"unsignedInt"},{code:"Quantity"}]},maxLength:{type:[{code:"integer"}]},condition:{max:9007199254740991,type:[{code:"id"}]},constraint:{max:9007199254740991,type:[{code:"ElementDefinitionConstraint"}]},mustSupport:{type:[{code:"boolean"}]},isModifier:{type:[{code:"boolean"}]},isModifierReason:{type:[{code:"string"}]},isSummary:{type:[{code:"boolean"}]},binding:{type:[{code:"ElementDefinitionBinding"}]},mapping:{max:9007199254740991,type:[{code:"ElementDefinitionMapping"}]}}},DU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},AU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},discriminator:{max:9007199254740991,type:[{code:"ElementDefinitionSlicingDiscriminator"}]},description:{type:[{code:"string"}]},ordered:{type:[{code:"boolean"}]},rules:{min:1,type:[{code:"code"}]}}},kU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},min:{min:1,type:[{code:"unsignedInt"}]},max:{min:1,type:[{code:"string"}]}}},PU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},code:{min:1,type:[{code:"uri"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},targetProfile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},aggregation:{max:9007199254740991,type:[{code:"code"}]},versioning:{type:[{code:"code"}]}}},NU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},label:{min:1,type:[{code:"string"}]},"value[x]":{min:1,type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]}}},OU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},key:{min:1,type:[{code:"id"}]},requirements:{type:[{code:"string"}]},severity:{min:1,type:[{code:"code"}]},human:{min:1,type:[{code:"string"}]},expression:{type:[{code:"string"}]},xpath:{type:[{code:"string"}]},source:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]}}},MU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},strength:{min:1,type:[{code:"code"}]},description:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]}}},LU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},identity:{min:1,type:[{code:"id"}]},language:{type:[{code:"code"}]},map:{min:1,type:[{code:"string"}]},comment:{type:[{code:"string"}]}}},IU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},description:{type:[{code:"string"}]},name:{type:[{code:"id"}]},language:{min:1,type:[{code:"code"}]},expression:{type:[{code:"string"}]},reference:{type:[{code:"uri"}]}}},zU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},url:{min:1,type:[{code:"uri"}]},"value[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]}}},$U={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},text:{type:[{code:"string"}]},family:{type:[{code:"string"}]},given:{max:9007199254740991,type:[{code:"string"}]},prefix:{max:9007199254740991,type:[{code:"string"}]},suffix:{max:9007199254740991,type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},UU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"CodeableConcept"}]},system:{type:[{code:"uri"}]},value:{type:[{code:"string"}]},period:{type:[{code:"Period"}]},assigner:{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Organization"]}]}}},BU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},country:{min:1,type:[{code:"CodeableConcept"}]},jurisdiction:{type:[{code:"CodeableConcept"}]},status:{min:1,type:[{code:"CodeableConcept"}]},dateRange:{min:1,type:[{code:"Period"}]},restoreDate:{type:[{code:"dateTime"}]}}},VU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},versionId:{type:[{code:"id"}]},lastUpdated:{type:[{code:"instant"}]},source:{type:[{code:"uri"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},security:{max:9007199254740991,type:[{code:"Coding"}]},tag:{max:9007199254740991,type:[{code:"Coding"}]},project:{type:[{code:"uri"}]},author:{type:[{code:"Reference"}]},onBehalfOf:{type:[{code:"Reference"}]},account:{type:[{code:"Reference"}]},accounts:{max:9007199254740991,type:[{code:"Reference"}]},compartment:{max:9007199254740991,type:[{code:"Reference"}]}}},FU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},HU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},qU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"code"}]},use:{min:1,type:[{code:"code"}]},min:{type:[{code:"integer"}]},max:{type:[{code:"string"}]},documentation:{type:[{code:"string"}]},type:{min:1,type:[{code:"code"}]},profile:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]}}},GU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},WU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},"age[x]":{type:[{code:"Range"},{code:"CodeableConcept"}]},gender:{type:[{code:"CodeableConcept"}]},race:{type:[{code:"CodeableConcept"}]},physiologicalCondition:{type:[{code:"CodeableConcept"}]}}},QU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},height:{type:[{code:"Quantity"}]},width:{type:[{code:"Quantity"}]},depth:{type:[{code:"Quantity"}]},weight:{type:[{code:"Quantity"}]},nominalVolume:{type:[{code:"Quantity"}]},externalDiameter:{type:[{code:"Quantity"}]},shape:{type:[{code:"string"}]},color:{max:9007199254740991,type:[{code:"string"}]},imprint:{max:9007199254740991,type:[{code:"string"}]},image:{max:9007199254740991,type:[{code:"Attachment"}]},scoring:{type:[{code:"CodeableConcept"}]}}},YU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},identifier:{type:[{code:"Identifier"}]},type:{min:1,type:[{code:"CodeableConcept"}]},period:{min:1,type:[{code:"Quantity"}]},specialPrecautionsForStorage:{max:9007199254740991,type:[{code:"CodeableConcept"}]}}},KU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},XU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},low:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},high:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},JU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},ZU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},reference:{type:[{code:"string"}]},type:{type:[{code:"uri"}]},identifier:{type:[{code:"Identifier"}]},display:{type:[{code:"string"}]}}},eB={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},label:{type:[{code:"string"}]},display:{type:[{code:"string"}]},citation:{type:[{code:"markdown"}]},url:{type:[{code:"url"}]},document:{type:[{code:"Attachment"}]},resource:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/Resource"]}]}}},tB={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},origin:{min:1,type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},period:{min:1,type:[{code:"decimal"}]},factor:{type:[{code:"decimal"}]},lowerLimit:{type:[{code:"decimal"}]},upperLimit:{type:[{code:"decimal"}]},dimensions:{min:1,type:[{code:"positiveInt"}]},data:{type:[{code:"string"}]}}},nB={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,max:9007199254740991,type:[{code:"Coding"}]},when:{min:1,type:[{code:"instant"}]},who:{min:1,type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/PractitionerRole","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/Device","http://hl7.org/fhir/StructureDefinition/Organization"]}]},onBehalfOf:{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/PractitionerRole","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/Device","http://hl7.org/fhir/StructureDefinition/Organization"]}]},targetFormat:{type:[{code:"code"}]},sigFormat:{type:[{code:"code"}]},data:{type:[{code:"base64Binary"}]}}},rB={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},"amount[x]":{type:[{code:"Quantity"},{code:"Range"},{code:"string"}]},amountType:{type:[{code:"CodeableConcept"}]},amountText:{type:[{code:"string"}]},referenceRange:{type:[{code:"SubstanceAmountReferenceRange"}]}}},iB={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]},highLimit:{type:[{code:"Quantity"}]}}},oB={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},event:{max:9007199254740991,type:[{code:"dateTime"}]},repeat:{type:[{code:"TimingRepeat"}]},code:{type:[{code:"CodeableConcept"}]}}},aB={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},"bounds[x]":{type:[{code:"Duration"},{code:"Range"},{code:"Period"}]},count:{type:[{code:"positiveInt"}]},countMax:{type:[{code:"positiveInt"}]},duration:{type:[{code:"decimal"}]},durationMax:{type:[{code:"decimal"}]},durationUnit:{type:[{code:"code"}]},frequency:{type:[{code:"positiveInt"}]},frequencyMax:{type:[{code:"positiveInt"}]},period:{type:[{code:"decimal"}]},periodMax:{type:[{code:"decimal"}]},periodUnit:{type:[{code:"code"}]},dayOfWeek:{max:9007199254740991,type:[{code:"code"}]},timeOfDay:{max:9007199254740991,type:[{code:"time"}]},when:{max:9007199254740991,type:[{code:"code"}]},offset:{type:[{code:"unsignedInt"}]}}},sB={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{type:[{code:"string"}]},"timing[x]":{type:[{code:"Timing"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Schedule"]},{code:"date"},{code:"dateTime"}]},data:{max:9007199254740991,type:[{code:"DataRequirement"}]},condition:{type:[{code:"Expression"}]}}},lB={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},code:{min:1,type:[{code:"Coding"}]},"value[x]":{min:1,type:[{code:"CodeableConcept"},{code:"Quantity"},{code:"Range"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/PlanDefinition","http://hl7.org/fhir/StructureDefinition/ResearchStudy","http://hl7.org/fhir/StructureDefinition/InsurancePlan","http://hl7.org/fhir/StructureDefinition/HealthcareService","http://hl7.org/fhir/StructureDefinition/Group","http://hl7.org/fhir/StructureDefinition/Location","http://hl7.org/fhir/StructureDefinition/Organization"]}]}}},cB={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},uB={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{max:0,type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},dB={elements:{authorizeUrl:{min:1,type:[{code:"string"}]},tokenUrl:{min:1,type:[{code:"string"}]},tokenAuthMethod:{type:[{code:"code"}]},userInfoUrl:{min:1,type:[{code:"string"}]},clientId:{min:1,type:[{code:"string"}]},clientSecret:{min:1,type:[{code:"string"}]},usePkce:{type:[{code:"boolean"}]},useSubject:{type:[{code:"boolean"}]}}},fB={Element:lU,BackboneElement:cU,Address:uU,Age:dU,Annotation:fU,Attachment:hU,CodeableConcept:pU,Coding:mU,ContactDetail:gU,ContactPoint:vU,Contributor:yU,Count:xU,DataRequirement:bU,DataRequirementCodeFilter:SU,DataRequirementDateFilter:jU,DataRequirementSort:wU,Distance:CU,Dosage:EU,DosageDoseAndRate:TU,Duration:RU,ElementDefinition:_U,ElementDefinitionSlicingDiscriminator:DU,ElementDefinitionSlicing:AU,ElementDefinitionBase:kU,ElementDefinitionType:PU,ElementDefinitionExample:NU,ElementDefinitionConstraint:OU,ElementDefinitionBinding:MU,ElementDefinitionMapping:LU,Expression:IU,Extension:zU,HumanName:$U,Identifier:UU,MarketingStatus:BU,Meta:VU,Money:FU,Narrative:HU,ParameterDefinition:qU,Period:GU,Population:WU,ProdCharacteristic:QU,ProductShelfLife:YU,Quantity:KU,Range:XU,Ratio:JU,Reference:ZU,RelatedArtifact:eB,SampledData:tB,Signature:nB,SubstanceAmount:rB,SubstanceAmountReferenceRange:iB,Timing:oB,TimingRepeat:aB,TriggerDefinition:sB,UsageContext:lB,MoneyQuantity:cB,SimpleQuantity:uB,IdentityProvider:dB};function hB(e){return new mB(e).parse()}const Fp=sU(fB),uS=Object.create(null),PT=Object.create(null),pB={"http://hl7.org/fhir/StructureDefinition/MoneyQuantity":"MoneyQuantity","http://hl7.org/fhir/StructureDefinition/SimpleQuantity":"SimpleQuantity","http://hl7.org/fhir/uv/sql-on-fhir/StructureDefinition/ViewDefinition":"ViewDefinition"};function rk(e){let t;return t=PT[e],t||(t=PT[e]=Object.create(null)),t}function NT(e){const n=(Array.isArray(e)?e:e.entry?.map(r=>r.resource)??[]).filter(r=>r?.resourceType==="StructureDefinition");nV(n);for(const r of n)ik(r)}function ik(e){if(!e?.name)throw new Error("Failed loading StructureDefinition from bundle");if(e.resourceType!=="StructureDefinition")return;const t=hB(e),n=pB[e.url];let r,i;n?(r=Fp,i=n):e.url===`http://hl7.org/fhir/StructureDefinition/${e.type}`||e.url===`https://medplum.com/fhir/StructureDefinition/${e.type}`||e.type?.startsWith("http://")||e.type?.startsWith("https://")?(r=Fp,i=e.type):(r=rk(e.url),i=e.type),r[i]=t;for(const s of t.innerTypes)s.parentType=t,r[s.name]=s;uS[e.url]=t}function ok(e){return!!Fp[e]}function Gm(e,t){if(t){const n=rk(t)[e];if(n)return n}return Fp[e]}function ak(e,t){const n=Gm(e,t);if(!n)throw new ut(Oo("Unknown data type: "+e));return n}function dS(e){return!!uS[e]}function Su(e){return uS[e]}class mB{root;elements;elementIndex;index;resourceSchema;slicingContext;innerTypes;backboneContext;constructor(t){if(!t.snapshot?.element||t.snapshot.element.length===0)throw new Error(`No snapshot defined for StructureDefinition '${t.name}'`);this.root=t.snapshot.element[0],this.elements=t.snapshot.element.slice(1),this.elementIndex=Object.create(null),this.index=0,this.resourceSchema={name:t.name,path:this.root.path,title:t.title,type:t.type,url:t.url,version:t.version,kind:t.kind,description:yB(t),elements:{},constraints:this.parseElementDefinition(this.root).constraints,innerTypes:[],summaryProperties:new Set,mandatoryProperties:new Set},this.innerTypes=[]}parse(){let t=this.next();for(;t;){if(t.sliceName)this.parseSliceStart(t);else if(t.id?.includes(":")){if(this.slicingContext?.current){const n=tx(t,this.slicingContext.path);this.slicingContext.current.elements[n]=this.parseElementDefinition(t)}}else{const n=this.parseElementDefinition(t);this.checkFieldEnter(t,n);let r=this.backboneContext;for(;r;){if(t.path?.startsWith(r.path+".")){r.type.elements[tx(t,r.path)]=n;break}r=r.parent}if(!r){const i=tx(t,this.root.path);t.isSummary&&this.resourceSchema.summaryProperties?.add(i.replace("[x]","")),n.min>0&&this.resourceSchema.mandatoryProperties?.add(i.replace("[x]","")),this.resourceSchema.elements[i]=n}this.checkFieldExit(t)}t=this.next()}return this.checkFieldExit(),this.innerTypes.length>0&&(this.resourceSchema.innerTypes=this.innerTypes),this.resourceSchema}checkFieldEnter(t,n){this.isInnerType(t)&&this.enterInnerType(t),this.slicingContext&&!Ic(this.slicingContext.path,t?.path)&&(this.slicingContext=void 0),t.slicing&&!this.slicingContext&&this.enterSlice(t,n)}enterInnerType(t){for(;this.backboneContext&&!Ic(this.backboneContext?.path,t.path);)this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;const n=BT(t);this.backboneContext={type:{name:n,type:n,path:t.path,title:t.label,description:t.definition,elements:{},constraints:this.parseElementDefinition(t).constraints,innerTypes:[]},path:t.path,parent:Ic(this.backboneContext?.path,t.path)?this.backboneContext:this.backboneContext?.parent}}enterSlice(t,n){vB(t)&&!this.peek()?.sliceName||(n.slicing={discriminator:(t.slicing?.discriminator??[]).map(r=>{if(r.type!=="value"&&r.type!=="pattern"&&r.type!=="type")throw new Error(`Unsupported slicing discriminator type: ${r.type}`);return{path:r.path,type:r.type}}),slices:[],ordered:t.slicing?.ordered??!1,rule:t.slicing?.rules},this.slicingContext={field:n.slicing,path:t.path??""})}checkFieldExit(t=void 0){if(this.backboneContext&&!Ic(this.backboneContext.path,t?.path))if(this.backboneContext.parent)do this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;while(this.backboneContext&&!Ic(this.backboneContext.path,t?.path));else this.innerTypes.push(this.backboneContext.type),this.backboneContext=void 0}next(){const t=this.peek();if(t)return this.index++,t}peek(){const t=this.elements[this.index];if(t){if(this.elementIndex[t.path??""]=t,t.contentReference){const n=t.contentReference.slice(t.contentReference.indexOf("#")+1),r=this.elementIndex[n];return r?{...r,id:t.id,path:t.path,min:t.min??r.min,max:t.max??r.max,base:{path:r.base?.path??n,min:t.base?.min??r.base?.min??r.min,max:t.base?.max??r.base?.max??r.max},contentReference:t.contentReference,definition:t.definition}:void 0}return t}}isInnerType(t){const n=this.peek();return!!(Ic(t?.path,n?.path)&&t.type?.some(r=>["BackboneElement","Element"].includes(r.code)))}parseSliceStart(t){if(!this.slicingContext)throw new Error(`Invalid slice start before discriminator: ${t.sliceName} (${t.id})`);this.slicingContext.current={...this.parseElementDefinition(t),name:t.sliceName??"",definition:t.definition,elements:{}},this.slicingContext.field.slices.push(this.slicingContext.current)}parseElementDefinitionType(t){return(t.type??[]).map(n=>{let r;return(n.code==="BackboneElement"||n.code==="Element")&&(r=BT(t)),r||(r=po(n,"http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type")?.valueUrl),r||(r=n.code??""),{code:r,targetProfile:n.targetProfile,profile:n.profile}})}parseElementDefinition(t){const n=OT(t.max),r=t.base?.max?OT(t.base.max):n,i={type:"ElementDefinition",value:t};return{description:t.definition||"",path:t.path||t.base?.path||"",min:t.min??0,max:n,isArray:r>1,constraints:(t.constraint??[]).map(s=>({key:s.key??"",severity:s.severity??"error",expression:s.expression??"",description:s.human??""})),type:this.parseElementDefinitionType(t),fixed:MT(Hd(i,"fixed[x]")),pattern:MT(Hd(i,"pattern[x]")),binding:t.binding}}}function OT(e){return e==="*"?Number.POSITIVE_INFINITY:Number.parseInt(e,10)}function tx(e,t=""){return gB(e.path,t)}function gB(e,t){return e?t&&e.startsWith(t)?e.substring(t.length+1):e:""}function Ic(e,t){return!e||!t?!1:t.startsWith(e+".")||t===e}function MT(e){return Array.isArray(e)&&e.length>0?e[0]:kn(e)?void 0:e}function vB(e){const t=e.slicing?.discriminator;return!!(e.type?.some(n=>n.code==="Extension")&&t?.length===1&&t[0].type==="value"&&t[0].path==="url")}function yB(e){let t=e.description;return t?.startsWith(`Base StructureDefinition for ${e.name} Type: `)&&(t=t.substring(`Base StructureDefinition for ${e.name} Type: `.length)),t}function xB(e,t,n){if(e===void 0)return[void 0];if(t==="$this")return[e];const r=n?.withPath?sk:Hd,[i,...s]=t.split(".");let c=[r(e,i,n)];for(const u of s){const f=[];for(const h of c)if(Array.isArray(h))for(const m of h)f.push(r(m,u,n));else(n?.withPath&&h?.value!==void 0||!n?.withPath&&h!==void 0)&&f.push(r(h,u,n));c=f}return c}function sk(e,t,n){const r=e.path;return bB(Hd(e,t,n),r,t)}function bB(e,t,n){const r=t?t+".":"";return e===void 0?{type:"undefined",value:void 0,path:`${r}${n}`}:Array.isArray(e)?e.map((i,s)=>({...i,path:`${r}${n}[${s}]`})):{...e,path:`${r}${n}`}}const lk={date:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1]))?)?$/,dateTime:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1])(T([01]\d|2[0-3])(:[0-5]\d:([0-5]\d|60)(\.\d{1,9})?)?)?)?(Z|[+-]((0\d|1[0-3]):[0-5]\d|14:00)?)?)?$/};function SB(e,t,n,r){if(Array.isArray(e))return!1;let i;t.path==="$this"?i=n:i=(r??n.elements)[t.path];const s=n.type;switch(t.type){case"value":case"pattern":if(!e||!i)return!1;if(i.pattern)return pS(e,i.pattern);if(i.fixed)return $i(e,i.fixed);if(i.binding?.strength==="required"&&i.binding.valueSet)return!0;break;case"type":return!e||!s?.length?!1:s.some(c=>c.code===e.type)}return!1}function Je(e){return[{type:re.boolean,value:e}]}function mi(e){return e==null?{type:"undefined",value:void 0}:Number.isSafeInteger(e)?{type:re.integer,value:e}:typeof e=="number"?{type:re.decimal,value:e}:typeof e=="boolean"?{type:re.boolean,value:e}:typeof e=="string"?{type:re.string,value:e}:Ii(e)?{type:re.Quantity,value:e}:Oa(e)?{type:e.resourceType,value:e}:Sk(e)?{type:re.CodeableConcept,value:e}:bk(e)?{type:re.Coding,value:e}:{type:re.BackboneElement,value:e}}function ko(e){return e.length===0?!1:!!e[0].value}function Ca(e,t){if(e.length!==0){if(e.length===1&&(!t||e[0].type===t))return e[0];throw new Error(`Expected singleton of type ${t}, but found ${JSON.stringify(e)}`)}}function Hd(e,t,n){if(!e.value)return;const r=Ps(e.type,t,n?.profileUrl);return r?ck(e,t,r):Tf(e,t)}function ck(e,t,n){const r=e.value,i=n.type;if(!i||i.length===0)return;let s,c="undefined",u;const f=n.path.lastIndexOf("."),h=n.path.substring(f+1);let m=h,g=!1;h.endsWith("[x]")&&(m=h.substring(0,h.length-3),g=!0);for(const y of i){let x=m;if(g&&(x+=Xn(y.code)),s=r[x],u=r["_"+x],s!==void 0||u!==void 0){c=y.code;break}}if(u)if(Array.isArray(s)){s=s.slice();for(let y=0;y<Math.max(s.length,u.length);y++)s[y]=nx(s[y],u[y])}else if(!s&&Array.isArray(u)){s=u.slice();for(let y=0;y<u.length;y++)s[y]=nx(void 0,u[y])}else s=nx(s,u);if(!kn(s))return(c==="Element"||c==="BackboneElement")&&(c=n.type[0].code),Array.isArray(s)?s.map(y=>LT(y,c)):LT(s,c)}function LT(e,t){return t==="Resource"&&Oa(e)&&(t=e.resourceType),{type:t,value:e}}function Tf(e,t){const n=e.value;if(!n||typeof n!="object")return;let r;if(t in n){const i=n[t];Array.isArray(i)?r=i.map(mi):r=mi(i)}else{const i=t.endsWith("[x]")?t.substring(0,t.length-3):t;for(const s of Object.values(re)){const c=i+Xn(s);if(c in n){const u=n[c];Array.isArray(u)?r=u.map(f=>({type:s,value:f})):r={type:s,value:u};break}}}if(Array.isArray(r)){if(r.length===0||kn(r[0]))return}else if(kn(r))return;return r}function uk(e){const t=[];for(const n of e){let r=!1;for(const i of t)if(ko(Wm(n,i))){r=!0;break}r||t.push(n)}return t}function jB(e){return Je(!ko(e))}function wB(e,t){return e.length===0||t.length===0?[]:e.length!==t.length?Je(!1):Je(e.every((n,r)=>ko(Wm(n,t[r]))))}function CB(e,t){return e.length===0||t.length===0?[]:e.length!==t.length?Je(!0):Je(e.some((n,r)=>!ko(Wm(n,t[r]))))}function Wm(e,t){const n=e.value?.valueOf(),r=t.value?.valueOf();return typeof n=="number"&&typeof r=="number"?Je(Math.abs(n-r)<1e-8):Ii(n)&&Ii(r)?Je(gk(n,r)):Je(typeof n=="object"&&typeof r=="object"?fS(e,t):n===r)}function dk(e,t){return e.length===0&&t.length===0?Je(!0):e.length!==t.length?Je(!1):(e.sort(IT),t.sort(IT),Je(e.every((n,r)=>ko(EB(n,t[r])))))}function EB(e,t){const{type:n,value:r}=e,{type:i,value:s}=t,c=r?.valueOf(),u=s?.valueOf();return typeof c=="number"&&typeof u=="number"?Je(Math.abs(c-u)<.01):Ii(c)&&Ii(u)?Je(gk(c,u)):Je(n==="Coding"&&i==="Coding"?typeof c!="object"||typeof u!="object"?!1:c.code===u.code&&c.system===u.system:typeof c=="object"&&typeof u=="object"?fS({...c,id:void 0},{...u,id:void 0}):typeof c=="string"&&typeof u=="string"?c.toLowerCase()===u.toLowerCase():c===u)}function IT(e,t){const n=e.value?.valueOf(),r=t.value?.valueOf();return typeof n=="number"&&typeof r=="number"?n-r:typeof n=="string"&&typeof r=="string"?n.localeCompare(r):0}function fk(e,t){const{value:n}=e;if(n==null)return!1;let r=t;switch(r.startsWith("System.")&&(r=r.substring(7)),r.startsWith("FHIR.")&&(r=r.substring(5)),r){case"Boolean":return typeof n=="boolean";case"Decimal":case"Integer":return typeof n=="number";case"Date":return hk(n);case"DateTime":return qd(n);case"Time":return typeof n=="string"&&!!/^T\d/.exec(n);case"Period":return pk(n);case"Quantity":return Ii(n);default:return e.type===r||typeof n=="object"&&n?.resourceType===r}}function hk(e){return typeof e=="string"&&!!lk.date.exec(e)}function qd(e){return typeof e=="string"&&!!lk.dateTime.exec(e)}function pk(e){return!!(e&&typeof e=="object"&&("start"in e&&qd(e.start)||"end"in e&&qd(e.end)))}function mk(e){if(e){if(hk(e)||qd(e))return{start:cp(e,"0000-01-01T00:00:00.000"),end:cp(e,"xxxx-12-31T23:59:59.999")};if(pk(e))return{start:e.start?cp(e.start,"0000-01-01T00:00:00.000"):void 0,end:e.end?cp(e.end,"xxxx-12-31T23:59:59.999"):void 0}}}function cp(e,t){let n="Z";const r=Math.max(e.indexOf("+",10),e.indexOf("-",10));r>-1?(n=e.substring(r),e=e.substring(0,r)):e.endsWith("Z")&&(e=e.substring(0,e.length-1));const i=e+t.substring(e.length)+n;return new Date(i).toISOString()}function Ii(e){return!!(e&&typeof e=="object"&&"value"in e&&typeof e.value=="number")}function gk(e,t){return Math.abs(e.value-t.value)<.01&&(e.unit===t.unit||e.code===t.code||e.unit===t.code||e.code===t.unit)}function fS(e,t){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n){const s=e[i],c=t[i];if(zT(s)&&zT(c)){if(!fS(s,c))return!1}else if(s!==c)return!1}return!0}function zT(e){return e!==null&&typeof e=="object"}function nx(e,t){if(t){if(typeof t!="object")throw new Error("Primitive extension must be an object");return TB(e??{},t)}return e}function TB(e,t){return delete t.__proto__,delete t.constructor,Object.assign(e,t)}function vk(e,t){return Oa(e,t)&&"id"in e&&typeof e.id=="string"}function nn(e){const t=$t(e)??"undefined/undefined",n=Ea(e);return n===t?{reference:t}:{reference:t,display:n}}function $t(e){if(Ma(e))return e.reference;if(vk(e))return`${e.resourceType}/${e.id}`}function bs(e){if(e)return Ma(e)?e.reference.split("/")[1]:e.id}function RB(e){return e.resourceType==="Patient"||e.resourceType==="Practitioner"||e.resourceType==="RelatedPerson"}function Ea(e){if(RB(e)){const t=_B(e);if(t)return t}if(e.resourceType==="Device"){const t=DB(e);if(t)return t}if(e.resourceType==="MedicationRequest"&&e.medicationCodeableConcept)return Ss(e.medicationCodeableConcept);if(e.resourceType==="Subscription"&&e.criteria)return e.criteria;if(e.resourceType==="User"&&e.email)return e.email;if("name"in e&&e.name&&typeof e.name=="string")return e.name;if("code"in e&&e.code){let t=e.code;if(Array.isArray(t)&&(t=t[0]),Sk(t))return Ss(t);if($B(t))return t.text}return $t(e)??""}function _B(e){const t=e.name;if(t&&t.length>0)return Na(t[0])}function DB(e){const t=e.deviceName;if(t&&t.length>0)return t[0].name}function AB(e){if(!("photo"in e))return;const t=e.photo;if(t)if(Array.isArray(t))for(const n of t){const r=$T(n);if(r)return r}else return $T(t)}function $T(e){if(e.url&&e.contentType?.startsWith("image/"))return e.url}function yk(e,t){const n=new Date(e);n.setUTCHours(0,0,0,0);const r=t?new Date(t):new Date;r.setUTCHours(0,0,0,0);const i=n.getUTCFullYear(),s=n.getUTCMonth(),c=n.getUTCDate(),u=r.getUTCFullYear(),f=r.getUTCMonth(),h=r.getUTCDate();let m=u-i;(f<s||f===s&&h<c)&&m--;let g=u*12+f-(i*12+s);h<c&&g--;const y=Math.floor((r.getTime()-n.getTime())/(1e3*60*60*24));return{years:m,months:g,days:y}}function kB(e,t){const{years:n,months:r,days:i}=yk(e,t);return n>=2?n.toString().padStart(3,"0")+"Y":r>=1?r.toString().padStart(3,"0")+"M":i.toString().padStart(3,"0")+"D"}function po(e,...t){let n=e;for(let r=0;r<t.length&&n;r++)n=n?.extension?.find(i=>i.url===t[r]);return n}function fo(e,t){const n=hS(e);return JSON.stringify(n,null,t?2:void 0)??""}function hS(e){if(!(e==null||e===""))return typeof e=="object"?Array.isArray(e)?PB(e):NB(e):e}function PB(e){const t=e.length;if(t===0)return;let n,r=0;for(let i=0;i<t;i++){const s=e[i],c=hS(s);c!==s&&!n&&(n=Array.from(e)),c===void 0?n&&(n[i]=null):(n&&(n[i]=c),r++)}if(r!==0)return n??e}function NB(e){let t,n=0;for(const r in e){const i=e[r],s=hS(i);s!==i&&!t&&(t={...e}),s===void 0?t&&delete t[r]:(t&&(t[r]=s),n++)}if(n!==0)return t??e}function kn(e){if(e==null)return!0;const t=typeof e;return t==="string"||t==="object"?!In(e):!1}function In(e){if(e==null)return!1;const t=typeof e;return t==="string"&&e!==""||t==="object"&&("length"in e&&e.length>0||Object.keys(e).length>0)}function OB(e){if(!e)return;let t=e.length-1;for(;t>=0&&kn(e[t]);)t--;return t>=0?e.slice(0,t+1):void 0}function $i(e,t,n){return e===t||kn(e)&&kn(t)?!0:kn(e)||kn(t)?!1:Array.isArray(e)&&Array.isArray(t)?MB(e,t):Array.isArray(e)||Array.isArray(t)?!1:mr(e)&&mr(t)?LB(e,t,n):(mr(e)||mr(t),!1)}function MB(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!$i(e[n],t[n]))return!1;return!0}function LB(e,t,n){const r=new Set;for(const i of Object.keys(e))r.add(i);for(const i of Object.keys(t))r.add(i);n==="meta"&&(r.delete("versionId"),r.delete("lastUpdated"),r.delete("author"));for(const i of r){const s=e[i],c=t[i];if(!$i(s,c,i))return!1}return!0}function pS(e,t){return kn(e)?!0:kn(t)?!1:Array.isArray(e)&&Array.isArray(t)?IB(e,t):Array.isArray(e)||Array.isArray(t)?!1:mr(e)&&mr(t)?zB(e,t):mr(e)||mr(t)?!1:e===t}function IB(e,t){return t.every(n=>e.some(r=>pS(r,n)))}function zB(e,t){return Object.entries(t).every(([n,r])=>n in e&&pS(e[n],r))}function gi(e){return e===void 0?e:JSON.parse(JSON.stringify(e))}function mS(e){return/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i.test(e)}function mr(e){return e!==null&&typeof e=="object"}function xk(e){return typeof e=="string"}function bk(e){return mr(e)&&"code"in e&&typeof e.code=="string"}function Sk(e){return mr(e)&&"coding"in e&&Array.isArray(e.coding)&&e.coding.every(bk)}function $B(e){return mr(e)&&"text"in e&&typeof e.text=="string"}const jk=[];for(let e=0;e<256;e++)jk.push(e.toString(16).padStart(2,"0"));function UB(e){const t=wk(e),n=new Uint8Array(t),r=new Array(n.length);for(let i=0;i<n.length;i++)r[i]=jk[n[i]];return r.join("")}function BB(e){const t=wk(e),n=new Uint8Array(t),r=new Array(n.length);for(let i=0;i<n.length;i++)r[i]=String.fromCodePoint(n[i]);return window.btoa(r.join(""))}function wk(e){return ArrayBuffer.isView(e)?e.buffer:e}function Xn(e){return e?e.charAt(0).toUpperCase()+e.substring(1):""}function gS(e){return e.length>0&&e.startsWith(e[0].toUpperCase())}function ml(e,t){const n=e+".";if(t.startsWith(n))return t.slice(n.length)}function VB(e,t){return e.coding?.find(n=>n.system===t)?.code}function FB(e){if(e!==void 0)return Array.isArray(e)?e:[e]}const UT=(e,t)=>new Promise((n,r)=>{t?.signal?.throwIfAborted();const i=setTimeout(n,e);t?.signal?.addEventListener("abort",()=>{clearTimeout(i),r(t.signal?.reason)},{once:!0})});function Yx(e,t,n){const r=[];for(let i=0;i<n-1;i++){const s=e.indexOf(t);if(s<0)break;r.push(e.slice(0,s)),e=e.slice(s+t.length)}return r.push(e),r}function HB(e){let t,n=!1;return function(){return n||(t=e(),n=!0),t}}function ul(e,t){return e?(e.push(t),e):[t]}function au(e){return e.sort((t,n)=>t.localeCompare(n))}function vS(e){return e.endsWith("/")?e:e+"/"}function qB(e){return e.startsWith("/")?e.slice(1):e}function Pi(e,t){return new URL(qB(t),vS(e.toString())).toString()}function GB(e,t){return Pi(e,t).toString().replace("http://","ws://").replace("https://","wss://")}function WB(e){return typeof e=="object"&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&(e=Object.fromEntries(Object.entries(e).filter(t=>t[1]!==void 0))),new URLSearchParams(e).toString()}function Ck(e,t){return e?.meta?.profile?.includes(t)||(e.meta=e.meta??{},e.meta.profile=e.meta.profile??[],e.meta.profile.push(t)),e}function QB(e,t){if(e?.meta?.profile?.includes(t)){const n=e.meta.profile.indexOf(t);e.meta.profile.splice(n,1)}return e}const Cr=Object.freeze([]);function El(e){if(!e)return"";switch(e.type){case"Address":return Ek(e.value);case"CodeableConcept":return Ss(e.value);case"Coding":return Rf(e.value);case"ContactPoint":return e.value.value;case"HumanName":return Na(e.value);case"Quantity":return gl(e.value);case"Reference":return YB(e.value);default:return e.value?.toString()??""}}function YB(e){return e?e.display??e.reference??fo(e):""}function Ek(e,t){if(!e)return"";const n=[];if(e.line&&n.push(...e.line),e.city||e.state||e.postalCode){const r=[];e.city&&r.push(e.city),e.state&&r.push(e.state),e.postalCode&&r.push(e.postalCode),n.push(r.join(", "))}return e.use&&t?.use,n.join(", ").trim()}function Na(e,t){if(!e)return"";const n=[];if(e.prefix&&t?.prefix!==!1&&n.push(...e.prefix),e.given&&n.push(...e.given),e.family&&n.push(e.family),e.suffix&&t?.suffix!==!1&&n.push(...e.suffix),e.use&&(t?.all||t?.use)&&n.push("["+e.use+"]"),n.length===0){const r=Wd(e.text);if(r)return r}return n.join(" ").trim()}function Qm(e){return e instanceof Date&&!Number.isNaN(e.getTime())}function Tk(e,t,n){if(!e)return"";const[r=0,i=0,s=0]=e.split(":").map(Number),c=new Date(Date.UTC(1970,0,1,r,i,s));return Qm(c)?new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit",second:s===0?void 0:"numeric",...n,timeZone:"UTC"}).format(c):""}function Nr(e,t,n){if(!e)return"";const r=new Date(e);return Qm(r)?r.toLocaleString(t,n):""}function KB(e,t,n){return!e||!e.start&&!e.end?"":Nr(e.start,t,n)+" - "+Nr(e.end,t,n)}const XB={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},JB={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},ZB={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function Rk(e){if(!e)return"";const t=[];return eV(t,e.repeat),e.event&&t.push(e.event.map(n=>Nr(n)).join(", ")),Xn(t.join(" ").trim())}function eV(e,t){if(!t?.periodUnit)return;const n=t.frequency??1,r=t.period??1,i=t.periodUnit;n===1&&r===1?e.push(XB[i]):(n===1?e.push("once"):e.push(n+" times"),r===1?e.push("per "+JB[i]):e.push("per "+r+" "+ZB[i])),t.dayOfWeek&&e.push("on "+t.dayOfWeek.map(Xn).join(", ")),t.timeOfDay&&e.push("at "+t.timeOfDay.map(s=>Tk(s)).join(", "))}function Gd(e,t,n=!1){if(n&&t===void 0)throw new Error("Precision must be specified for exclusive ranges");const r=e?.low&&{...e.low,comparator:void 0},i=e?.high&&{...e.high,comparator:void 0};return r?.value===void 0&&i?.value===void 0?"":r?.value!==void 0&&i?.value===void 0?`>= ${gl(r)}`:r?.value===void 0&&i?.value!==void 0?`<= ${gl(i)}`:(r?.unit===i?.unit&&delete r?.unit,`${gl(r)} - ${gl(i)}`)}function gl(e,t){if(!e)return"";const n=[];return e.comparator&&(n.push(e.comparator),n.push(" ")),e.value!==void 0&&n.push(e.value),e.unit&&(e.unit!=="%"&&n.at(-1)!==" "&&n.push(" "),n.push(e.unit)),n.join("").trim()}function tV(e){return e?.value===void 0?"":e.value.toLocaleString(void 0,{style:"currency",currency:e.currency??"USD",currencyDisplay:"narrowSymbol"})}function Ss(e){if(!e)return"";const t=Wd(e.text);return t||(e.coding?e.coding.map(n=>Rf(n)).join(", "):"")}function Rf(e,t){const n=Wd(e?.display);return n?`${n}`:Wd(e?.code)??""}function _k(e){if(!e)return"";const t=[];if(e.valueQuantity)t.push(gl(e.valueQuantity));else if(e.valueCodeableConcept)t.push(Ss(e.valueCodeableConcept));else{const n=Wd(e.valueString);n&&t.push(n)}return"component"in e&&t.push(e.component.map(n=>_k(n)).join(" / ")),t.join(" / ").trim()}function Wd(e){return typeof e=="string"?e:void 0}const re={Address:"Address",Age:"Age",Annotation:"Annotation",Attachment:"Attachment",BackboneElement:"BackboneElement",CodeableConcept:"CodeableConcept",Coding:"Coding",ContactDetail:"ContactDetail",ContactPoint:"ContactPoint",Contributor:"Contributor",Count:"Count",DataRequirement:"DataRequirement",Distance:"Distance",Dosage:"Dosage",Duration:"Duration",Element:"Element",ElementDefinition:"ElementDefinition",Expression:"Expression",Extension:"Extension",HumanName:"HumanName",Identifier:"Identifier",MarketingStatus:"MarketingStatus",Meta:"Meta",Money:"Money",MoneyQuantity:"MoneyQuantity",Narrative:"Narrative",ParameterDefinition:"ParameterDefinition",Period:"Period",Population:"Population",ProdCharacteristic:"ProdCharacteristic",ProductShelfLife:"ProductShelfLife",Quantity:"Quantity",Range:"Range",Ratio:"Ratio",Reference:"Reference",RelatedArtifact:"RelatedArtifact",SampledData:"SampledData",Signature:"Signature",SimpleQuantity:"SimpleQuantity",SubstanceAmount:"SubstanceAmount",SystemString:"http://hl7.org/fhirpath/System.String",Timing:"Timing",TriggerDefinition:"TriggerDefinition",UsageContext:"UsageContext",base64Binary:"base64Binary",boolean:"boolean",canonical:"canonical",code:"code",date:"date",dateTime:"dateTime",decimal:"decimal",id:"id",instant:"instant",integer:"integer",markdown:"markdown",oid:"oid",positiveInt:"positiveInt",string:"string",time:"time",unsignedInt:"unsignedInt",uri:"uri",url:"url",uuid:"uuid",xhtml:"xhtml"};function nV(e){const t=Array.isArray(e)?e:e.entry?.map(n=>n.resource)??[];for(const n of t)n?.resourceType==="StructureDefinition"&&n.kind==="resource"&&Dk(n.type)}function Dk(e){let t=$o.types[e];return t||(t={searchParamsDetails:{}},$o.types[e]=t),!t.searchParams&&e!=="Binary"&&(t.searchParams={_id:{base:[e],code:"_id",type:"token",expression:e+".id"},_lastUpdated:{base:[e],code:"_lastUpdated",type:"date",expression:e+".meta.lastUpdated"},_compartment:{base:[e],code:"_compartment",type:"reference",expression:e+".meta.compartment"},_profile:{base:[e],code:"_profile",type:"uri",expression:e+".meta.profile"},_security:{base:[e],code:"_security",type:"token",expression:e+".meta.security"},_source:{base:[e],code:"_source",type:"uri",expression:e+".meta.source"},_tag:{base:[e],code:"_tag",type:"token",expression:e+".meta.tag"}}),t}function rV(e){for(const t of e.base??Cr){const n=Dk(t);n.searchParams||(n.searchParams={}),n.searchParams[e.code]=e}}function BT(e){const t=e.type?.[0]?.code;return t==="BackboneElement"||t==="Element"?iV((e.base?.path??e.path)?.split(".")):t}function iV(e){return e.length===1?e[0]:e.map(Xn).join("")}function yS(e){return $o.types[e]?.searchParams}function oV(e,t){return $o.types[e]?.searchParams?.[t]}function Tl(e){const t=e.replaceAll("[x]","").split(".").pop();return Ak(t)}function Ak(e){let t;return e.length<100?t=e.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+/g)??[]:t=e.split(/(?=[A-Z])/),t.map(sV).join(" ").replace("_"," ").replaceAll(/\s+/g," ")}const aV=new Set(["CDS","ID","IP","PKCE","JWKS","URI","URL","OMB","UDI"]);function sV(e){const t=e.toUpperCase();return e===t?e:aV.has(t)?t:t.charAt(0)+e.slice(1)}function Ps(e,t,n){const r=Gm(e,n);if(r)return lV(r.elements,t)}function lV(e,t){const n=e[t]??e[t+"[x]"];if(n)return n;for(let r=0;r<t.length;r++){const i=t[r];if(i>="A"&&i<="Z"){const s=t.slice(0,r)+"[x]",c=e[s];if(c)return c}}}function Oa(e,t){return!(!e||typeof e!="object"||!("resourceType"in e)||t&&e.resourceType!==t)}function Ma(e,t){return!!(e&&typeof e=="object"&&"reference"in e&&typeof e.reference=="string")}const $o={types:{}};function Ep(e){if(e.startsWith("T"))return e+"T00:00:00.000Z".substring(e.length);if(e.length<=10)return e;try{return new Date(e).toISOString()}catch{return e}}const pa=()=>[],Xr={empty:(e,t)=>Je(t.every(n=>kn(n.value))),hasValue:(e,t)=>Je(t.length!==0),exists:(e,t,n)=>Je(n?t.some(r=>ko(n.eval(e,[r]))):t.length>0&&t.every(r=>!kn(r.value))),all:(e,t,n)=>Je(t.every(r=>ko(n.eval(e,[r])))),allTrue:(e,t)=>{for(const n of t)if(!n.value)return Je(!1);return Je(!0)},anyTrue:(e,t)=>{for(const n of t)if(n.value)return Je(!0);return Je(!1)},allFalse:(e,t)=>{for(const n of t)if(n.value)return Je(!1);return Je(!0)},anyFalse:(e,t)=>{for(const n of t)if(!n.value)return Je(!0);return Je(!1)},subsetOf:(e,t,n)=>{if(t.length===0)return Je(!0);const r=n.eval(e,rl(e));return r.length===0?Je(!1):Je(t.every(i=>r.some(s=>s.value===i.value)))},supersetOf:(e,t,n)=>{const r=n.eval(e,rl(e));return r.length===0?Je(!0):t.length===0?Je(!1):Je(r.every(i=>t.some(s=>s.value===i.value)))},count:(e,t)=>[{type:re.integer,value:t.length}],distinct:(e,t)=>{const n=[];for(const r of t)n.some(i=>i.value===r.value)||n.push(r);return n},isDistinct:(e,t)=>Je(t.length===Xr.distinct(e,t).length),where:(e,t,n)=>t.filter(r=>ko(n.eval(e,[r]))),select:(e,t,n)=>t.flatMap(r=>n.eval({parent:e,variables:{$this:r}},[r])),repeat:pa,ofType:(e,t,n)=>t.filter(r=>r.type===n.name),single:(e,t)=>{if(t.length>1)throw new Error("Expected input length one for single()");return t.length===0?[]:t.slice(0,1)},first:(e,t)=>t.length===0?[]:t.slice(0,1),last:(e,t)=>t.length===0?[]:t.slice(-1,t.length),tail:(e,t)=>t.length===0?[]:t.slice(1,t.length),skip:(e,t,n)=>{const r=n.eval(e,t)[0]?.value;if(typeof r!="number")throw new TypeError("Expected a number for skip(num)");return r>=t.length?[]:r<=0?t:t.slice(r,t.length)},take:(e,t,n)=>{const r=n.eval(e,t)[0]?.value;if(typeof r!="number")throw new TypeError("Expected a number for take(num)");return r>=t.length?t:r<=0?[]:t.slice(0,r)},intersect:(e,t,n)=>{if(!n)return t;const r=n.eval(e,rl(e)),i=[];for(const s of t)!i.some(c=>c.value===s.value)&&r.some(c=>c.value===s.value)&&i.push(s);return i},exclude:(e,t,n)=>{if(!n)return t;const r=n.eval(e,rl(e)),i=[];for(const s of t)r.some(c=>c.value===s.value)||i.push(s);return i},union:(e,t,n)=>{if(!n)return t;const r=n.eval(e,rl(e));return uk([...t,...r])},combine:(e,t,n)=>{if(!n)return t;const r=n.eval(e,rl(e));return[...t,...r]},htmlChecks:(e,t,n)=>[mi(!0)],iif:(e,t,n,r,i)=>{const s=n.eval(e,t);if(s.length>1||s.length===1&&typeof s[0].value!="boolean")throw new Error("Expected criterion to evaluate to a Boolean");return ko(s)?r.eval(e,t):i?i.eval(e,t):[]},toBoolean:(e,t)=>{if(t.length===0)return[];const[{value:n}]=To(t,1);if(typeof n=="boolean")return[{type:re.boolean,value:n}];if(typeof n=="number"&&(n===0||n===1))return Je(!!n);if(typeof n=="string"){const r=n.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(r))return Je(!0);if(["false","f","no","n","0","0.0"].includes(r))return Je(!1)}return[]},convertsToBoolean:(e,t)=>t.length===0?[]:Je(Xr.toBoolean(e,t).length===1),toInteger:(e,t)=>{if(t.length===0)return[];const[{value:n}]=To(t,1);return typeof n=="number"?[{type:re.integer,value:n}]:typeof n=="string"&&/^[+-]?\d+$/.exec(n)?[{type:re.integer,value:Number.parseInt(n,10)}]:typeof n=="boolean"?[{type:re.integer,value:n?1:0}]:[]},convertsToInteger:(e,t)=>t.length===0?[]:Je(Xr.toInteger(e,t).length===1),toDate:(e,t)=>{if(t.length===0)return[];const[{value:n}]=To(t,1);return typeof n=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(n)?[{type:re.date,value:Ep(n)}]:[]},convertsToDate:(e,t)=>t.length===0?[]:Je(Xr.toDate(e,t).length===1),toDateTime:(e,t)=>{if(t.length===0)return[];const[{value:n}]=To(t,1);return typeof n=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(n)?[{type:re.dateTime,value:Ep(n)}]:[]},convertsToDateTime:(e,t)=>t.length===0?[]:Je(Xr.toDateTime(e,t).length===1),toDecimal:(e,t)=>{if(t.length===0)return[];const[{value:n}]=To(t,1);return typeof n=="number"?[{type:re.decimal,value:n}]:typeof n=="string"&&/^-?\d{1,9}(\.\d{1,9})?$/.exec(n)?[{type:re.decimal,value:Number.parseFloat(n)}]:typeof n=="boolean"?[{type:re.decimal,value:n?1:0}]:[]},convertsToDecimal:(e,t)=>t.length===0?[]:Je(Xr.toDecimal(e,t).length===1),toQuantity:(e,t)=>{if(t.length===0)return[];const[{value:n}]=To(t,1);return Ii(n)?[{type:re.Quantity,value:n}]:typeof n=="number"?[{type:re.Quantity,value:{value:n,unit:"1"}}]:typeof n=="string"&&/^-?\d{1,9}(\.\d{1,9})?/.exec(n)?[{type:re.Quantity,value:{value:Number.parseFloat(n),unit:"1"}}]:typeof n=="boolean"?[{type:re.Quantity,value:{value:n?1:0,unit:"1"}}]:[]},convertsToQuantity:(e,t)=>t.length===0?[]:Je(Xr.toQuantity(e,t).length===1),toString:(e,t)=>{if(t.length===0)return[];const[{value:n}]=To(t,1);return n==null?[]:Ii(n)?[{type:re.string,value:`${n.value} '${n.unit}'`}]:[{type:re.string,value:n.toString()}]},convertsToString:(e,t)=>t.length===0?[]:Je(Xr.toString(e,t).length===1),toTime:(e,t)=>{if(t.length===0)return[];const[{value:n}]=To(t,1);if(typeof n=="string"){const r=/^T?(\d{2}(:\d{2}(:\d{2})?)?)/.exec(n);if(r)return[{type:re.time,value:Ep("T"+r[1])}]}return[]},convertsToTime:(e,t)=>t.length===0?[]:Je(Xr.toTime(e,t).length===1),indexOf:(e,t,n)=>Ai((r,i)=>r.indexOf(i),e,t,n),substring:(e,t,n,r)=>Ai((i,s,c)=>{const u=s,f=c?u+c:i.length;return u<0||u>=i.length?void 0:i.substring(u,f)},e,t,n,r),startsWith:(e,t,n)=>Ai((r,i)=>r.startsWith(i),e,t,n),endsWith:(e,t,n)=>Ai((r,i)=>r.endsWith(i),e,t,n),contains:(e,t,n)=>Ai((r,i)=>r.includes(i),e,t,n),upper:(e,t)=>Ai(n=>n.toUpperCase(),e,t),lower:(e,t)=>Ai(n=>n.toLowerCase(),e,t),replace:(e,t,n,r)=>Ai((i,s,c)=>i.replaceAll(s,c),e,t,n,r),matches:(e,t,n)=>Ai((r,i)=>!!new RegExp(i).exec(r),e,t,n),replaceMatches:(e,t,n,r)=>Ai((i,s,c)=>i.replaceAll(new RegExp(s,"g"),c.replaceAll(/\$\{(\w+)\}/g,"$<$1>")),e,t,n,r),length:(e,t)=>Ai(n=>n.length,e,t),toChars:(e,t)=>Ai(n=>n?n.split(""):void 0,e,t),encode:pa,decode:pa,escape:pa,unescape:pa,trim:pa,split:pa,join:(e,t,n)=>{const r=n?.eval(e,rl(e))[0]?.value??"";if(typeof r!="string")throw new TypeError("Separator must be a string.");return[{type:re.string,value:t.map(i=>i.value?.toString()??"").join(r)}]},abs:(e,t)=>wo(Math.abs,e,t),ceiling:(e,t)=>wo(Math.ceil,e,t),exp:(e,t)=>wo(Math.exp,e,t),floor:(e,t)=>wo(Math.floor,e,t),ln:(e,t)=>wo(Math.log,e,t),log:(e,t,n)=>wo((r,i)=>Math.log(r)/Math.log(i),e,t,n),power:(e,t,n)=>wo(Math.pow,e,t,n),round:(e,t,...n)=>wo((r,i=0)=>{if(typeof i!="number"||i<0)throw new Error("Invalid precision provided to round()");const s=Math.pow(10,i);return Math.round(r*s)/s},e,t,...n),sqrt:(e,t)=>wo(Math.sqrt,e,t),truncate:(e,t)=>wo(n=>Math.trunc(n),e,t),children:pa,descendants:pa,trace:(e,t,n)=>t,now:()=>[{type:re.dateTime,value:new Date().toISOString()}],timeOfDay:()=>[{type:re.time,value:new Date().toISOString().substring(11)}],today:()=>[{type:re.date,value:new Date().toISOString().substring(0,10)}],between:(e,t,n,r,i)=>{const s=Xr.toDateTime(e,n.eval(e,t));if(s.length===0)throw new Error("Invalid start date");const c=Xr.toDateTime(e,r.eval(e,t));if(c.length===0)throw new Error("Invalid end date");const u=i.eval(e,t)[0]?.value;if(u!=="years"&&u!=="months"&&u!=="days")throw new Error("Invalid units");const f=yk(s[0].value,c[0].value);return[{type:re.Quantity,value:{value:f[u],unit:u}}]},is:(e,t,n)=>{let r="";return n instanceof Qd?r=n.name:n instanceof Ym&&(r=n.left.name+"."+n.right.name),r?t.map(i=>({type:re.boolean,value:fk(i,r)})):[]},not:(e,t)=>Xr.toBoolean(e,t).map(n=>({type:re.boolean,value:!n.value})),resolve:(e,t)=>t.map(n=>{const r=n.value;let i;if(typeof r=="string")i=r;else if(typeof r=="object"){const s=r;if(s.resource)return mi(s.resource);s.reference?i=s.reference:s.type&&s.identifier&&(i=`${s.type}?identifier=${s.identifier.system}|${s.identifier.value}`)}if(i?.includes("?")){const[s]=i.split("?");return{type:s,value:{resourceType:s}}}if(i?.includes("/")){const[s,c]=i.split("/");return{type:s,value:{resourceType:s,id:c}}}return{type:re.BackboneElement,value:void 0}}).filter(n=>!!n.value),as:(e,t)=>t,type:(e,t)=>t.map(({value:n})=>typeof n=="boolean"?{type:re.BackboneElement,value:{namespace:"System",name:"Boolean"}}:typeof n=="number"?{type:re.BackboneElement,value:{namespace:"System",name:"Integer"}}:Oa(n)?{type:re.BackboneElement,value:{namespace:"FHIR",name:n.resourceType}}:{type:re.BackboneElement,value:null}),conformsTo:(e,t,n)=>{const r=n.eval(e,t)[0].value;if(!r.startsWith("http://hl7.org/fhir/StructureDefinition/"))throw new Error("Expected a StructureDefinition URL");const i=r.replace("http://hl7.org/fhir/StructureDefinition/","");return t.map(s=>({type:re.boolean,value:s.value?.resourceType===i}))},getResourceKey:(e,t)=>{const n=t[0].value;return n?.id?[{type:re.id,value:n.id}]:[]},getReferenceKey:(e,t,n)=>{const r=t[0].value;if(!r?.reference)return[];let i="";return n instanceof Qd&&(i=n.name),i&&!r.reference.startsWith(i+"/")?[]:[{type:re.id,value:bs(r)}]},extension:(e,t,n)=>{const r=n.eval(e,t)[0].value,i=t?.[0]?.value;if(i){const s=po(i,r);if(s)return[{type:re.Extension,value:s}]}return[]}};function Ai(e,t,n,...r){if(n.length===0)return[];const[{value:i}]=To(n,1);if(typeof i!="string")throw new TypeError("String function cannot be called with non-string");const s=r.map(u=>u?.eval(t,n)[0]?.value),c=e(i,...s);return c===void 0?[]:Array.isArray(c)?c.map(mi):[mi(c)]}function wo(e,t,n,...r){if(n.length===0)return[];const[{value:i}]=To(n,1),s=Ii(i),c=s?i.value:i;if(typeof c!="number")throw new TypeError("Math function cannot be called with non-number");const u=e(c,...r.map(m=>m.eval(t,n)[0]?.value)),f=s?re.Quantity:n[0].type,h=s?{...i,value:u}:u;return[{type:f,value:h}]}function To(e,t){if(e.length!==t)throw new Error(`Expected ${t} arguments`);for(const n of e)if(n==null)throw new Error("Expected non-null argument");return e}function rl(e){let t=e;for(;t.parent?.variables.$this;)t=t.parent;return[t.variables.$this]}class xS{original;child;constructor(t,n){this.original=t,this.child=n}eval(t,n){try{if(n.length>0){const r=[];for(const i of n)r.push(this.child.eval({parent:t,variables:{$this:i}},[i]));return r.flat()}else return this.child.eval(t,[])}catch(r){throw new Error(`FhirPathError on "${this.original}": ${r}`,{cause:r})}}toString(){return this.child.toString()}}class zc{value;constructor(t){this.value=t}eval(){return[this.value]}toString(){const t=this.value.value;return typeof t=="string"?`'${t}'`:t.toString()}}class Qd{name;constructor(t){this.name=t}eval(t,n){if(this.name==="$this")return n;const r=this.getVariable(t);if(r)return[r];if(this.name.startsWith("%"))throw new Error(`Undefined variable ${this.name}`);return n.flatMap(i=>this.evalValue(i)).filter(i=>i?.value!==void 0)}getVariable(t){const n=t.variables[this.name];if(n!==void 0)return n;if(t.parent)return this.getVariable(t.parent)}evalValue(t){const n=t.value;if(!(!n||typeof n!="object"))return Oa(n,this.name)?t:sk(t,this.name)}toString(){return this.name}}class cV{eval(){return[]}toString(){return"{}"}}class uV extends H8{impl;constructor(t,n,r){super(t,n),this.impl=r}eval(t,n){return this.impl(this.child.eval(t,n))}toString(){return this.operator+this.child.toString()}}class Hp extends wf{constructor(t,n){super("as",t,n)}eval(t,n){return Xr.ofType(t,this.left.eval(t,n),this.right)}}class ri extends wf{}class to extends ri{impl;constructor(t,n,r,i){super(t,n,r),this.impl=i}eval(t,n){const r=this.left.eval(t,n);if(r.length!==1)return[];const i=this.right.eval(t,n);if(i.length!==1)return[];const s=r[0].value,c=i[0].value,u=Ii(s)?s.value:s,f=Ii(c)?c.value:c,h=this.impl(u,f);return typeof h=="boolean"?Je(h):Ii(s)?[{type:re.Quantity,value:{...s,value:h}}]:[mi(h)]}}class dV extends wf{constructor(t,n){super("&",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n),s=[...r,...i];return s.length>0&&s.every(c=>typeof c.value=="string")?[{type:re.string,value:s.map(c=>c.value).join("")}]:s}}class fV extends ri{constructor(t,n){super("contains",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return Je(r.some(s=>s.value===i[0].value))}}class hV extends ri{constructor(t,n){super("in",t,n)}eval(t,n){const r=Ca(this.left.eval(t,n)),i=this.right.eval(t,n);return r?Je(i.some(s=>Wm(r,s)[0].value)):[]}}class Ym extends wf{constructor(t,n){super(".",t,n)}eval(t,n){return this.right.eval(t,this.left.eval(t,n))}toString(){return`${this.left.toString()}.${this.right.toString()}`}}class bS extends wf{constructor(t,n){super("|",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return uk([...r,...i])}}class pV extends ri{constructor(t,n){super("=",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return wB(r,i)}}class mV extends ri{constructor(t,n){super("!=",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return CB(r,i)}}class gV extends ri{constructor(t,n){super("~",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return dk(r,i)}}class vV extends ri{constructor(t,n){super("!~",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return jB(dk(r,i))}}class SS extends ri{constructor(t,n){super("is",t,n)}eval(t,n){const r=this.left.eval(t,n);if(r.length!==1)return[];const i=this.right.name;return Je(fk(r[0],i))}}class yV extends ri{constructor(t,n){super("and",t,n)}eval(t,n){const r=Ca(this.left.eval(t,n),"boolean"),i=Ca(this.right.eval(t,n),"boolean");return r?.value===!0&&i?.value===!0?Je(!0):r?.value===!1||i?.value===!1?Je(!1):[]}}class xV extends ri{constructor(t,n){super("or",t,n)}eval(t,n){const r=Ca(this.left.eval(t,n),"boolean"),i=Ca(this.right.eval(t,n),"boolean");return r?.value===!1&&i?.value===!1?Je(!1):r?.value||i?.value?Je(!0):[]}}class bV extends ri{constructor(t,n){super("xor",t,n)}eval(t,n){const r=Ca(this.left.eval(t,n),"boolean"),i=Ca(this.right.eval(t,n),"boolean");return!r||!i?[]:Je(r.value!==i.value)}}class SV extends ri{constructor(t,n){super("implies",t,n)}eval(t,n){const r=Ca(this.left.eval(t,n),"boolean"),i=Ca(this.right.eval(t,n),"boolean");return i?.value===!0||r?.value===!1?Je(!0):!r||!i?[]:Je(!1)}}class jS{name;args;constructor(t,n){this.name=t,this.args=n}eval(t,n){const r=Xr[this.name];if(!r)throw new Error("Unrecognized function: "+this.name);return r(t,n,...this.args)}toString(){return`${this.name}(${this.args.map(t=>t.toString()).join(", ")})`}}class wS{left;expr;constructor(t,n){this.left=t,this.expr=n}eval(t,n){const r=this.expr.eval(t,n);if(r.length!==1)return[];const i=r[0].value;if(typeof i!="number")throw new Error("Invalid indexer expression: should return integer}");const s=this.left.eval(t,n);return i in s?[s[i]]:[]}toString(){return`${this.left.toString()}[${this.expr.toString()}]`}}const jV=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"],wV={"'":"'",'"':'"',"`":"`",r:"\r",n:`
54
54
  `,t:" ",f:"\f","\\":"\\"};class CV{str;keywords;operators;dateTimeLiterals;symbolRegex;result=[];pos={index:0,line:1,column:0};markStack=[];constructor(t,n,r,i){this.str=t,this.keywords=n,this.operators=r,this.dateTimeLiterals=!!i?.dateTimeLiterals,this.symbolRegex=i?.symbolRegex??/[$\w%]/}tokenize(){for(;this.pos.index<this.str.length;){const t=this.consumeToken();t&&this.result.push(t)}return this.result}prevToken(){return this.result.slice(-1)[0]}peekToken(){this.mark();const t=this.consumeToken();return this.reset(),t}consumeToken(){this.consumeWhitespace();const t=this.curr();if(!t)return;this.mark();const n=this.peek();return t==="/"&&n==="*"?this.consumeMultiLineComment():t==="/"&&n==="/"?this.consumeSingleLineComment():t==="'"||t==='"'||t==="`"?this.consumeString(t):t==="@"?this.consumeDateTime():/\d/.exec(t)?this.consumeNumber():/\w/.exec(t)?this.consumeSymbol():(t==="$"||t==="%")&&/\w/.exec(n)?this.consumeSymbol():(t==="$"||t==="%")&&(n==="'"||n==='"'||n==="`")?this.consumeQuotedSymbol(n):this.consumeOperator()}consumeWhitespace(){this.consumeWhile(()=>/\s/.exec(this.curr()))}consumeMultiLineComment(){const t=this.pos.index;return this.consumeWhile(()=>this.curr()!=="*"||this.peek()!=="/"),this.advance(),this.advance(),this.buildToken("Comment",this.str.substring(t,this.pos.index))}consumeSingleLineComment(){return this.buildToken("Comment",this.consumeWhile(()=>this.curr()!==`
55
55
  `))}consumeString(t){this.advance();let n="",r;for(;r=this.consumeChar(t);)n+=r;const i=this.buildToken(t==="`"?"Symbol":"String",n);return this.advance(),i}consumeChar(t){const n=this.curr();if(n==="\\"){this.advance();const r=this.curr(),i=wV[r];if(i!==void 0)return this.advance(),i;if(r==="u"){this.advance();const s=/^[0-9a-fA-F]{4}$/.exec(this.str.substring(this.pos.index,this.pos.index+4))?.[0];return s?(this.advance(),this.advance(),this.advance(),this.advance(),String.fromCodePoint(Number.parseInt(s,16))):"u"}return this.consumeChar(t)}return n===t||!n?"":(this.advance(),n)}consumeQuotedSymbol(t){this.mark();const n=this.pos.index;this.advance(),this.consumeString(t);const r=this.str.substring(n,this.pos.index);return this.buildToken("Symbol",r)}consumeDateTime(){this.advance();const t=this.pos.index;this.consumeWhile(()=>/[\d-]/.exec(this.curr()));let n=!1,r=!1;if(this.curr()==="T"&&(n=!0,this.advance(),this.consumeWhile(()=>/[\d:]/.exec(this.curr())),this.curr()==="."&&/\d/.exec(this.peek())&&(this.advance(),this.consumeWhile(()=>/\d/.exec(this.curr()))),this.curr()==="Z"?(r=!0,this.advance()):(this.curr()==="+"||this.curr()==="-")&&(r=!0,this.advance(),this.consumeWhile(()=>/[\d:]/.exec(this.curr())))),this.pos.index===t)throw new Error("Invalid DateTime literal");let i=this.str.substring(t,this.pos.index);return i.endsWith("T")?i=i.substring(0,i.length-1):!i.startsWith("T")&&n&&!r&&(i+="Z"),this.buildToken("DateTime",i)}consumeNumber(){const t=this.pos.index;let n="Number";return this.consumeWhile(()=>/\d/.exec(this.curr())),this.curr()==="."&&/\d/.exec(this.peek())&&(this.advance(),this.consumeWhile(()=>/\d/.exec(this.curr()))),this.curr()==="-"&&this.dateTimeLiterals?(this.pos.index=t-1,this.consumeDateTime()):(this.curr()===" "&&EV(this.peekToken())&&(n="Quantity",this.consumeToken()),this.buildToken(n,this.str.substring(t,this.pos.index)))}consumeSymbol(){const t=this.consumeWhile(()=>this.symbolRegex.exec(this.curr()));return this.prevToken()?.value!=="."&&this.keywords.includes(t)?this.buildToken(t,t):this.buildToken("Symbol",t)}consumeOperator(){const t=this.curr(),n=this.peek(),r=t+n;return this.operators.includes(r)?(this.advance(),this.advance(),this.buildToken(r,r)):(this.advance(),this.buildToken(t,t))}consumeWhile(t){const n=this.pos.index;for(;this.pos.index<this.str.length&&t();)this.advance();return this.str.substring(n,this.pos.index)}curr(){return this.str[this.pos.index]}peek(){return this.str[this.pos.index+1]??""}mark(){this.markStack.push({...this.pos})}reset(){const t=this.markStack.pop();if(!t)throw new Error("No mark to reset to");this.pos.index=t.index,this.pos.line=t.line,this.pos.column=t.column}advance(){this.pos.index++,this.curr()===`
56
- `?(this.pos.line++,this.pos.column=0):this.pos.column++}buildToken(t,n){const r=this.markStack.pop();if(!r)throw new Error("No mark for token");return{id:t,value:n,...r}}}function EV(e){return!!(e&&(e.id==="String"||e.id==="Symbol"&&jV.includes(e.value)))}const TV=["true","false"],RV=["!=","!~","<=",">=","{}","->"];function _V(e){return new CV(e,TV,RV).tokenize()}const en={FunctionCall:0,Dot:1,Indexer:2,UnaryAdd:3,UnarySubtract:3,Multiply:4,Divide:4,Modulo:4,Add:5,Subtract:5,Ampersand:5,Is:6,As:6,Union:7,GreaterThan:8,GreaterThanOrEquals:8,LessThan:8,LessThanOrEquals:8,Equals:9,Equivalent:9,NotEquals:9,NotEquivalent:9,In:10,Contains:10,And:11,Xor:12,Or:12,Implies:13},DV={parse(e){const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+e.peek()?.value+"`");return t}},AV={parse(e,t){const n=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new wS(t,n)},precedence:en.Indexer},kV={parse(e,t){if(!(t instanceof Qd))throw new Error("Unexpected parentheses");const n=[];for(;!e.match(")");)n.push(e.consumeAndParse()),e.match(",");return new jS(t.name,n)},precedence:en.FunctionCall};function PV(e){const t=e.split(" "),n=Number.parseFloat(t[0]);let r=t[1];return r?.startsWith("'")&&r.endsWith("'")?r=r.substring(1,r.length-1):r="{"+r+"}",{value:n,unit:r}}function NV(){return new q8().registerPrefix("String",{parse:(e,t)=>new zc({type:re.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new zc({type:re.dateTime,value:Ep(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new zc({type:re.Quantity,value:PV(t.value)})}).registerPrefix("Number",{parse:(e,t)=>new zc({type:t.value.includes(".")?re.decimal:re.integer,value:Number.parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new zc({type:re.boolean,value:!0})}).registerPrefix("false",{parse:()=>new zc({type:re.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new Qd(t.value)}).registerPrefix("{}",{parse:()=>new cV}).registerPrefix("(",DV).registerInfix("[",AV).registerInfix("(",kV).prefix("+",en.UnaryAdd,(e,t)=>new uV("+",t,n=>n)).prefix("-",en.UnarySubtract,(e,t)=>new to("-",t,t,(n,r)=>-r)).infixLeft(".",en.Dot,(e,t,n)=>new Ym(e,n)).infixLeft("/",en.Divide,(e,t,n)=>new to("/",e,n,(r,i)=>r/i)).infixLeft("*",en.Multiply,(e,t,n)=>new to("*",e,n,(r,i)=>r*i)).infixLeft("+",en.Add,(e,t,n)=>new to("+",e,n,(r,i)=>r+i)).infixLeft("-",en.Subtract,(e,t,n)=>new to("-",e,n,(r,i)=>r-i)).infixLeft("|",en.Union,(e,t,n)=>new bS(e,n)).infixLeft("=",en.Equals,(e,t,n)=>new pV(e,n)).infixLeft("!=",en.NotEquals,(e,t,n)=>new mV(e,n)).infixLeft("~",en.Equivalent,(e,t,n)=>new gV(e,n)).infixLeft("!~",en.NotEquivalent,(e,t,n)=>new vV(e,n)).infixLeft("<",en.LessThan,(e,t,n)=>new to("<",e,n,(r,i)=>r<i)).infixLeft("<=",en.LessThanOrEquals,(e,t,n)=>new to("<=",e,n,(r,i)=>r<=i)).infixLeft(">",en.GreaterThan,(e,t,n)=>new to(">",e,n,(r,i)=>r>i)).infixLeft(">=",en.GreaterThanOrEquals,(e,t,n)=>new to(">=",e,n,(r,i)=>r>=i)).infixLeft("&",en.Ampersand,(e,t,n)=>new dV(e,n)).infixLeft("and",en.And,(e,t,n)=>new yV(e,n)).infixLeft("as",en.As,(e,t,n)=>new Hp(e,n)).infixLeft("contains",en.Contains,(e,t,n)=>new fV(e,n)).infixLeft("div",en.Divide,(e,t,n)=>new to("div",e,n,(r,i)=>Math.trunc(r/i))).infixLeft("in",en.In,(e,t,n)=>new hV(e,n)).infixLeft("is",en.Is,(e,t,n)=>new SS(e,n)).infixLeft("mod",en.Modulo,(e,t,n)=>new to("mod",e,n,(r,i)=>r%i)).infixLeft("or",en.Or,(e,t,n)=>new xV(e,n)).infixLeft("xor",en.Xor,(e,t,n)=>new bV(e,n)).infixLeft("implies",en.Implies,(e,t,n)=>new SV(e,n))}const OV=NV();function CS(e){return new xS(e,OV.construct(_V(e)).consumeAndParse())}function MV(e,t){const n=Array.isArray(t)?t:[t];for(let r=0;r<n.length;r++){const i=n[r];typeof i=="object"&&"type"in i&&"value"in i||(n[r]=mi(n[r]))}return js(e,n).map(r=>r.value)}function js(e,t,n={},r=void 0){let i;if(typeof e=="string"){const s=r?.get(e);i=s??CS(e),r&&!s&&r.set(e,i)}else i=e;return i.eval({variables:n},t).map(s=>{const c={type:s.type,value:s.value?.valueOf()};return"path"in s&&(c.path=s.path),c})}function LV(e){const t=[];for(const n of e){const r=mk(n.value);r&&t.push(r)}return t}function IV(e){const t=new Set;for(const n of e){const r=El(n);r&&t.add(r)}return Array.from(t)}function zV(e){const t=new Set;for(const n of e){const{value:r}=n;r&&(xk(r)?t.add(r):Ma(r)?t.add(r.reference):vk(r)?t.add($t(r)):typeof r.identifier=="object"&&t.add(`identifier:${r.identifier.system}|${r.identifier.value}`))}return Array.from(t)}function $V(e,t={}){const n=[];for(const r of e)UV(t,n,r);return n}function UV(e,t,n){const{type:r,value:i}=n;switch(r){case re.Identifier:BV(t,e,i);break;case re.CodeableConcept:VV(t,e,i);break;case re.Coding:kk(t,e,i);break;case re.ContactPoint:FV(t,e,i);break;default:Rl(t,e,void 0,i?.toString())}}function BV(e,t,n){n?.type?.text&&Rl(e,t,t.textSearchSystem,n.type.text),Rl(e,t,n?.system,n?.value)}function VV(e,t,n){n?.text&&Rl(e,t,t.textSearchSystem,n.text);for(const r of n?.coding??Cr)kk(e,t,r)}function kk(e,t,n){n&&(n.display&&Rl(e,t,t.textSearchSystem,n.display),Rl(e,t,n.system,n.code))}function FV(e,t,n){n&&Rl(e,t,n.system,n.value?.toLocaleLowerCase())}function Rl(e,t,n,r){(n||r)&&!e.some(i=>i.system===n&&i.value===r)&&e.push({system:n,value:r&&t.caseInsensitive?r.toLocaleLowerCase():r})}const Km=20,fe={EQUALS:"eq",NOT_EQUALS:"ne",GREATER_THAN:"gt",LESS_THAN:"lt",GREATER_THAN_OR_EQUALS:"ge",LESS_THAN_OR_EQUALS:"le",STARTS_AFTER:"sa",ENDS_BEFORE:"eb",APPROXIMATELY:"ap",CONTAINS:"contains",STARTS_WITH:"sw",EXACT:"exact",TEXT:"text",NOT:"not",ABOVE:"above",BELOW:"below",IN:"in",NOT_IN:"not-in",OF_TYPE:"of-type",MISSING:"missing",PRESENT:"present",IDENTIFIER:"identifier",ITERATE:"iterate"},Pk={contains:fe.CONTAINS,exact:fe.EXACT,above:fe.ABOVE,below:fe.BELOW,text:fe.TEXT,not:fe.NOT,in:fe.IN,"not-in":fe.NOT_IN,"of-type":fe.OF_TYPE,missing:fe.MISSING,identifier:fe.IDENTIFIER,iterate:fe.ITERATE},ES={eq:fe.EQUALS,ne:fe.NOT_EQUALS,lt:fe.LESS_THAN,le:fe.LESS_THAN_OR_EQUALS,gt:fe.GREATER_THAN,ge:fe.GREATER_THAN_OR_EQUALS,sa:fe.STARTS_AFTER,eb:fe.ENDS_BEFORE,ap:fe.APPROXIMATELY,sw:fe.STARTS_WITH};function Nk(e,t){if(!e)throw new Error("Invalid search URL");let n="",r;if(typeof e=="string")if(e.includes("?")){const[c,u]=e.split("?");n=c,r=new URLSearchParams(u)}else n=e;else typeof e=="object"&&(n=e.pathname,r=e.searchParams);let i;n.includes("/")?i=n.split("/").filter(Boolean).pop():i=n;const s=[];return r&&s.push(...r.entries()),HV(i,s)}function HV(e,t){const n={resourceType:e};for(const[r,i]of t)qV(n,r,i);return n}function qV(e,t,n){let r,i;const s=t.indexOf(":");if(s>=0?(r=t.substring(0,s),i=t.substring(s+1)):(r=t,i=""),r!=="_"){if(r==="_has"||t.includes(".")){e.filters=ul(e.filters,{code:t,operator:fe.EQUALS,value:n});return}switch(r){case"_sort":GV(e,n);break;case"_cursor":e.cursor=n;break;case"_count":e.count=Number.parseInt(n,10);break;case"_offset":e.offset=Number.parseInt(n,10);break;case"_total":e.total=n;break;case"_summary":n==="count"?(e.total="accurate",e.count=0):(n==="true"||n==="data"||n==="text")&&(e.summary=n);break;case"_include":{const c=VT(n);i==="iterate"&&(c.modifier=fe.ITERATE),e.include=ul(e.include,c);break}case"_revinclude":{const c=VT(n);i==="iterate"&&(c.modifier=fe.ITERATE),e.revInclude=ul(e.revInclude,c);break}case"_fields":case"_elements":e.fields=n.split(",");break;case"_type":e.types=n.split(",");break;case"_format":e.format=n;break;case"_pretty":e.pretty=n==="true";break;default:{const c=$o.types[e.resourceType]?.searchParams?.[r];c?e.filters=ul(e.filters,QV(c,i,n)):e.filters=ul(e.filters,YV(r,i,n))}}}}function GV(e,t){for(const n of t.split(",")){let r,i=!1;n.startsWith("-")?(r=n.substring(1),i=!0):r=n,e.sortRules||(e.sortRules=[]),e.sortRules.push({code:r,descending:i})}}const WV=[fe.MISSING,fe.PRESENT];function QV(e,t,n){if(WV.includes(t))return{code:e.code,operator:t,value:n};switch(e.type){case"number":case"date":case"quantity":{const{operator:r,value:i}=KV(n,t||fe.EQUALS);if(!FT(e,i))throw new ut(Oo(`Invalid format for ${e.type} search parameter: ${i}`));return{code:e.code,operator:r,value:i}}case"reference":case"string":case"token":case"uri":if(!FT(e,n))throw new ut(Oo(`Invalid format for ${e.type} search parameter: ${n}`));return{code:e.code,operator:XV(t),value:n};default:throw new Error("Unrecognized search parameter type: "+e.type)}}function YV(e,t,n){let r=fe.EQUALS;if(t)r=t;else if(n.length>=2){const i=n.substring(0,2);i in ES&&(n.length===2||n.at(2)?.match(/\d/))&&(r=i,n=n.substring(i.length))}return{code:e,operator:r,value:n}}function KV(e,t){const n=e.substring(0,2),r=ES[n];return r?{operator:r,value:e.substring(2)}:{operator:t,value:e}}function XV(e){return Pk[e]??fe.EQUALS}function VT(e){const t=e.split(":");if(t.includes("*"))throw new ut(Oo("'*' is not supported as a value for search inclusion parameters"));if(t.length===1)throw new ut(Oo(`Invalid include value '${e}': must be of the form ResourceType:search-parameter`));if(t.length===2)return{resourceType:t[0],searchParam:t[1]};if(t.length===3)return{resourceType:t[0],searchParam:t[1],targetType:t[2]};throw new ut(Oo(`Invalid include value '${e}'`))}function FT(e,t){return e.type==="date"?qd(t):!0}function vs(e){const t=[];e.fields&&t.push("_fields="+e.fields.join(","));for(const n of e.filters??Cr)t.push(JV(n));e.sortRules&&e.sortRules.length>0&&t.push(ZV(e.sortRules)),e.cursor!==void 0&&t.push("_cursor="+encodeURIComponent(e.cursor)),e.offset!==void 0&&e.offset!==0&&t.push("_offset="+e.offset),e.count!==void 0&&t.push("_count="+e.count),e.total!==void 0&&t.push("_total="+e.total),e.types&&e.types.length>0&&t.push("_type="+e.types.join(","));for(const n of e.include??Cr)t.push(HT("_include",n));for(const n of e.revInclude??Cr)t.push(HT("_revinclude",n));return t.length===0?"":(au(t),"?"+t.join("&"))}function JV(e){const t=e.operator in Pk?":"+e.operator:"",n=e.operator!==fe.EQUALS&&e.operator in ES?e.operator:"";return`${e.code}${t}=${n}${encodeURIComponent(e.value)}`}function ZV(e){return"_sort="+e.map(t=>t.descending?"-"+t.code:t.code).join(",")}function HT(e,t){return e+(t.modifier?":"+t.modifier:"")+"="+t.resourceType+":"+t.searchParam+(t.targetType?":"+t.targetType:"")}function Xm(e){const t=[];let n="",r=!1;for(const i of e)r?(n+=i,r=!1):i==="\\"?r=!0:i===","?(t.push(n),n=""):n+=i;return t.push(n),t}function eF(e,t){if(t.resourceType!==e.resourceType)return!1;for(const n of t.filters??Cr)if(!nF(e,t,n))return!1;return!0}const tF=new cS(1e3);function nF(e,t,n){const r=$o.types[t.resourceType]?.searchParams?.[n.code];if(!r)return!1;const i=js(r.expression,[mi(e)],void 0,tF);if(n.operator===fe.MISSING||n.operator===fe.PRESENT)return rF(i,n);switch(r.type){case"reference":return iF(i,n);case"string":case"uri":return sF(i,n);case"token":return oF(i,n);case"date":return cF(i,n);default:return!1}}function rF(e,t){const n=e.length>0;return(t.operator===fe.MISSING&&t.value==="false"||t.operator===fe.PRESENT&&t.value==="true")===n}function iF(e,t){const n=Jm(t.operator);if(t.value===""&&e.length===0)return t.operator===fe.EQUALS;const r=zV(e);for(const i of Xm(t.value)){let s=r.includes(i);if(!s&&t.code==="_compartment"&&(s=r.some(c=>c?.endsWith("/"+i))),s)return!n}return n}function oF(e,t){const n=$V(e),r=Xm(t.value),i=Jm(t.operator);for(const s of n)for(const c of r)if(aF(s,c))return!i;return i}function aF(e,t){if(t.includes("|")){const[n,r]=t.split("|").map(i=>i.toLowerCase());return!n&&!r?!1:n?e.system?.toLowerCase()===n&&(!r||e.value?.toLowerCase()===r):!e.system&&e.value?.toLowerCase()===r}return e.value?.toLowerCase()===t.toLowerCase()}function sF(e,t){const n=IV(e),r=Xm(t.value),i=Jm(t.operator);for(const s of n)for(const c of r)if(lF(s,c))return!i;return i}function lF(e,t){return e.toLowerCase().includes(t.toLowerCase())}function cF(e,t){const n=LV(e),r=Xm(t.value),i=Jm(t.operator);for(const s of n)for(const c of r)if(uF(s,t.operator,c))return!i;return i}function uF(e,t,n){if(!e)return!1;const r=mk(n);if(!r)return!1;const i=e.start??"0000",s=e.end??"9999",c=r.start,u=r.end;switch(t){case fe.APPROXIMATELY:case fe.EQUALS:case fe.NOT_EQUALS:return i<u&&s>c;case fe.LESS_THAN:return i<c;case fe.GREATER_THAN:return s>u;case fe.LESS_THAN_OR_EQUALS:return i<=u;case fe.GREATER_THAN_OR_EQUALS:return s>=c;case fe.STARTS_AFTER:return i>u;case fe.ENDS_BEFORE:return s<c;default:return!1}}function Jm(e){return e===fe.NOT_EQUALS||e===fe.NOT}const dF={resourceType:"*"},fF=["DomainConfiguration","JsonWebKey","Login"],hF=["UserSecurityRequest","Project","ProjectMembership","User"],vl={READ:"read",VREAD:"vread",UPDATE:"update",HISTORY:"history",SEARCH:"search"},pF=[vl.READ,vl.VREAD,vl.HISTORY,vl.SEARCH];function mF(e,t){return fF.includes(t)?!1:gF(e,vl.UPDATE,t)}function gF(e,t,n){return!!e.resource?.some(r=>Mk(r,n,t))}function Ok(e,t,n){return n?n.resource?.find(r=>vF(e,t,r)):dF}function vF(e,t,n){const r=e.resourceType;return Mk(n,r,t)?r==="Binary"?!0:!(n.compartment&&!e.meta?.compartment?.some(i=>i.reference===n.compartment?.reference)||n.criteria&&!eF(e,Nk(n.criteria))):!1}function Mk(e,t,n){return e.resourceType!==t&&(e.resourceType!=="*"||hF.includes(t))?!1:e.interaction?e.interaction.includes(n):!e.readonly||pF.includes(n)}function Ro(){return typeof window<"u"}function Lk(){return typeof Buffer<"u"?Buffer:void 0}const rr={assign(e){Ro()&&globalThis.location.assign(e)},reload(){Ro()&&globalThis.location.reload()},getSearch(){return Ro()?globalThis.location.search:""},getPathname(){return Ro()?globalThis.location.pathname:""},getLocation(){return Ro()?globalThis.location.toString():""},getOrigin(){return Ro()?globalThis.location.protocol+"//"+globalThis.location.host+"/":""}};function yF(e){if(Ro()){const n=window.atob(e),r=Uint8Array.from(n,i=>i.codePointAt(0));return new window.TextDecoder().decode(r)}const t=Lk();if(t)return t.from(e,"base64").toString("utf-8");throw new Error("Unable to decode base64")}function qT(e){if(Ro()){const n=new window.TextEncoder().encode(e),r=String.fromCodePoint.apply(null,n);return window.btoa(r)}const t=Lk();if(t)return t.from(e,"utf8").toString("base64");throw new Error("Unable to encode base64")}function xF(e){e=e.padEnd(e.length+(4-e.length%4)%4,"=");const t=e.replaceAll("-","+").replaceAll("_","/");return yF(t)}function GT(){const e=new Uint32Array(28);return crypto.getRandomValues(e),UB(e.buffer)}async function bF(e){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))}function Ik(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replaceAll(/[xy]/g,e=>{const t=Math.trunc(Math.random()*16);return(e==="x"?t:t&3|8).toString(16)})}function zk(e){const t={};e=gi(e);for(const i of e.entry??Cr){const s=i.resource;if(!s)continue;s.meta!==void 0&&(delete s.meta.author,delete s.meta.compartment,delete s.meta.lastUpdated,delete s.meta.project,delete s.meta.versionId,Object.keys(s.meta).length===0&&delete s.meta);const c=s?.id;c&&(t[c]=Ik(),i.fullUrl="urn:uuid:"+t[c],delete i.resource?.id)}const n=e.entry,r=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:n?.map(i=>({fullUrl:i.fullUrl,request:{method:"POST",url:i.resource?.resourceType},resource:i.resource}))},(i,s)=>SF(i,s,t),2);return jF(JSON.parse(r))}function SF(e,t,n){if(e==="reference"&&typeof t=="string"){let r;if(t.includes("/")?r=t.split("/")[1]:t.startsWith("urn:uuid:")?r=t.slice(9):t.startsWith("#")&&(r=t.slice(1)),r){const i=n[r];if(i)return"urn:uuid:"+i}}return t}function jF(e){const t=CF(e),{sorted:n,cycles:r}=wF(t),i={},s=[];for(const u of e.entry??Cr)u.fullUrl?i[u.fullUrl]=u:s.push(u);const c=n.map(u=>i[u]);for(const u of r)for(const f of u){const h=i[f],m={...h,request:{...h.request,method:"PUT"}};c.push(m)}return c.push(...s),{...e,entry:c}}const $c={NotVisited:"NotVisited",Visiting:"Visiting",Visited:"Visited"};function wF(e){const t=[],n={},r=[];for(const s of Object.keys(e))n[s]=$c.NotVisited;function i(s,c){if(n[s]===$c.Visited)return!0;if(n[s]===$c.Visiting){const f=c.lastIndexOf(s);return f!==-1&&r.push(c.slice(f)),!0}n[s]=$c.Visiting,c.push(s);let u=!1;for(const f of e[s])i(f,c)||(u=!0);return n[s]=$c.Visited,c.pop(),t.unshift(s),!u}for(const s in e)n[s]===$c.NotVisited&&i(s,[]);return{sorted:t,cycles:r}}function $k(e,t){for(const n in e)if(e[n]&&typeof e[n]=="object"){const r=e[n];if(Ma(r)){const i=r.reference;i.startsWith("urn:uuid:")&&t(i)}else $k(r,t)}}function CF(e){const t={};for(const n of e.entry??Cr)n.fullUrl&&(t[n.fullUrl]=[]);for(const n of e.entry??Cr){const r=n.fullUrl;n.resource&&$k(n.resource,i=>{t[i]&&t[i].push(r)})}return t}const tn={CSS:"text/css",DICOM:"application/dicom",FAVICON:"image/vnd.microsoft.icon",FHIR_JSON:"application/fhir+json",FORM_URL_ENCODED:"application/x-www-form-urlencoded",HL7_V2:"x-application/hl7-v2+er7",HTML:"text/html",JAVASCRIPT:"text/javascript",JSON:"application/json",JSON_PATCH:"application/json-patch+json",JWT:"application/jwt",MULTIPART_FORM_DATA:"multipart/form-data",PNG:"image/png",SCIM_JSON:"application/scim+json",SVG:"image/svg+xml",TEXT:"text/plain",TYPESCRIPT:"text/typescript",PING:"x-application/ping",XML:"text/xml",CDA_XML:"application/cda+xml",OCTET_STREAM:"application/octet-stream"};let EF=class{listeners;constructor(){this.listeners={}}addEventListener(t,n){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(n)}removeEventListener(t,n){const r=this.listeners[t];if(r){for(let i=0;i<r.length;i++)if(r[i]===n){r.splice(i,1);return}}}dispatchEvent(t){const n=this.listeners[t.type];for(const r of n??Cr)r.call(this,t);return!t.defaultPrevented}removeAllListeners(){this.listeners={}}listenerCount(t){return this.listeners[t]?.length??0}};class Zm{emitter=new EF;dispatchEvent(t){this.emitter.dispatchEvent(t)}addEventListener(t,n){this.emitter.addEventListener(t,n)}removeEventListener(t,n){this.emitter.removeEventListener(t,n)}removeAllListeners(){this.emitter.removeAllListeners()}listenerCount(t){return this.emitter.listenerCount(t)}}const Kx={"Patient-open":"Patient-open","Patient-close":"Patient-close","ImagingStudy-open":"ImagingStudy-open","ImagingStudy-close":"ImagingStudy-close","Encounter-open":"Encounter-open","Encounter-close":"Encounter-close","DiagnosticReport-open":"DiagnosticReport-open","DiagnosticReport-close":"DiagnosticReport-close","DiagnosticReport-select":"DiagnosticReport-select","DiagnosticReport-update":"DiagnosticReport-update",syncerror:"syncerror"},TF=["Patient","Encounter","ImagingStudy","DiagnosticReport","OperationOutcome","Bundle"],TS=["DiagnosticReport-update"];function RF(e){return TS.includes(e)}function _F(e){if(TS.includes(e))throw new ut(Sn(`'context.version' is required for '${e}'.`))}const DF={"Patient-open":{patient:{resourceType:"Patient"},encounter:{resourceType:"Encounter",optional:!0}},"Patient-close":{patient:{resourceType:"Patient"},encounter:{resourceType:"Encounter",optional:!0}},"ImagingStudy-open":{study:{resourceType:"ImagingStudy"},encounter:{resourceType:"Encounter",optional:!0},patient:{resourceType:"Patient",optional:!0}},"ImagingStudy-close":{study:{resourceType:"ImagingStudy"},encounter:{resourceType:"Encounter",optional:!0},patient:{resourceType:"Patient",optional:!0}},"Encounter-open":{encounter:{resourceType:"Encounter"},patient:{resourceType:"Patient"}},"Encounter-close":{encounter:{resourceType:"Encounter"},patient:{resourceType:"Patient"}},"DiagnosticReport-open":{report:{resourceType:"DiagnosticReport"},encounter:{resourceType:"Encounter",optional:!0},study:{resourceType:"ImagingStudy",optional:!0,manyAllowed:!0},patient:{resourceType:"Patient"}},"DiagnosticReport-close":{report:{resourceType:"DiagnosticReport"},encounter:{resourceType:"Encounter",optional:!0},study:{resourceType:"ImagingStudy",optional:!0,manyAllowed:!0},patient:{resourceType:"Patient"}},"DiagnosticReport-select":{report:{resourceType:"DiagnosticReport",reference:!0},patient:{resourceType:"Patient",optional:!0,reference:!0},select:{resourceType:"*",reference:!0,manyAllowed:!0}},"DiagnosticReport-update":{report:{resourceType:"DiagnosticReport",reference:!0},patient:{resourceType:"Patient",optional:!0,reference:!0},updates:{resourceType:"Bundle"}},syncerror:{operationoutcome:{resourceType:"OperationOutcome"}}};function AF(e){return TF.includes(e)}function Uk(e){return!!e.endpoint}function WT(e){if(!RS(e))throw new ut(Sn("subscriptionRequest must be an object conforming to SubscriptionRequest type."));const{channelType:t,mode:n,topic:r,events:i}=e,s={"hub.channel.type":t,"hub.mode":n,"hub.topic":r,"hub.events":i.join(",")};return Uk(e)&&(s.endpoint=e.endpoint),new URLSearchParams(s).toString()}function RS(e){if(typeof e!="object")return!1;const{channelType:t,mode:n,topic:r,events:i}=e;if(!(t&&n&&r&&i)||typeof r!="string"||typeof i!="object"||!Array.isArray(i)||i.length<1||t!=="websocket"||n!=="subscribe"&&n!=="unsubscribe")return!1;for(const s of i)if(!Kx[s])return!1;return!(Uk(e)&&!(typeof e.endpoint=="string"&&e.endpoint.startsWith("ws")))}function kF(e,t,n,r){if(typeof t!="object")throw new ut(Sn(`context[${n}] is invalid. Context must contain a single valid FHIR resource! Resource is not an object.`));if(!(t.id&&typeof t.id=="string"))throw new ut(Sn(`context[${n}] is invalid. Resource must contain a valid string ID.`));if(!t.resourceType)throw new ut(Sn(`context[${n}] is invalid. Resource must contain a resource type. No resource type found.`));const i=r.resourceType;if(i!=="*"){if(!AF(t.resourceType))throw new ut(Sn(`context[${n}] is invalid. Resource must contain a valid FHIRcast resource type. Resource type is not a known resource type.`));if(i&&t.resourceType!==i)throw new ut(Sn(`context[${n}] is invalid. context[${n}] for the '${e}' event should contain resource of type ${i}.`))}}function PF(e,t,n,r,i){if(i.set(t.key,(i.get(t.key)??0)+1),r.reference){if(!Ma(t.reference))throw new ut(Sn(`context[${n}] is invalid. Expected key '${t.key}' to be a reference.`))}else kF(e,t.resource,n,r)}function NF(e,t){const n=new Map,r=DF[e];for(let i=0;i<t.length;i++){const s=t[i].key;if(!r[s])throw new ut(Sn(`Key '${s}' not found for event '${e}'. Make sure to add only valid keys.`));PF(e,t[i],i,r[s],n)}for(const[i,s]of Object.entries(r)){if(!(s.optional||n.has(i)))throw new ut(Sn(`Missing required key '${i}' on context for '${e}' event.`));if(!s.manyAllowed&&(n.get(i)??0)>1)throw new ut(Sn(`${n.get(i)} context entries with key '${i}' found for the '${e}' event when schema only allows for 1.`))}}function QT(e,t,n,r){if(!(e&&typeof e=="string"))throw new ut(Sn("Must provide a topic."));if(!Kx[t])throw new ut(Sn(`Must provide a valid FHIRcast event name. Supported events: ${Object.keys(Kx).join(", ")}`));if(typeof n!="object")throw new ut(Sn("context must be a context object or array of context objects."));if(TS.includes(t)&&!r)throw new ut(Sn(`The '${t}' event must contain a 'context.versionId'.`));const i=Array.isArray(n)?n:[n];return NF(t,i),{timestamp:new Date().toISOString(),id:Ik(),event:{"hub.topic":e,"hub.event":t,context:i,...r?{"context.versionId":r}:{}}}}class OF extends Zm{subRequest;websocket;constructor(t){if(super(),this.subRequest=t,!t.endpoint)throw new ut(Sn("Subscription request should contain an endpoint."));if(!RS(t))throw new ut(Sn("Subscription request failed validation."));const n=new WebSocket(t.endpoint);n.addEventListener("open",()=>{this.dispatchEvent({type:"connect"}),n.addEventListener("message",r=>{const i=JSON.parse(r.data);if(i["hub.topic"])return;const s=i;s.event["hub.event"]!=="heartbeat"&&(this.dispatchEvent({type:"message",payload:s}),n.send(JSON.stringify({id:i?.id,timestamp:new Date().toISOString()})))}),n.addEventListener("close",()=>{this.dispatchEvent({type:"disconnect"})})}),this.websocket=n}disconnect(){this.websocket.close()}}function MF(e){return JSON.parse(xF(e))}function LF(e){return e.split(".").length===3}function _S(e){const[t,n,r]=e.split(".");return MF(n)}function IF(e){try{return typeof _S(e).login_id=="string"}catch{return!1}}function zF(e){try{const n=_S(e).exp;return typeof n=="number"?n*1e3:void 0}catch{return}}class $F{medplum;constructor(t){this.medplum=t}async get(t){return this.medplum.get(`keyvalue/v1/${t}`)}async set(t,n){await this.medplum.put(`keyvalue/v1/${t}`,n,tn.TEXT)}async delete(t){await this.medplum.delete(`keyvalue/v1/${t}`)}}class no{[Symbol.toStringTag]="ReadablePromise";suspender;status="pending";response;error;constructor(t){this.suspender=t.then(n=>(this.status="success",this.response=n,n),n=>{throw this.status="error",this.error=n,n})}isPending(){return this.status==="pending"}isOk(){return this.status==="success"}read(){switch(this.status){case"pending":throw this.suspender;case"error":throw this.error;default:return this.response}}then(t,n){return this.suspender.then(t,n)}catch(t){return this.suspender.catch(t)}finally(t){return this.suspender.finally(t)}}class UF{storage;prefix="";constructor(t,n=""){this.storage=t??globalThis.localStorage??new BF,this.prefix=n}makeKey(t){return this.prefix+t}clear(){this.storage===globalThis.localStorage&&this.prefix?Object.keys(this.storage).filter(t=>t.startsWith(this.prefix)).forEach(t=>{this.storage.removeItem(t)}):this.storage.clear()}getString(t){return this.storage.getItem(this.makeKey(t))??void 0}setString(t,n){n?this.storage.setItem(this.makeKey(t),n):this.storage.removeItem(this.makeKey(t))}getObject(t){const n=this.getString(t);return n?JSON.parse(n):void 0}setObject(t,n){this.setString(t,n?fo(n):void 0)}}class BF{data;constructor(){this.data=new Map}get length(){return this.data.size}clear(){this.data.clear()}getItem(t){return this.data.get(t)??null}setItem(t,n){n?this.data.set(t,n):this.data.delete(t)}removeItem(t){this.data.delete(t)}key(t){return Array.from(this.data.keys())[t]}}const Xc={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let YT=!1;function VF(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Xc.Event=globalThis.Event,Xc.ErrorEvent=class extends Event{message;error;constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Xc.CloseEvent=class extends Event{code;reason;wasClean=!0;constructor(t=1e3,n="",r){super("close",r),this.code=t,this.reason=n}}}function FF(e,t){if(!e)throw new Error(t)}function up(e){return new e.constructor(e.type,e)}const il={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let KT=!1;class fs extends Zm{_ws;_retryCount=-1;_uptimeTimeout;_connectTimeout;_shouldReconnect=!0;_connectLock=!1;_binaryType;_closeCalled=!1;_messageQueue=[];_debugLogger=console.log.bind(console);_url;_protocols;_options;constructor(t,n,r={}){YT||(VF(),YT=!0),super(),this._url=t,this._protocols=n,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._options.binaryType?this._binaryType=this._options.binaryType:this._binaryType="blob",this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return fs.CONNECTING}get OPEN(){return fs.OPEN}get CLOSING(){return fs.CLOSING}get CLOSED(){return fs.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,r)=>(typeof r=="string"?n+=r.length:r instanceof Blob?n+=r.size:n+=r.byteLength,n),0)+(this._ws?.bufferedAmount??0)}get extensions(){return this._ws?.extensions??""}get protocol(){return this._ws?.protocol??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?fs.CLOSED:fs.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}onclose=null;onerror=null;onmessage=null;onopen=null;close(t=1e3,n){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(t,n)}reconnect(t,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(t,n),this._connect())}send(t){if(this._ws?.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{const{maxEnqueuedMessages:n=il.maxEnqueuedMessages}=this._options;this._messageQueue.length<n&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){const{reconnectionDelayGrowFactor:t=il.reconnectionDelayGrowFactor,minReconnectionDelay:n=il.minReconnectionDelay,maxReconnectionDelay:r=il.maxReconnectionDelay}=this._options;let i=0;return this._retryCount>0&&(i=n*Math.pow(t,this._retryCount-1),i>r&&(i=r)),this._debug("next delay",i),i}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=il.maxRetries,connectionTimeout:n=il.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!KT&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),KT=!0);const r=this._options.WebSocket||WebSocket;this._debug("connect",{url:this._url,protocols:this._protocols}),this._ws=this._protocols?new r(this._url,this._protocols):new r(this._url),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),n)}).catch(r=>{this._connectLock=!1,this._handleError(new Xc.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Xc.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Xc.CloseEvent(t,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_handleOpen=t=>{this._debug("open event");const{minUptime:n=il.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),n),FF(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(r=>this._ws?.send(r)),this._messageQueue=[],this.onopen&&this.onopen(t),this.dispatchEvent(up(t))};_handleMessage=t=>{this._debug("message event"),this.onmessage&&this.onmessage(t),this.dispatchEvent(up(t))};_handleError=t=>{this._debug("error event",t.message),this._disconnect(void 0,t.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(t),this._debug("exec error listeners"),this.dispatchEvent(up(t)),this._connect()};_handleClose=t=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(t),this.dispatchEvent(up(t))};_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}}const HF=5e3,qF=300*1e3,GF=6e4,WF=[WebSocket.CLOSING,WebSocket.CLOSED];class Xx extends Zm{criteria;constructor(...t){super(),this.criteria=new Set(t)}getCriteria(){return this.criteria}_addCriteria(t){this.criteria.add(t)}_removeCriteria(t){this.criteria.delete(t)}}class QF{criteria;emitter;refCount;subscriptionProps;subscriptionId;token;tokenExpiry;connecting=!1;constructor(t,n){this.criteria=t,this.emitter=new Xx(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0,this.tokenExpiry=void 0}}class YF{medplum;ws;masterSubEmitter;criteriaEntries;criteriaEntriesBySubscriptionId;wsClosed;pingTimer=void 0;tokenRefreshTimer=void 0;pingIntervalMs;waitingForPong=!1;currentProfile;constructor(t,n,r){if(!(t instanceof Vk))throw new ut(Sn("First arg of constructor should be a `MedplumClient`"));let i;try{i=new URL(n).toString()}catch{throw new ut(Sn("Not a valid URL"))}const s=r?.ReconnectingWebSocket?new r.ReconnectingWebSocket(i,void 0,{debug:r?.debug,debugLogger:r?.debugLogger}):new fs(i,void 0,{debug:r?.debug,debugLogger:r?.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new Xx,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=r?.pingIntervalMs??HF,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{try{const r=JSON.parse(n.data);if(r.type==="pong"){this.waitingForPong=!1;return}const i=r,s=i?.entry?.[0]?.resource;if(s.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:i});return}if(s.type==="handshake"){const u=bs(s.subscription),f={type:"connect",payload:{subscriptionId:u}};this.masterSubEmitter?.dispatchEvent(f);const h=this.criteriaEntriesBySubscriptionId.get(u);if(!h){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}h.connecting=!1,h.emitter.dispatchEvent({...f});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:i});const c=this.criteriaEntriesBySubscriptionId.get(bs(s.subscription));if(!c){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}c.emitter.dispatchEvent({type:"message",payload:i})}catch(r){console.error(r);const i={type:"error",payload:r};this.masterSubEmitter?.dispatchEvent(i);for(const s of this.getAllCriteriaEmitters())s.dispatchEvent({...i})}}),t.addEventListener("error",()=>{const n={type:"error",payload:new ut(rU(new Error("WebSocket error")))};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n})}),t.addEventListener("close",()=>{const n={type:"close"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.tokenRefreshTimer&&(clearInterval(this.tokenRefreshTimer),this.tokenRefreshTimer=void 0),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),t.addEventListener("open",()=>{const n={type:"open"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs)),this.tokenRefreshTimer??=setInterval(()=>{this.checkTokenExpirations()},GF)}),this.medplum.addEventListener("change",()=>{const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&this.currentProfile?.id!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){const r={type:"error",payload:n};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){const{subscriptionId:n}=t;if(n){const r={type:"disconnect",payload:{subscriptionId:n}};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){let n=t?.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${$t(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),i=r?.find(u=>u.name==="token")?.valueString,s=r?.find(u=>u.name==="websocket-url")?.valueUrl,c=r?.find(u=>u.name==="expiration")?.valueDateTime;if(!i)throw new ut(Sn("Failed to get token"));if(!s)throw new ut(Sn("Failed to get URL from $get-ws-binding-token"));if(!c)throw new ut(Sn("Failed to get expiration from $get-ws-binding-token"));return[n,i,c]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const i of r.criteriaWithProps)if($i(n,i.subscriptionProps))return i}}getAllCriteriaEmitters(){const t=[];for(const n of this.criteriaEntries.values()){n.bareCriteria&&t.push(n.bareCriteria.emitter);for(const r of n.criteriaWithProps)t.push(r.emitter)}return t}addCriteriaEntry(t){const{criteria:n,subscriptionProps:r}=t;let i;this.criteriaEntries.has(n)?i=this.criteriaEntries.get(n):(i={criteriaWithProps:[]},this.criteriaEntries.set(n,i)),r?i.criteriaWithProps.push(t):i.bareCriteria=t}removeCriteriaEntry(t){const{criteria:n,subscriptionProps:r,subscriptionId:i,token:s}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(u=>{const f=u.subscriptionProps;return!$i(r,f)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),this.masterSubEmitter?._removeCriteria(n)),i&&this.criteriaEntriesBySubscriptionId.delete(i),s&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:s}}))}async subscribeToCriteria(t){this.wsClosed&&await this.reconnectIfNeeded(),!this.isReconnecting(t)&&(t.connecting=!0,await this.rebindCriteriaEntry(t))}async refreshAllSubscriptions(){this.criteriaEntriesBySubscriptionId.clear();for(const t of this.criteriaEntries.values())for(const n of[...t.bareCriteria?[t.bareCriteria]:[],...t.criteriaWithProps])n.clearAttachedSubscription(),await this.subscribeToCriteria(n)}isReconnecting(t){return!!(this.ws.readyState!==WebSocket.OPEN||t.connecting)}async rebindCriteriaEntry(t){try{const[n,r,i]=await this.getTokenForCriteria(t);t.token=r,t.tokenExpiry=new Date(i).getTime(),t.subscriptionId=n,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(We(n)),this.emitError(t,n)}}checkTokenExpirations(){const t=Date.now();for(const n of this.criteriaEntries.values())for(const r of[...n.bareCriteria?[n.bareCriteria]:[],...n.criteriaWithProps])r.tokenExpiry&&r.tokenExpiry-t<=qF&&!this.isReconnecting(r)&&this.rebindCriteriaEntry(r).catch(i=>{this.masterSubEmitter?.dispatchEvent({type:"error",payload:i})})}addCriteria(t,n){this.masterSubEmitter&&this.masterSubEmitter._addCriteria(t);const r=this.maybeGetCriteriaEntry(t,n);if(r)return r.refCount+=1,r.emitter;const i=new QF(t,n);return this.addCriteriaEntry(i),this.subscribeToCriteria(i).catch(console.error),i.emitter}removeCriteria(t,n){const r=this.maybeGetCriteriaEntry(t,n);if(!r){console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times.");return}r.refCount-=1,!(r.refCount>0)&&(this.maybeEmitDisconnect(r),this.removeCriteriaEntry(r))}getWebSocket(){return this.ws}closeWebSocket(){this.wsClosed||(this.wsClosed=!0,this.ws.close())}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new Xx(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}async reconnectIfNeeded(){WF.includes(this.getWebSocket().readyState)&&await new Promise(t=>{const n=()=>{this.getWebSocket().removeEventListener("open",n),t()};this.getWebSocket().addEventListener("open",n),this.reconnectWebSocket()})}}const Bk="5.1.2-a3e2a8a",KF=tn.FHIR_JSON+", */*; q=0.1",XF="https://api.medplum.com/",JF=1e3,ZF=6e4,eH=0,tH=3e5,nH="Binary/",XT={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Uc={ClientCredentials:"client_credentials",AuthorizationCode:"authorization_code",RefreshToken:"refresh_token",JwtBearer:"urn:ietf:params:oauth:grant-type:jwt-bearer",TokenExchange:"urn:ietf:params:oauth:grant-type:token-exchange"},rH={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},iH={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class Vk extends Zm{options;fetch;createPdfImpl;storage;requestCache;cacheTime;baseUrl;fhirBaseUrl;authorizeUrl;tokenUrl;logoutUrl;fhircastHubUrl;cdsServicesUrl;defaultHeaders;onUnauthenticated;autoBatchTime;autoBatchQueue;maxRetryTime;refreshGracePeriod;subscriptionManager;medplumServer;clientId;clientSecret;credentialsInHeader;autoBatchTimerId;accessToken;accessTokenExpires;refreshToken;refreshPromise;profilePromise;sessionDetails;currentRateLimits;basicAuth;initPromise;initComplete=!0;keyValueClient;logLevel;constructor(t){if(super(),t?.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=t?.fetch??oH(),this.storage=t?.storage??new UF(void 0,t?.storagePrefix),this.createPdfImpl=t?.createPdf,this.baseUrl=vS(t?.baseUrl??XF),this.fhirBaseUrl=Pi(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=Pi(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=Pi(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=Pi(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=Pi(this.baseUrl,t?.fhircastHubUrl??"fhircast/STU3"),this.cdsServicesUrl=Pi(this.baseUrl,t?.cdsServicesUrl??"cds-services"),this.clientId=t?.clientId??"",this.clientSecret=t?.clientSecret??"",this.credentialsInHeader=t?.authCredentialsMethod==="header",this.defaultHeaders=t?.defaultHeaders??{},this.onUnauthenticated=t?.onUnauthenticated,this.refreshGracePeriod=t?.refreshGracePeriod??tH,this.logLevel=this.initializeLogLevel(t),this.maxRetryTime=t?.maxRetryTime??2e3,this.cacheTime=t?.cacheTime??(Ro()?ZF:eH),this.cacheTime>0?this.requestCache=new cS(t?.resourceCacheSize??JF):this.requestCache=void 0,t?.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t?.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}initializeLogLevel(t){return t?.logLevel?t.logLevel:t?.verbose!==void 0&&t.verbose?"verbose":"none"}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getCdsServicesUrl(){return this.cdsServicesUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),Ro()&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),this.requestCache?.delete(t)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(t){const n=Pi(this.fhirBaseUrl,t);for(const r of this.requestCache?.keys()??Cr)(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache?.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let i;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?i=new Promise((c,u)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:u}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):i=this.request("GET",t,n);const s=new no(i);return this.setCacheEntry(t,s,n),s}post(t,n,r,i={}){return t=t.toString(),this.setRequestBody(i,n),r&&this.setRequestContentType(i,r),this.invalidateUrl(t),this.request("POST",t,i)}put(t,n,r,i={}){return t=t.toString(),this.setRequestBody(i,n),r&&this.setRequestContentType(i,r),this.invalidateUrl(t),this.request("PUT",t,i)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,tn.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,r)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){const{codeChallengeMethod:r,codeChallenge:i}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:i},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){const r=new URLSearchParams(rr.getSearch()).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){rr.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,i,s=!0){let c=i;s&&(c=await this.ensureCodeChallenge(i)),rr.assign(this.getExternalAuthRedirectUri(t,n,r,c,s))}async exchangeExternalAccessToken(t,n,r){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");const i={grant_type:Uc.TokenExchange,subject_token_type:rH.AccessToken,client_id:n,subject_token:t};return r&&(i.membership_id=r),this.fetchTokens(i)}getExternalAuthRedirectUri(t,n,r,i,s=!0){const c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",n),c.searchParams.set("redirect_uri",r),c.searchParams.set("scope",i.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(i)),s){const{codeChallenge:u,codeChallengeMethod:f}=i;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!u)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",u)}return c.toString()}fhirUrl(...t){return new URL(Pi(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=WB(n)),r}search(t,n,r){const i=this.fhirSearchUrl(t,n),s="search-"+i.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=this.getBundle(i,r);return this.setCacheEntry(s,u,r),u}searchOne(t,n,r){const i=this.fhirSearchUrl(t,n);i.searchParams.set("_count","1"),i.searchParams.sort();const s="searchOne-"+i.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=new no(this.search(t,i.searchParams,r).then(f=>f.entry?.[0]?.resource));return this.setCacheEntry(s,u,r),u}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=new no(this.search(t,n,r).then(ZT));return this.setCacheEntry(s,u,r),u}async*searchResourcePages(t,n,r){let i=this.fhirSearchUrl(t,n);for(;i;){const s=new URL(i).searchParams;s.has("_count")||s.set("_count","1000");const c=await this.search(t,s,r),u=c.link?.find(f=>f.relation==="next");if(!c.entry?.length&&!u)break;yield ZT(c),i=u?.url?new URL(u.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){const r=this.requestCache?.get(this.fhirUrl(t,n).toString())?.value;return r?.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return XT;const[r,i]=n.split("/");if(!(!r||!i))return this.getCached(r,i)}readResource(t,n,r){if(!n)throw new Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(t,n),r)}readReference(t,n){const r=t.reference;if(!r)return new no(Promise.reject(new Error("Missing reference")));if(r==="system")return new no(Promise.resolve(XT));const[i,s]=r.split("/");return!i||!s?new no(Promise.reject(new Error("Invalid reference"))):this.readResource(i,s,n)}readCanonical(t,n,r){return Array.isArray(t)?this.searchOne("",{_type:t.join(","),url:n},r):this.searchOne(t,"url="+n,r)}requestSchema(t,n){if(ok(t))return Promise.resolve();const r=t+"-requestSchema",i=this.getCacheEntry(r,void 0);if(i)return i.value;const s=new no((async()=>{const c=`{
56
+ `?(this.pos.line++,this.pos.column=0):this.pos.column++}buildToken(t,n){const r=this.markStack.pop();if(!r)throw new Error("No mark for token");return{id:t,value:n,...r}}}function EV(e){return!!(e&&(e.id==="String"||e.id==="Symbol"&&jV.includes(e.value)))}const TV=["true","false"],RV=["!=","!~","<=",">=","{}","->"];function _V(e){return new CV(e,TV,RV).tokenize()}const en={FunctionCall:0,Dot:1,Indexer:2,UnaryAdd:3,UnarySubtract:3,Multiply:4,Divide:4,Modulo:4,Add:5,Subtract:5,Ampersand:5,Is:6,As:6,Union:7,GreaterThan:8,GreaterThanOrEquals:8,LessThan:8,LessThanOrEquals:8,Equals:9,Equivalent:9,NotEquals:9,NotEquivalent:9,In:10,Contains:10,And:11,Xor:12,Or:12,Implies:13},DV={parse(e){const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+e.peek()?.value+"`");return t}},AV={parse(e,t){const n=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new wS(t,n)},precedence:en.Indexer},kV={parse(e,t){if(!(t instanceof Qd))throw new Error("Unexpected parentheses");const n=[];for(;!e.match(")");)n.push(e.consumeAndParse()),e.match(",");return new jS(t.name,n)},precedence:en.FunctionCall};function PV(e){const t=e.split(" "),n=Number.parseFloat(t[0]);let r=t[1];return r?.startsWith("'")&&r.endsWith("'")?r=r.substring(1,r.length-1):r="{"+r+"}",{value:n,unit:r}}function NV(){return new q8().registerPrefix("String",{parse:(e,t)=>new zc({type:re.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new zc({type:re.dateTime,value:Ep(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new zc({type:re.Quantity,value:PV(t.value)})}).registerPrefix("Number",{parse:(e,t)=>new zc({type:t.value.includes(".")?re.decimal:re.integer,value:Number.parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new zc({type:re.boolean,value:!0})}).registerPrefix("false",{parse:()=>new zc({type:re.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new Qd(t.value)}).registerPrefix("{}",{parse:()=>new cV}).registerPrefix("(",DV).registerInfix("[",AV).registerInfix("(",kV).prefix("+",en.UnaryAdd,(e,t)=>new uV("+",t,n=>n)).prefix("-",en.UnarySubtract,(e,t)=>new to("-",t,t,(n,r)=>-r)).infixLeft(".",en.Dot,(e,t,n)=>new Ym(e,n)).infixLeft("/",en.Divide,(e,t,n)=>new to("/",e,n,(r,i)=>r/i)).infixLeft("*",en.Multiply,(e,t,n)=>new to("*",e,n,(r,i)=>r*i)).infixLeft("+",en.Add,(e,t,n)=>new to("+",e,n,(r,i)=>r+i)).infixLeft("-",en.Subtract,(e,t,n)=>new to("-",e,n,(r,i)=>r-i)).infixLeft("|",en.Union,(e,t,n)=>new bS(e,n)).infixLeft("=",en.Equals,(e,t,n)=>new pV(e,n)).infixLeft("!=",en.NotEquals,(e,t,n)=>new mV(e,n)).infixLeft("~",en.Equivalent,(e,t,n)=>new gV(e,n)).infixLeft("!~",en.NotEquivalent,(e,t,n)=>new vV(e,n)).infixLeft("<",en.LessThan,(e,t,n)=>new to("<",e,n,(r,i)=>r<i)).infixLeft("<=",en.LessThanOrEquals,(e,t,n)=>new to("<=",e,n,(r,i)=>r<=i)).infixLeft(">",en.GreaterThan,(e,t,n)=>new to(">",e,n,(r,i)=>r>i)).infixLeft(">=",en.GreaterThanOrEquals,(e,t,n)=>new to(">=",e,n,(r,i)=>r>=i)).infixLeft("&",en.Ampersand,(e,t,n)=>new dV(e,n)).infixLeft("and",en.And,(e,t,n)=>new yV(e,n)).infixLeft("as",en.As,(e,t,n)=>new Hp(e,n)).infixLeft("contains",en.Contains,(e,t,n)=>new fV(e,n)).infixLeft("div",en.Divide,(e,t,n)=>new to("div",e,n,(r,i)=>Math.trunc(r/i))).infixLeft("in",en.In,(e,t,n)=>new hV(e,n)).infixLeft("is",en.Is,(e,t,n)=>new SS(e,n)).infixLeft("mod",en.Modulo,(e,t,n)=>new to("mod",e,n,(r,i)=>r%i)).infixLeft("or",en.Or,(e,t,n)=>new xV(e,n)).infixLeft("xor",en.Xor,(e,t,n)=>new bV(e,n)).infixLeft("implies",en.Implies,(e,t,n)=>new SV(e,n))}const OV=NV();function CS(e){return new xS(e,OV.construct(_V(e)).consumeAndParse())}function MV(e,t){const n=Array.isArray(t)?t:[t];for(let r=0;r<n.length;r++){const i=n[r];typeof i=="object"&&"type"in i&&"value"in i||(n[r]=mi(n[r]))}return js(e,n).map(r=>r.value)}function js(e,t,n={},r=void 0){let i;if(typeof e=="string"){const s=r?.get(e);i=s??CS(e),r&&!s&&r.set(e,i)}else i=e;return i.eval({variables:n},t).map(s=>{const c={type:s.type,value:s.value?.valueOf()};return"path"in s&&(c.path=s.path),c})}function LV(e){const t=[];for(const n of e){const r=mk(n.value);r&&t.push(r)}return t}function IV(e){const t=new Set;for(const n of e){const r=El(n);r&&t.add(r)}return Array.from(t)}function zV(e){const t=new Set;for(const n of e){const{value:r}=n;r&&(xk(r)?t.add(r):Ma(r)?t.add(r.reference):vk(r)?t.add($t(r)):typeof r.identifier=="object"&&t.add(`identifier:${r.identifier.system}|${r.identifier.value}`))}return Array.from(t)}function $V(e,t={}){const n=[];for(const r of e)UV(t,n,r);return n}function UV(e,t,n){const{type:r,value:i}=n;switch(r){case re.Identifier:BV(t,e,i);break;case re.CodeableConcept:VV(t,e,i);break;case re.Coding:kk(t,e,i);break;case re.ContactPoint:FV(t,e,i);break;default:Rl(t,e,void 0,i?.toString())}}function BV(e,t,n){n?.type?.text&&Rl(e,t,t.textSearchSystem,n.type.text),Rl(e,t,n?.system,n?.value)}function VV(e,t,n){n?.text&&Rl(e,t,t.textSearchSystem,n.text);for(const r of n?.coding??Cr)kk(e,t,r)}function kk(e,t,n){n&&(n.display&&Rl(e,t,t.textSearchSystem,n.display),Rl(e,t,n.system,n.code))}function FV(e,t,n){n&&Rl(e,t,n.system,n.value?.toLocaleLowerCase())}function Rl(e,t,n,r){(n||r)&&!e.some(i=>i.system===n&&i.value===r)&&e.push({system:n,value:r&&t.caseInsensitive?r.toLocaleLowerCase():r})}const Km=20,fe={EQUALS:"eq",NOT_EQUALS:"ne",GREATER_THAN:"gt",LESS_THAN:"lt",GREATER_THAN_OR_EQUALS:"ge",LESS_THAN_OR_EQUALS:"le",STARTS_AFTER:"sa",ENDS_BEFORE:"eb",APPROXIMATELY:"ap",CONTAINS:"contains",STARTS_WITH:"sw",EXACT:"exact",TEXT:"text",NOT:"not",ABOVE:"above",BELOW:"below",IN:"in",NOT_IN:"not-in",OF_TYPE:"of-type",MISSING:"missing",PRESENT:"present",IDENTIFIER:"identifier",ITERATE:"iterate"},Pk={contains:fe.CONTAINS,exact:fe.EXACT,above:fe.ABOVE,below:fe.BELOW,text:fe.TEXT,not:fe.NOT,in:fe.IN,"not-in":fe.NOT_IN,"of-type":fe.OF_TYPE,missing:fe.MISSING,identifier:fe.IDENTIFIER,iterate:fe.ITERATE},ES={eq:fe.EQUALS,ne:fe.NOT_EQUALS,lt:fe.LESS_THAN,le:fe.LESS_THAN_OR_EQUALS,gt:fe.GREATER_THAN,ge:fe.GREATER_THAN_OR_EQUALS,sa:fe.STARTS_AFTER,eb:fe.ENDS_BEFORE,ap:fe.APPROXIMATELY,sw:fe.STARTS_WITH};function Nk(e,t){if(!e)throw new Error("Invalid search URL");let n="",r;if(typeof e=="string")if(e.includes("?")){const[c,u]=e.split("?");n=c,r=new URLSearchParams(u)}else n=e;else typeof e=="object"&&(n=e.pathname,r=e.searchParams);let i;n.includes("/")?i=n.split("/").filter(Boolean).pop():i=n;const s=[];return r&&s.push(...r.entries()),HV(i,s)}function HV(e,t){const n={resourceType:e};for(const[r,i]of t)qV(n,r,i);return n}function qV(e,t,n){let r,i;const s=t.indexOf(":");if(s>=0?(r=t.substring(0,s),i=t.substring(s+1)):(r=t,i=""),r!=="_"){if(r==="_has"||t.includes(".")){e.filters=ul(e.filters,{code:t,operator:fe.EQUALS,value:n});return}switch(r){case"_sort":GV(e,n);break;case"_cursor":e.cursor=n;break;case"_count":e.count=Number.parseInt(n,10);break;case"_offset":e.offset=Number.parseInt(n,10);break;case"_total":e.total=n;break;case"_summary":n==="count"?(e.total="accurate",e.count=0):(n==="true"||n==="data"||n==="text")&&(e.summary=n);break;case"_include":{const c=VT(n);i==="iterate"&&(c.modifier=fe.ITERATE),e.include=ul(e.include,c);break}case"_revinclude":{const c=VT(n);i==="iterate"&&(c.modifier=fe.ITERATE),e.revInclude=ul(e.revInclude,c);break}case"_fields":case"_elements":e.fields=n.split(",");break;case"_type":e.types=n.split(",");break;case"_format":e.format=n;break;case"_pretty":e.pretty=n==="true";break;default:{const c=$o.types[e.resourceType]?.searchParams?.[r];c?e.filters=ul(e.filters,QV(c,i,n)):e.filters=ul(e.filters,YV(r,i,n))}}}}function GV(e,t){for(const n of t.split(",")){let r,i=!1;n.startsWith("-")?(r=n.substring(1),i=!0):r=n,e.sortRules||(e.sortRules=[]),e.sortRules.push({code:r,descending:i})}}const WV=[fe.MISSING,fe.PRESENT];function QV(e,t,n){if(WV.includes(t))return{code:e.code,operator:t,value:n};switch(e.type){case"number":case"date":case"quantity":{const{operator:r,value:i}=KV(n,t||fe.EQUALS);if(!FT(e,i))throw new ut(Oo(`Invalid format for ${e.type} search parameter: ${i}`));return{code:e.code,operator:r,value:i}}case"reference":case"string":case"token":case"uri":if(!FT(e,n))throw new ut(Oo(`Invalid format for ${e.type} search parameter: ${n}`));return{code:e.code,operator:XV(t),value:n};default:throw new Error("Unrecognized search parameter type: "+e.type)}}function YV(e,t,n){let r=fe.EQUALS;if(t)r=t;else if(n.length>=2){const i=n.substring(0,2);i in ES&&(n.length===2||n.at(2)?.match(/\d/))&&(r=i,n=n.substring(i.length))}return{code:e,operator:r,value:n}}function KV(e,t){const n=e.substring(0,2),r=ES[n];return r?{operator:r,value:e.substring(2)}:{operator:t,value:e}}function XV(e){return Pk[e]??fe.EQUALS}function VT(e){const t=e.split(":");if(t.includes("*"))throw new ut(Oo("'*' is not supported as a value for search inclusion parameters"));if(t.length===1)throw new ut(Oo(`Invalid include value '${e}': must be of the form ResourceType:search-parameter`));if(t.length===2)return{resourceType:t[0],searchParam:t[1]};if(t.length===3)return{resourceType:t[0],searchParam:t[1],targetType:t[2]};throw new ut(Oo(`Invalid include value '${e}'`))}function FT(e,t){return e.type==="date"?qd(t):!0}function vs(e){const t=[];e.fields&&t.push("_fields="+e.fields.join(","));for(const n of e.filters??Cr)t.push(JV(n));e.sortRules&&e.sortRules.length>0&&t.push(ZV(e.sortRules)),e.cursor!==void 0&&t.push("_cursor="+encodeURIComponent(e.cursor)),e.offset!==void 0&&e.offset!==0&&t.push("_offset="+e.offset),e.count!==void 0&&t.push("_count="+e.count),e.total!==void 0&&t.push("_total="+e.total),e.types&&e.types.length>0&&t.push("_type="+e.types.join(","));for(const n of e.include??Cr)t.push(HT("_include",n));for(const n of e.revInclude??Cr)t.push(HT("_revinclude",n));return t.length===0?"":(au(t),"?"+t.join("&"))}function JV(e){const t=e.operator in Pk?":"+e.operator:"",n=e.operator!==fe.EQUALS&&e.operator in ES?e.operator:"";return`${e.code}${t}=${n}${encodeURIComponent(e.value)}`}function ZV(e){return"_sort="+e.map(t=>t.descending?"-"+t.code:t.code).join(",")}function HT(e,t){return e+(t.modifier?":"+t.modifier:"")+"="+t.resourceType+":"+t.searchParam+(t.targetType?":"+t.targetType:"")}function Xm(e){const t=[];let n="",r=!1;for(const i of e)r?(n+=i,r=!1):i==="\\"?r=!0:i===","?(t.push(n),n=""):n+=i;return t.push(n),t}function eF(e,t){if(t.resourceType!==e.resourceType)return!1;for(const n of t.filters??Cr)if(!nF(e,t,n))return!1;return!0}const tF=new cS(1e3);function nF(e,t,n){const r=$o.types[t.resourceType]?.searchParams?.[n.code];if(!r)return!1;const i=js(r.expression,[mi(e)],void 0,tF);if(n.operator===fe.MISSING||n.operator===fe.PRESENT)return rF(i,n);switch(r.type){case"reference":return iF(i,n);case"string":case"uri":return sF(i,n);case"token":return oF(i,n);case"date":return cF(i,n);default:return!1}}function rF(e,t){const n=e.length>0;return(t.operator===fe.MISSING&&t.value==="false"||t.operator===fe.PRESENT&&t.value==="true")===n}function iF(e,t){const n=Jm(t.operator);if(t.value===""&&e.length===0)return t.operator===fe.EQUALS;const r=zV(e);for(const i of Xm(t.value)){let s=r.includes(i);if(!s&&t.code==="_compartment"&&(s=r.some(c=>c?.endsWith("/"+i))),s)return!n}return n}function oF(e,t){const n=$V(e),r=Xm(t.value),i=Jm(t.operator);for(const s of n)for(const c of r)if(aF(s,c))return!i;return i}function aF(e,t){if(t.includes("|")){const[n,r]=t.split("|").map(i=>i.toLowerCase());return!n&&!r?!1:n?e.system?.toLowerCase()===n&&(!r||e.value?.toLowerCase()===r):!e.system&&e.value?.toLowerCase()===r}return e.value?.toLowerCase()===t.toLowerCase()}function sF(e,t){const n=IV(e),r=Xm(t.value),i=Jm(t.operator);for(const s of n)for(const c of r)if(lF(s,c))return!i;return i}function lF(e,t){return e.toLowerCase().includes(t.toLowerCase())}function cF(e,t){const n=LV(e),r=Xm(t.value),i=Jm(t.operator);for(const s of n)for(const c of r)if(uF(s,t.operator,c))return!i;return i}function uF(e,t,n){if(!e)return!1;const r=mk(n);if(!r)return!1;const i=e.start??"0000",s=e.end??"9999",c=r.start,u=r.end;switch(t){case fe.APPROXIMATELY:case fe.EQUALS:case fe.NOT_EQUALS:return i<u&&s>c;case fe.LESS_THAN:return i<c;case fe.GREATER_THAN:return s>u;case fe.LESS_THAN_OR_EQUALS:return i<=u;case fe.GREATER_THAN_OR_EQUALS:return s>=c;case fe.STARTS_AFTER:return i>u;case fe.ENDS_BEFORE:return s<c;default:return!1}}function Jm(e){return e===fe.NOT_EQUALS||e===fe.NOT}const dF={resourceType:"*"},fF=["DomainConfiguration","JsonWebKey","Login"],hF=["UserSecurityRequest","Project","ProjectMembership","User"],vl={READ:"read",VREAD:"vread",UPDATE:"update",HISTORY:"history",SEARCH:"search"},pF=[vl.READ,vl.VREAD,vl.HISTORY,vl.SEARCH];function mF(e,t){return fF.includes(t)?!1:gF(e,vl.UPDATE,t)}function gF(e,t,n){return!!e.resource?.some(r=>Mk(r,n,t))}function Ok(e,t,n){return n?n.resource?.find(r=>vF(e,t,r)):dF}function vF(e,t,n){const r=e.resourceType;return Mk(n,r,t)?r==="Binary"?!0:!(n.compartment&&!e.meta?.compartment?.some(i=>i.reference===n.compartment?.reference)||n.criteria&&!eF(e,Nk(n.criteria))):!1}function Mk(e,t,n){return e.resourceType!==t&&(e.resourceType!=="*"||hF.includes(t))?!1:e.interaction?e.interaction.includes(n):!e.readonly||pF.includes(n)}function Ro(){return typeof window<"u"}function Lk(){return typeof Buffer<"u"?Buffer:void 0}const rr={assign(e){Ro()&&globalThis.location.assign(e)},reload(){Ro()&&globalThis.location.reload()},getSearch(){return Ro()?globalThis.location.search:""},getPathname(){return Ro()?globalThis.location.pathname:""},getLocation(){return Ro()?globalThis.location.toString():""},getOrigin(){return Ro()?globalThis.location.protocol+"//"+globalThis.location.host+"/":""}};function yF(e){if(Ro()){const n=window.atob(e),r=Uint8Array.from(n,i=>i.codePointAt(0));return new window.TextDecoder().decode(r)}const t=Lk();if(t)return t.from(e,"base64").toString("utf-8");throw new Error("Unable to decode base64")}function qT(e){if(Ro()){const n=new window.TextEncoder().encode(e),r=String.fromCodePoint.apply(null,n);return window.btoa(r)}const t=Lk();if(t)return t.from(e,"utf8").toString("base64");throw new Error("Unable to encode base64")}function xF(e){e=e.padEnd(e.length+(4-e.length%4)%4,"=");const t=e.replaceAll("-","+").replaceAll("_","/");return yF(t)}function GT(){const e=new Uint32Array(28);return crypto.getRandomValues(e),UB(e.buffer)}async function bF(e){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))}function Ik(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replaceAll(/[xy]/g,e=>{const t=Math.trunc(Math.random()*16);return(e==="x"?t:t&3|8).toString(16)})}function zk(e){const t={};e=gi(e);for(const i of e.entry??Cr){const s=i.resource;if(!s)continue;s.meta!==void 0&&(delete s.meta.author,delete s.meta.compartment,delete s.meta.lastUpdated,delete s.meta.project,delete s.meta.versionId,Object.keys(s.meta).length===0&&delete s.meta);const c=s?.id;c&&(t[c]=Ik(),i.fullUrl="urn:uuid:"+t[c],delete i.resource?.id)}const n=e.entry,r=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:n?.map(i=>({fullUrl:i.fullUrl,request:{method:"POST",url:i.resource?.resourceType},resource:i.resource}))},(i,s)=>SF(i,s,t),2);return jF(JSON.parse(r))}function SF(e,t,n){if(e==="reference"&&typeof t=="string"){let r;if(t.includes("/")?r=t.split("/")[1]:t.startsWith("urn:uuid:")?r=t.slice(9):t.startsWith("#")&&(r=t.slice(1)),r){const i=n[r];if(i)return"urn:uuid:"+i}}return t}function jF(e){const t=CF(e),{sorted:n,cycles:r}=wF(t),i={},s=[];for(const u of e.entry??Cr)u.fullUrl?i[u.fullUrl]=u:s.push(u);const c=n.map(u=>i[u]);for(const u of r)for(const f of u){const h=i[f],m={...h,request:{...h.request,method:"PUT"}};c.push(m)}return c.push(...s),{...e,entry:c}}const $c={NotVisited:"NotVisited",Visiting:"Visiting",Visited:"Visited"};function wF(e){const t=[],n={},r=[];for(const s of Object.keys(e))n[s]=$c.NotVisited;function i(s,c){if(n[s]===$c.Visited)return!0;if(n[s]===$c.Visiting){const f=c.lastIndexOf(s);return f!==-1&&r.push(c.slice(f)),!0}n[s]=$c.Visiting,c.push(s);let u=!1;for(const f of e[s])i(f,c)||(u=!0);return n[s]=$c.Visited,c.pop(),t.unshift(s),!u}for(const s in e)n[s]===$c.NotVisited&&i(s,[]);return{sorted:t,cycles:r}}function $k(e,t){for(const n in e)if(e[n]&&typeof e[n]=="object"){const r=e[n];if(Ma(r)){const i=r.reference;i.startsWith("urn:uuid:")&&t(i)}else $k(r,t)}}function CF(e){const t={};for(const n of e.entry??Cr)n.fullUrl&&(t[n.fullUrl]=[]);for(const n of e.entry??Cr){const r=n.fullUrl;n.resource&&$k(n.resource,i=>{t[i]&&t[i].push(r)})}return t}const tn={CSS:"text/css",DICOM:"application/dicom",FAVICON:"image/vnd.microsoft.icon",FHIR_JSON:"application/fhir+json",FORM_URL_ENCODED:"application/x-www-form-urlencoded",HL7_V2:"x-application/hl7-v2+er7",HTML:"text/html",JAVASCRIPT:"text/javascript",JSON:"application/json",JSON_PATCH:"application/json-patch+json",JWT:"application/jwt",MULTIPART_FORM_DATA:"multipart/form-data",PNG:"image/png",SCIM_JSON:"application/scim+json",SVG:"image/svg+xml",TEXT:"text/plain",TYPESCRIPT:"text/typescript",PING:"x-application/ping",XML:"text/xml",CDA_XML:"application/cda+xml",OCTET_STREAM:"application/octet-stream"};let EF=class{listeners;constructor(){this.listeners={}}addEventListener(t,n){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(n)}removeEventListener(t,n){const r=this.listeners[t];if(r){for(let i=0;i<r.length;i++)if(r[i]===n){r.splice(i,1);return}}}dispatchEvent(t){const n=this.listeners[t.type];for(const r of n??Cr)r.call(this,t);return!t.defaultPrevented}removeAllListeners(){this.listeners={}}listenerCount(t){return this.listeners[t]?.length??0}};class Zm{emitter=new EF;dispatchEvent(t){this.emitter.dispatchEvent(t)}addEventListener(t,n){this.emitter.addEventListener(t,n)}removeEventListener(t,n){this.emitter.removeEventListener(t,n)}removeAllListeners(){this.emitter.removeAllListeners()}listenerCount(t){return this.emitter.listenerCount(t)}}const Kx={"Patient-open":"Patient-open","Patient-close":"Patient-close","ImagingStudy-open":"ImagingStudy-open","ImagingStudy-close":"ImagingStudy-close","Encounter-open":"Encounter-open","Encounter-close":"Encounter-close","DiagnosticReport-open":"DiagnosticReport-open","DiagnosticReport-close":"DiagnosticReport-close","DiagnosticReport-select":"DiagnosticReport-select","DiagnosticReport-update":"DiagnosticReport-update",syncerror:"syncerror"},TF=["Patient","Encounter","ImagingStudy","DiagnosticReport","OperationOutcome","Bundle"],TS=["DiagnosticReport-update"];function RF(e){return TS.includes(e)}function _F(e){if(TS.includes(e))throw new ut(Sn(`'context.version' is required for '${e}'.`))}const DF={"Patient-open":{patient:{resourceType:"Patient"},encounter:{resourceType:"Encounter",optional:!0}},"Patient-close":{patient:{resourceType:"Patient"},encounter:{resourceType:"Encounter",optional:!0}},"ImagingStudy-open":{study:{resourceType:"ImagingStudy"},encounter:{resourceType:"Encounter",optional:!0},patient:{resourceType:"Patient",optional:!0}},"ImagingStudy-close":{study:{resourceType:"ImagingStudy"},encounter:{resourceType:"Encounter",optional:!0},patient:{resourceType:"Patient",optional:!0}},"Encounter-open":{encounter:{resourceType:"Encounter"},patient:{resourceType:"Patient"}},"Encounter-close":{encounter:{resourceType:"Encounter"},patient:{resourceType:"Patient"}},"DiagnosticReport-open":{report:{resourceType:"DiagnosticReport"},encounter:{resourceType:"Encounter",optional:!0},study:{resourceType:"ImagingStudy",optional:!0,manyAllowed:!0},patient:{resourceType:"Patient"}},"DiagnosticReport-close":{report:{resourceType:"DiagnosticReport"},encounter:{resourceType:"Encounter",optional:!0},study:{resourceType:"ImagingStudy",optional:!0,manyAllowed:!0},patient:{resourceType:"Patient"}},"DiagnosticReport-select":{report:{resourceType:"DiagnosticReport",reference:!0},patient:{resourceType:"Patient",optional:!0,reference:!0},select:{resourceType:"*",reference:!0,manyAllowed:!0}},"DiagnosticReport-update":{report:{resourceType:"DiagnosticReport",reference:!0},patient:{resourceType:"Patient",optional:!0,reference:!0},updates:{resourceType:"Bundle"}},syncerror:{operationoutcome:{resourceType:"OperationOutcome"}}};function AF(e){return TF.includes(e)}function Uk(e){return!!e.endpoint}function WT(e){if(!RS(e))throw new ut(Sn("subscriptionRequest must be an object conforming to SubscriptionRequest type."));const{channelType:t,mode:n,topic:r,events:i}=e,s={"hub.channel.type":t,"hub.mode":n,"hub.topic":r,"hub.events":i.join(",")};return Uk(e)&&(s.endpoint=e.endpoint),new URLSearchParams(s).toString()}function RS(e){if(typeof e!="object")return!1;const{channelType:t,mode:n,topic:r,events:i}=e;if(!(t&&n&&r&&i)||typeof r!="string"||typeof i!="object"||!Array.isArray(i)||i.length<1||t!=="websocket"||n!=="subscribe"&&n!=="unsubscribe")return!1;for(const s of i)if(!Kx[s])return!1;return!(Uk(e)&&!(typeof e.endpoint=="string"&&e.endpoint.startsWith("ws")))}function kF(e,t,n,r){if(typeof t!="object")throw new ut(Sn(`context[${n}] is invalid. Context must contain a single valid FHIR resource! Resource is not an object.`));if(!(t.id&&typeof t.id=="string"))throw new ut(Sn(`context[${n}] is invalid. Resource must contain a valid string ID.`));if(!t.resourceType)throw new ut(Sn(`context[${n}] is invalid. Resource must contain a resource type. No resource type found.`));const i=r.resourceType;if(i!=="*"){if(!AF(t.resourceType))throw new ut(Sn(`context[${n}] is invalid. Resource must contain a valid FHIRcast resource type. Resource type is not a known resource type.`));if(i&&t.resourceType!==i)throw new ut(Sn(`context[${n}] is invalid. context[${n}] for the '${e}' event should contain resource of type ${i}.`))}}function PF(e,t,n,r,i){if(i.set(t.key,(i.get(t.key)??0)+1),r.reference){if(!Ma(t.reference))throw new ut(Sn(`context[${n}] is invalid. Expected key '${t.key}' to be a reference.`))}else kF(e,t.resource,n,r)}function NF(e,t){const n=new Map,r=DF[e];for(let i=0;i<t.length;i++){const s=t[i].key;if(!r[s])throw new ut(Sn(`Key '${s}' not found for event '${e}'. Make sure to add only valid keys.`));PF(e,t[i],i,r[s],n)}for(const[i,s]of Object.entries(r)){if(!(s.optional||n.has(i)))throw new ut(Sn(`Missing required key '${i}' on context for '${e}' event.`));if(!s.manyAllowed&&(n.get(i)??0)>1)throw new ut(Sn(`${n.get(i)} context entries with key '${i}' found for the '${e}' event when schema only allows for 1.`))}}function QT(e,t,n,r){if(!(e&&typeof e=="string"))throw new ut(Sn("Must provide a topic."));if(!Kx[t])throw new ut(Sn(`Must provide a valid FHIRcast event name. Supported events: ${Object.keys(Kx).join(", ")}`));if(typeof n!="object")throw new ut(Sn("context must be a context object or array of context objects."));if(TS.includes(t)&&!r)throw new ut(Sn(`The '${t}' event must contain a 'context.versionId'.`));const i=Array.isArray(n)?n:[n];return NF(t,i),{timestamp:new Date().toISOString(),id:Ik(),event:{"hub.topic":e,"hub.event":t,context:i,...r?{"context.versionId":r}:{}}}}class OF extends Zm{subRequest;websocket;constructor(t){if(super(),this.subRequest=t,!t.endpoint)throw new ut(Sn("Subscription request should contain an endpoint."));if(!RS(t))throw new ut(Sn("Subscription request failed validation."));const n=new WebSocket(t.endpoint);n.addEventListener("open",()=>{this.dispatchEvent({type:"connect"}),n.addEventListener("message",r=>{const i=JSON.parse(r.data);if(i["hub.topic"])return;const s=i;s.event["hub.event"]!=="heartbeat"&&(this.dispatchEvent({type:"message",payload:s}),n.send(JSON.stringify({id:i?.id,timestamp:new Date().toISOString()})))}),n.addEventListener("close",()=>{this.dispatchEvent({type:"disconnect"})})}),this.websocket=n}disconnect(){this.websocket.close()}}function MF(e){return JSON.parse(xF(e))}function LF(e){return e.split(".").length===3}function _S(e){const[t,n,r]=e.split(".");return MF(n)}function IF(e){try{return typeof _S(e).login_id=="string"}catch{return!1}}function zF(e){try{const n=_S(e).exp;return typeof n=="number"?n*1e3:void 0}catch{return}}class $F{medplum;constructor(t){this.medplum=t}async get(t){return this.medplum.get(`keyvalue/v1/${t}`)}async set(t,n){await this.medplum.put(`keyvalue/v1/${t}`,n,tn.TEXT)}async delete(t){await this.medplum.delete(`keyvalue/v1/${t}`)}}class no{[Symbol.toStringTag]="ReadablePromise";suspender;status="pending";response;error;constructor(t){this.suspender=t.then(n=>(this.status="success",this.response=n,n),n=>{throw this.status="error",this.error=n,n})}isPending(){return this.status==="pending"}isOk(){return this.status==="success"}read(){switch(this.status){case"pending":throw this.suspender;case"error":throw this.error;default:return this.response}}then(t,n){return this.suspender.then(t,n)}catch(t){return this.suspender.catch(t)}finally(t){return this.suspender.finally(t)}}class UF{storage;prefix="";constructor(t,n=""){this.storage=t??globalThis.localStorage??new BF,this.prefix=n}makeKey(t){return this.prefix+t}clear(){this.storage===globalThis.localStorage&&this.prefix?Object.keys(this.storage).filter(t=>t.startsWith(this.prefix)).forEach(t=>{this.storage.removeItem(t)}):this.storage.clear()}getString(t){return this.storage.getItem(this.makeKey(t))??void 0}setString(t,n){n?this.storage.setItem(this.makeKey(t),n):this.storage.removeItem(this.makeKey(t))}getObject(t){const n=this.getString(t);return n?JSON.parse(n):void 0}setObject(t,n){this.setString(t,n?fo(n):void 0)}}class BF{data;constructor(){this.data=new Map}get length(){return this.data.size}clear(){this.data.clear()}getItem(t){return this.data.get(t)??null}setItem(t,n){n?this.data.set(t,n):this.data.delete(t)}removeItem(t){this.data.delete(t)}key(t){return Array.from(this.data.keys())[t]}}const Xc={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let YT=!1;function VF(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Xc.Event=globalThis.Event,Xc.ErrorEvent=class extends Event{message;error;constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Xc.CloseEvent=class extends Event{code;reason;wasClean=!0;constructor(t=1e3,n="",r){super("close",r),this.code=t,this.reason=n}}}function FF(e,t){if(!e)throw new Error(t)}function up(e){return new e.constructor(e.type,e)}const il={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let KT=!1;class fs extends Zm{_ws;_retryCount=-1;_uptimeTimeout;_connectTimeout;_shouldReconnect=!0;_connectLock=!1;_binaryType;_closeCalled=!1;_messageQueue=[];_debugLogger=console.log.bind(console);_url;_protocols;_options;constructor(t,n,r={}){YT||(VF(),YT=!0),super(),this._url=t,this._protocols=n,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._options.binaryType?this._binaryType=this._options.binaryType:this._binaryType="blob",this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return fs.CONNECTING}get OPEN(){return fs.OPEN}get CLOSING(){return fs.CLOSING}get CLOSED(){return fs.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,r)=>(typeof r=="string"?n+=r.length:r instanceof Blob?n+=r.size:n+=r.byteLength,n),0)+(this._ws?.bufferedAmount??0)}get extensions(){return this._ws?.extensions??""}get protocol(){return this._ws?.protocol??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?fs.CLOSED:fs.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}onclose=null;onerror=null;onmessage=null;onopen=null;close(t=1e3,n){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(t,n)}reconnect(t,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(t,n),this._connect())}send(t){if(this._ws?.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{const{maxEnqueuedMessages:n=il.maxEnqueuedMessages}=this._options;this._messageQueue.length<n&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){const{reconnectionDelayGrowFactor:t=il.reconnectionDelayGrowFactor,minReconnectionDelay:n=il.minReconnectionDelay,maxReconnectionDelay:r=il.maxReconnectionDelay}=this._options;let i=0;return this._retryCount>0&&(i=n*Math.pow(t,this._retryCount-1),i>r&&(i=r)),this._debug("next delay",i),i}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=il.maxRetries,connectionTimeout:n=il.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!KT&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),KT=!0);const r=this._options.WebSocket||WebSocket;this._debug("connect",{url:this._url,protocols:this._protocols}),this._ws=this._protocols?new r(this._url,this._protocols):new r(this._url),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),n)}).catch(r=>{this._connectLock=!1,this._handleError(new Xc.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Xc.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Xc.CloseEvent(t,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_handleOpen=t=>{this._debug("open event");const{minUptime:n=il.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),n),FF(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(r=>this._ws?.send(r)),this._messageQueue=[],this.onopen&&this.onopen(t),this.dispatchEvent(up(t))};_handleMessage=t=>{this._debug("message event"),this.onmessage&&this.onmessage(t),this.dispatchEvent(up(t))};_handleError=t=>{this._debug("error event",t.message),this._disconnect(void 0,t.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(t),this._debug("exec error listeners"),this.dispatchEvent(up(t)),this._connect()};_handleClose=t=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(t),this.dispatchEvent(up(t))};_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}}const HF=5e3,qF=300*1e3,GF=6e4,WF=[WebSocket.CLOSING,WebSocket.CLOSED];class Xx extends Zm{criteria;constructor(...t){super(),this.criteria=new Set(t)}getCriteria(){return this.criteria}_addCriteria(t){this.criteria.add(t)}_removeCriteria(t){this.criteria.delete(t)}}class QF{criteria;emitter;refCount;subscriptionProps;subscriptionId;token;tokenExpiry;connecting=!1;constructor(t,n){this.criteria=t,this.emitter=new Xx(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0,this.tokenExpiry=void 0}}class YF{medplum;ws;masterSubEmitter;criteriaEntries;criteriaEntriesBySubscriptionId;wsClosed;pingTimer=void 0;tokenRefreshTimer=void 0;pingIntervalMs;waitingForPong=!1;currentProfile;constructor(t,n,r){if(!(t instanceof Vk))throw new ut(Sn("First arg of constructor should be a `MedplumClient`"));let i;try{i=new URL(n).toString()}catch{throw new ut(Sn("Not a valid URL"))}const s=r?.ReconnectingWebSocket?new r.ReconnectingWebSocket(i,void 0,{debug:r?.debug,debugLogger:r?.debugLogger}):new fs(i,void 0,{debug:r?.debug,debugLogger:r?.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new Xx,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=r?.pingIntervalMs??HF,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{try{const r=JSON.parse(n.data);if(r.type==="pong"){this.waitingForPong=!1;return}const i=r,s=i?.entry?.[0]?.resource;if(s.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:i});return}if(s.type==="handshake"){const u=bs(s.subscription),f={type:"connect",payload:{subscriptionId:u}};this.masterSubEmitter?.dispatchEvent(f);const h=this.criteriaEntriesBySubscriptionId.get(u);if(!h){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}h.connecting=!1,h.emitter.dispatchEvent({...f});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:i});const c=this.criteriaEntriesBySubscriptionId.get(bs(s.subscription));if(!c){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}c.emitter.dispatchEvent({type:"message",payload:i})}catch(r){console.error(r);const i={type:"error",payload:r};this.masterSubEmitter?.dispatchEvent(i);for(const s of this.getAllCriteriaEmitters())s.dispatchEvent({...i})}}),t.addEventListener("error",()=>{const n={type:"error",payload:new ut(rU(new Error("WebSocket error")))};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n})}),t.addEventListener("close",()=>{const n={type:"close"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.tokenRefreshTimer&&(clearInterval(this.tokenRefreshTimer),this.tokenRefreshTimer=void 0),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),t.addEventListener("open",()=>{const n={type:"open"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs)),this.tokenRefreshTimer??=setInterval(()=>{this.checkTokenExpirations()},GF)}),this.medplum.addEventListener("change",()=>{const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&this.currentProfile?.id!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){const r={type:"error",payload:n};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){const{subscriptionId:n}=t;if(n){const r={type:"disconnect",payload:{subscriptionId:n}};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){let n=t?.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${$t(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),i=r?.find(u=>u.name==="token")?.valueString,s=r?.find(u=>u.name==="websocket-url")?.valueUrl,c=r?.find(u=>u.name==="expiration")?.valueDateTime;if(!i)throw new ut(Sn("Failed to get token"));if(!s)throw new ut(Sn("Failed to get URL from $get-ws-binding-token"));if(!c)throw new ut(Sn("Failed to get expiration from $get-ws-binding-token"));return[n,i,c]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const i of r.criteriaWithProps)if($i(n,i.subscriptionProps))return i}}getAllCriteriaEmitters(){const t=[];for(const n of this.criteriaEntries.values()){n.bareCriteria&&t.push(n.bareCriteria.emitter);for(const r of n.criteriaWithProps)t.push(r.emitter)}return t}addCriteriaEntry(t){const{criteria:n,subscriptionProps:r}=t;let i;this.criteriaEntries.has(n)?i=this.criteriaEntries.get(n):(i={criteriaWithProps:[]},this.criteriaEntries.set(n,i)),r?i.criteriaWithProps.push(t):i.bareCriteria=t}removeCriteriaEntry(t){const{criteria:n,subscriptionProps:r,subscriptionId:i,token:s}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(u=>{const f=u.subscriptionProps;return!$i(r,f)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),this.masterSubEmitter?._removeCriteria(n)),i&&this.criteriaEntriesBySubscriptionId.delete(i),s&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:s}}))}async subscribeToCriteria(t){this.wsClosed&&await this.reconnectIfNeeded(),!this.isReconnecting(t)&&(t.connecting=!0,await this.rebindCriteriaEntry(t))}async refreshAllSubscriptions(){this.criteriaEntriesBySubscriptionId.clear();for(const t of this.criteriaEntries.values())for(const n of[...t.bareCriteria?[t.bareCriteria]:[],...t.criteriaWithProps])n.clearAttachedSubscription(),await this.subscribeToCriteria(n)}isReconnecting(t){return!!(this.ws.readyState!==WebSocket.OPEN||t.connecting)}async rebindCriteriaEntry(t){try{const[n,r,i]=await this.getTokenForCriteria(t);t.token=r,t.tokenExpiry=new Date(i).getTime(),t.subscriptionId=n,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(We(n)),this.emitError(t,n)}}checkTokenExpirations(){const t=Date.now();for(const n of this.criteriaEntries.values())for(const r of[...n.bareCriteria?[n.bareCriteria]:[],...n.criteriaWithProps])r.tokenExpiry&&r.tokenExpiry-t<=qF&&!this.isReconnecting(r)&&this.rebindCriteriaEntry(r).catch(i=>{this.masterSubEmitter?.dispatchEvent({type:"error",payload:i})})}addCriteria(t,n){this.masterSubEmitter&&this.masterSubEmitter._addCriteria(t);const r=this.maybeGetCriteriaEntry(t,n);if(r)return r.refCount+=1,r.emitter;const i=new QF(t,n);return this.addCriteriaEntry(i),this.subscribeToCriteria(i).catch(console.error),i.emitter}removeCriteria(t,n){const r=this.maybeGetCriteriaEntry(t,n);if(!r){console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times.");return}r.refCount-=1,!(r.refCount>0)&&(this.maybeEmitDisconnect(r),this.removeCriteriaEntry(r))}getWebSocket(){return this.ws}closeWebSocket(){this.wsClosed||(this.wsClosed=!0,this.ws.close())}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new Xx(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}async reconnectIfNeeded(){WF.includes(this.getWebSocket().readyState)&&await new Promise(t=>{const n=()=>{this.getWebSocket().removeEventListener("open",n),t()};this.getWebSocket().addEventListener("open",n),this.reconnectWebSocket()})}}const Bk="5.1.3-224406a",KF=tn.FHIR_JSON+", */*; q=0.1",XF="https://api.medplum.com/",JF=1e3,ZF=6e4,eH=0,tH=3e5,nH="Binary/",XT={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Uc={ClientCredentials:"client_credentials",AuthorizationCode:"authorization_code",RefreshToken:"refresh_token",JwtBearer:"urn:ietf:params:oauth:grant-type:jwt-bearer",TokenExchange:"urn:ietf:params:oauth:grant-type:token-exchange"},rH={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},iH={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class Vk extends Zm{options;fetch;createPdfImpl;storage;requestCache;cacheTime;baseUrl;fhirBaseUrl;authorizeUrl;tokenUrl;logoutUrl;fhircastHubUrl;cdsServicesUrl;defaultHeaders;onUnauthenticated;autoBatchTime;autoBatchQueue;maxRetryTime;refreshGracePeriod;subscriptionManager;medplumServer;clientId;clientSecret;credentialsInHeader;autoBatchTimerId;accessToken;accessTokenExpires;refreshToken;refreshPromise;profilePromise;sessionDetails;currentRateLimits;basicAuth;initPromise;initComplete=!0;keyValueClient;logLevel;constructor(t){if(super(),t?.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=t?.fetch??oH(),this.storage=t?.storage??new UF(void 0,t?.storagePrefix),this.createPdfImpl=t?.createPdf,this.baseUrl=vS(t?.baseUrl??XF),this.fhirBaseUrl=Pi(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=Pi(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=Pi(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=Pi(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=Pi(this.baseUrl,t?.fhircastHubUrl??"fhircast/STU3"),this.cdsServicesUrl=Pi(this.baseUrl,t?.cdsServicesUrl??"cds-services"),this.clientId=t?.clientId??"",this.clientSecret=t?.clientSecret??"",this.credentialsInHeader=t?.authCredentialsMethod==="header",this.defaultHeaders=t?.defaultHeaders??{},this.onUnauthenticated=t?.onUnauthenticated,this.refreshGracePeriod=t?.refreshGracePeriod??tH,this.logLevel=this.initializeLogLevel(t),this.maxRetryTime=t?.maxRetryTime??2e3,this.cacheTime=t?.cacheTime??(Ro()?ZF:eH),this.cacheTime>0?this.requestCache=new cS(t?.resourceCacheSize??JF):this.requestCache=void 0,t?.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t?.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}initializeLogLevel(t){return t?.logLevel?t.logLevel:t?.verbose!==void 0&&t.verbose?"verbose":"none"}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getCdsServicesUrl(){return this.cdsServicesUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),Ro()&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),this.requestCache?.delete(t)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(t){const n=Pi(this.fhirBaseUrl,t);for(const r of this.requestCache?.keys()??Cr)(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache?.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let i;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?i=new Promise((c,u)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:u}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):i=this.request("GET",t,n);const s=new no(i);return this.setCacheEntry(t,s,n),s}post(t,n,r,i={}){return t=t.toString(),this.setRequestBody(i,n),r&&this.setRequestContentType(i,r),this.invalidateUrl(t),this.request("POST",t,i)}put(t,n,r,i={}){return t=t.toString(),this.setRequestBody(i,n),r&&this.setRequestContentType(i,r),this.invalidateUrl(t),this.request("PUT",t,i)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,tn.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,r)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){const{codeChallengeMethod:r,codeChallenge:i}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:i},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){const r=new URLSearchParams(rr.getSearch()).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){rr.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,i,s=!0){let c=i;s&&(c=await this.ensureCodeChallenge(i)),rr.assign(this.getExternalAuthRedirectUri(t,n,r,c,s))}async exchangeExternalAccessToken(t,n,r){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");const i={grant_type:Uc.TokenExchange,subject_token_type:rH.AccessToken,client_id:n,subject_token:t};return r&&(i.membership_id=r),this.fetchTokens(i)}getExternalAuthRedirectUri(t,n,r,i,s=!0){const c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",n),c.searchParams.set("redirect_uri",r),c.searchParams.set("scope",i.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(i)),s){const{codeChallenge:u,codeChallengeMethod:f}=i;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!u)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",u)}return c.toString()}fhirUrl(...t){return new URL(Pi(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=WB(n)),r}search(t,n,r){const i=this.fhirSearchUrl(t,n),s="search-"+i.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=this.getBundle(i,r);return this.setCacheEntry(s,u,r),u}searchOne(t,n,r){const i=this.fhirSearchUrl(t,n);i.searchParams.set("_count","1"),i.searchParams.sort();const s="searchOne-"+i.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=new no(this.search(t,i.searchParams,r).then(f=>f.entry?.[0]?.resource));return this.setCacheEntry(s,u,r),u}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=new no(this.search(t,n,r).then(ZT));return this.setCacheEntry(s,u,r),u}async*searchResourcePages(t,n,r){let i=this.fhirSearchUrl(t,n);for(;i;){const s=new URL(i).searchParams;s.has("_count")||s.set("_count","1000");const c=await this.search(t,s,r),u=c.link?.find(f=>f.relation==="next");if(!c.entry?.length&&!u)break;yield ZT(c),i=u?.url?new URL(u.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){const r=this.requestCache?.get(this.fhirUrl(t,n).toString())?.value;return r?.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return XT;const[r,i]=n.split("/");if(!(!r||!i))return this.getCached(r,i)}readResource(t,n,r){if(!n)throw new Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(t,n),r)}readReference(t,n){const r=t.reference;if(!r)return new no(Promise.reject(new Error("Missing reference")));if(r==="system")return new no(Promise.resolve(XT));const[i,s]=r.split("/");return!i||!s?new no(Promise.reject(new Error("Invalid reference"))):this.readResource(i,s,n)}readCanonical(t,n,r){return Array.isArray(t)?this.searchOne("",{_type:t.join(","),url:n},r):this.searchOne(t,"url="+n,r)}requestSchema(t,n){if(ok(t))return Promise.resolve();const r=t+"-requestSchema",i=this.getCacheEntry(r,void 0);if(i)return i.value;const s=new no((async()=>{const c=`{
57
57
  StructureDefinitionList(_filter: "name eq ${t}") {
58
58
  resourceType,
59
59
  name,
@@ -232,4 +232,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
232
232
  }
233
233
  ]
234
234
  }`,_oe="MSH|^~\\&|ADT1|MCM|LABADT|MCM|198808181126|SECURITY|ADT|MSG00001|P|2.1\rPID|||PATID1234^5^M11||JONES^WILLIAM^A^III||19610615|M-||C|1200 N ELM STREET^^GREENSBORO^NC^27401-1020|GL|(919)379-1212|(919)271-3434||S||PATID12345001^2^M10|123456789|987654^NC\rNK1|1|JONES^BARBARA^K|SPO|||||20011105\rPV1|1|I|2000^2012^01||||004777^LEBAUER^SIDNEY^J.|||SUR||-||1|A0-";function Doe(){const e=Re(),{id:t}=Yt(),[n,r]=v.useState(),[i,s]=v.useState(),[c,u]=v.useState(),[f,h]=v.useState(Roe),[m,g]=v.useState(_oe),[y,x]=v.useState(tn.FHIR_JSON),S=v.useRef(null),w=v.useRef(null),[C,T]=v.useState(!1);v.useEffect(()=>{e.readResource("Bot",t).then(async A=>{r(A),s(A.runtimeVersion==="vmcontext"?"commonjs":"esnext"),u(await Aoe(e,A))}).catch(A=>Ae({color:"red",message:We(A),autoClose:!1}))},[e,t]);const R=v.useCallback(async()=>kd(S.current,{command:"getValue"}),[]),E=v.useCallback(async()=>kd(S.current,{command:"getOutput"}),[]),_=v.useCallback(async()=>y===tn.FHIR_JSON?JSON.parse(f):m,[y,f,m]),P=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),T(!0);try{const z=await R(),U=await E(),K=await e.createAttachment({data:z,filename:"index.ts",contentType:tn.TYPESCRIPT}),W=await e.createAttachment({data:U,filename:i==="commonjs"?"index.cjs":"index.mjs",contentType:tn.JAVASCRIPT}),ee=[{op:"add",path:"/sourceCode",value:K},{op:"add",path:"/executableCode",value:W}];await e.patchResource("Bot",t,ee),Ae({color:"green",message:"Saved"})}catch(z){Ae({color:"red",message:We(z),autoClose:!1})}finally{T(!1)}},[e,t,i,R,E]),O=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),T(!0);try{await e.post(e.fhirUrl("Bot",t,"$deploy")),Ae({color:"green",message:"Deployed"})}catch(z){Ae({color:"red",message:We(z),autoClose:!1})}finally{T(!1)}},[e,t]),k=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),T(!0);try{const z=await _(),U=await e.post(e.fhirUrl("Bot",t,"$execute"),z,y);await kd(w.current,{command:"setValue",value:U}),Ae({color:"green",message:"Success"})}catch(z){Ae({color:"red",message:We(z),autoClose:!1})}finally{T(!1)}},[e,t,_,y]);return!n||c===void 0?null:a.jsxs(Nt,{m:0,gutter:0,style:{overflow:"hidden"},children:[a.jsx(Nt.Col,{span:8,children:a.jsxs(gr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[a.jsx(Toe,{iframeRef:S,language:"typescript",module:i,testId:"code-frame",defaultValue:c,minHeight:"528px"}),a.jsxs(xe,{justify:"flex-end",gap:"xs",children:[a.jsx(Me,{type:"button",onClick:P,loading:C,leftSection:a.jsx(aG,{size:"1rem"}),children:"Save"}),a.jsx(Me,{type:"button",onClick:O,loading:C,leftSection:a.jsx(OS,{size:"1rem"}),children:"Deploy"}),a.jsx(Me,{type:"button",onClick:k,loading:C,leftSection:a.jsx(ZG,{size:"1rem"}),children:"Execute"})]})]})}),a.jsxs(Nt.Col,{span:4,children:[a.jsxs(gr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[a.jsx(pn,{data:[{label:"FHIR",value:tn.FHIR_JSON},{label:"HL7",value:tn.HL7_V2}],onChange:A=>x(A.currentTarget.value)}),y===tn.FHIR_JSON?a.jsx(vu,{value:f,onChange:A=>h(A),autosize:!0,minRows:15}):a.jsx("textarea",{className:Coe.hl7Input,value:m,onChange:A=>g(A.currentTarget.value),rows:15})]}),a.jsx(gr,{m:2,p:"xs",shadow:"md",children:a.jsx(Eoe,{iframeRef:w,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function Aoe(e,t){if(t.sourceCode?.url){const n=t.sourceCode.url?.split("/")?.find(mS);return(await e.download(e.fhirUrl("Binary",n))).text()}return t.code??""}function Cs(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function koe(){const e=Re(),{resourceType:t,id:n}=Yt(),r={reference:t+"/"+n},i=v.useCallback(s=>{e.updateResource(Cs(s)).then(()=>{Ae({color:"green",message:"Success"})}).catch(c=>{Ae({color:"red",message:We(c),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return a.jsx(lt,{children:a.jsx(fZ,{value:r,onSubmit:i})});case"Questionnaire":return a.jsx(lt,{children:a.jsx(AZ,{questionnaire:r,onSubmit:i})});default:return null}}function Poe(){const{resourceType:e,id:t}=Yt(),n=Wt({reference:e+"/"+t}),r=Fn();return n?a.jsx(lt,{children:a.jsx(KZ,{value:n,onStart:(i,s)=>r(`/forms/${bs(s)}`)?.catch(console.error),onEdit:(i,s,c)=>r(`/${c.reference}}`)?.catch(console.error)})}):null}function Noe(){const e=Re(),{resourceType:t,id:n}=Yt(),r=Fn();return a.jsxs(lt,{children:[a.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),a.jsx(Me,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>r(`/${t}`)?.catch(console.error)).catch(i=>Ae({color:"red",message:We(i),autoClose:!1}))},children:"Delete"})]})}const Ooe="_selectProfileBtn_tbaz6_1",Moe="_chevron_tbaz6_13",V_={selectProfileBtn:Ooe,chevron:Moe};function Loe(){const{resourceType:e,id:t}=Yt(),n=Wt({reference:e+"/"+t}),[r,i]=v.useState(),s=$l({onDropdownClose:()=>s.resetSelectedOption()}),c=v.useMemo(()=>{if(In(n?.meta?.profile))return[a.jsx(Ye.Option,{value:"",children:"None"},""),...n.meta.profile.map(f=>a.jsx(Ye.Option,{value:f,children:f},f))]},[n?.meta?.profile]);if(v.useEffect(()=>{n?.meta?.profile?.length===1&&i(n.meta.profile[0])},[n?.meta?.profile]),!n)return null;let u;return In(c)&&(u=a.jsx(xe,{justify:"flex-end",children:a.jsxs(Ne,{align:"flex-end",gap:"xs",children:[a.jsxs(Ye,{store:s,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:f=>{i(f),s.closeDropdown()},children:[a.jsx(Ye.Target,{children:a.jsx(An,{onClick:()=>s.toggleDropdown(),children:a.jsxs(mf,{fw:"bold",fs:"sm",className:V_.selectProfileBtn,children:[a.jsx("span",{children:"Pick profile"}),a.jsx(NS,{stroke:1.5,className:V_.chevron})]})})}),a.jsx(Ye.Dropdown,{w:"max-content",children:a.jsx(Ye.Options,{children:c})})]}),a.jsx(le,{children:r?a.jsxs(a.Fragment,{children:[a.jsx(ge,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),a.jsx(ge,{span:!0,size:"sm",children:r||"Nothing selected"})]}):a.jsx(ge,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),a.jsx(lt,{children:a.jsxs(Ne,{gap:"xl",children:[u,a.jsx(t1,{value:n,profileUrl:r})]})})}function Ioe(){const e=Re(),{resourceType:t,id:n}=Yt(),[r,i]=v.useState(),[s,c]=v.useState(),u=Fn(),[f,h]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(x=>{i(gi(x)),c(gi(x))}).catch(x=>{h(rn(x)),Ae({color:"red",message:We(x),autoClose:!1})})},[e,t,n]);const m=v.useCallback(x=>{h(void 0),e.updateResource(Cs(x)).then(()=>{u(`/${t}/${n}/details`)?.catch(console.error),Ae({id:"succes",color:"green",message:"Success"})}).catch(S=>{h(rn(S)),Ae({color:"red",message:We(S),autoClose:!1})})},[e,t,n,u]),g=v.useCallback(x=>{h(void 0);const S=tN.createPatch(r,Cs(x));e.patchResource(t,n,S).then(()=>{u(`/${t}/${n}/details`)?.catch(console.error),Ae({id:"succes",color:"green",message:"Success"})}).catch(w=>{h(rn(w)),Ae({color:"red",message:We(w),autoClose:!1})})},[e,t,n,r,u]),y=v.useCallback(()=>u(`/${t}/${n}/delete`)?.catch(console.error),[u,t,n]);return s?a.jsx(lt,{children:a.jsx(nm,{defaultValue:s,onSubmit:m,onPatch:g,onDelete:y,outcome:f})}):null}function zoe(){const{resourceType:e,id:t}=Yt(),n=Wt({reference:e+"/"+t});return n?a.jsx(lt,{maw:700,children:n.resourceType==="Patient"?a.jsx(aZ,{patient:n}):a.jsx(qo,{icon:a.jsx(Ns,{size:16}),title:"Unsupported export type",color:"red",children:"This page is only supported for Patient resources"})}):null}function mO({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,i=Re(),[s,c]=v.useState();return v.useEffect(()=>{i.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(u=>{c(u.filter(rK))}).catch(console.error)},[i,n,r]),a.jsx(bn,{value:t?.url,onChange:u=>{const f=s?.find(h=>h.url===u);f&&n(f)},children:a.jsx(bn.List,{children:s?.map(u=>{const f=e.meta?.profile?.includes(u.url),h=f?"This profile is present in this resource's meta.profile property.":"This profile is not included in this resource's meta.profile property.";return a.jsx(bn.Tab,{value:u.url,title:h,rightSection:f&&a.jsx(sS,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:a.jsx(NW,{size:"90%"})}),children:u.title||u.name},u.url)})})})}function gO(e,t){const n=Re(),r=Fn();return{defaultValue:{resourceType:e},handleSubmit:c=>{t&&t(void 0),n.createResource(c).then(u=>r("/"+u.resourceType+"/"+u.id)).catch(u=>{t&&t(rn(u)),Ae({color:"red",message:We(u),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function Tx(){const{resourceType:e}=Yt(),t=Fr(),[n,r]=v.useState(),{defaultValue:i,handleSubmit:s}=gO(e,r),[c,u]=v.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),h=v.useCallback(m=>{const g=Cs(m);c&&Ck(g,c.url),s(g)},[c,s]);return f?a.jsx(lt,{children:a.jsxs(Ne,{children:[a.jsx(mO,{resource:i,currentProfile:c,onChange:u}),c?a.jsx(nm,{defaultValue:i,onSubmit:h,outcome:n,profileUrl:c.url},c.url):a.jsx(ge,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):a.jsx(lt,{children:a.jsx(nm,{defaultValue:i,onSubmit:s,outcome:n})})}function F_(){const e=Re(),{resourceType:t,id:n}=Yt(),r=e.readHistory(t,n).read();return a.jsx(lt,{children:a.jsx(See,{history:r})})}function $oe(){const{resourceType:e}=Yt(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:i}=gO(e,n),s=v.useCallback(c=>{i(JSON.parse(c["new-resource"]))},[i]);return a.jsxs(lt,{children:[t&&a.jsx(xr,{outcome:t}),a.jsxs(pt,{onSubmit:s,children:[a.jsx(vu,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:fo(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),a.jsx(xe,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(Me,{type:"submit",children:"OK"})})]})]})}function Uoe(){const e=Re(),{resourceType:t,id:n}=Yt(),r=Wt({reference:t+"/"+n}),i=Fn(),[s,c]=v.useState(),u=v.useCallback(f=>{e.updateResource(Cs(JSON.parse(f.resource))).then(()=>{c(void 0),i(`/${t}/${n}/details`)?.catch(console.error),Ae({color:"green",message:"Success"})}).catch(h=>{Ae({color:"red",message:We(h),autoClose:!1})})},[e,t,n,i]);return r?a.jsxs(lt,{children:[s&&a.jsx(xr,{outcome:s}),a.jsxs(pt,{onSubmit:u,children:[a.jsx(vu,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:fo(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),a.jsx(xe,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(Me,{type:"submit",children:"OK"})})]})]}):null}function Boe(e){const{resourceType:t,id:n}=e;return a.jsxs(lt,{children:[a.jsxs(qo,{icon:a.jsx(Ns,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",a.jsx("br",{}),a.jsx(wt,{href:`/forms/${n}`,children:`/forms/${n}`})]}),a.jsx(QP,{questionnaire:{reference:t+"/"+n},onSubmit:()=>alert("You submitted the preview")})]})}const Voe="_propertyTable_1xts4_1",Foe="_propertiesTitle_1xts4_17",vO={propertyTable:Voe,propertiesTitle:Foe};function Hoe(e){return e.valueCode||e.valueString||(e.valueBoolean===void 0?void 0:String(e.valueBoolean))||(e.valueInteger===void 0?void 0:String(e.valueInteger))||(e.valueDecimal===void 0?void 0:String(e.valueDecimal))||e.valueDate||e.valueDateTime||"N/A"}function qoe(e){const{properties:t}=e,n=t.map(r=>{let i="",s="",c="";return r.part?.forEach(u=>{u.name==="code"?i=u.valueCode||"":u.name==="description"?s=u.valueString||"":u.name==="value"&&(c=Hoe(u))}),{code:i,description:s,value:c}});return a.jsxs(Z,{className:vO.propertyTable,children:[a.jsx(Z.Thead,{children:a.jsxs(Z.Tr,{children:[a.jsx(Z.Th,{children:"Code"}),a.jsx(Z.Th,{children:"Description"}),a.jsx(Z.Th,{children:"Value"})]})}),a.jsx(Z.Tbody,{children:n.map((r,i)=>a.jsxs(Z.Tr,{children:[a.jsx(Z.Td,{children:r.code}),a.jsx(Z.Td,{children:r.description}),a.jsx(Z.Td,{children:r.value})]},`property-${i}`))})]})}function Goe(e){const{valueSet:t}=e,n=Re(),r=t.url,[i,s]=v.useState(),[c,u]=v.useState(),[f,h]=v.useState(!1),[m,g]=v.useState(),y=v.useCallback(async w=>{if(s(w),u(void 0),g(void 0),!w?.code||!w?.system){h(!1);return}h(!0);try{const C=new URLSearchParams({system:w.system,code:w.code}),T=n.fhirUrl("CodeSystem","$lookup")+"?"+C.toString(),R=await n.get(T);u(R)}catch(C){g(C instanceof Error?C:new Error(String(C)))}finally{h(!1)}},[n]),x=v.useMemo(()=>c?.parameter?.filter(w=>w.name==="property"&&w.part)??[],[c]),S=x.length>0;return a.jsx(lt,{children:a.jsxs(Ne,{gap:"xl",children:[a.jsx(Af,{binding:r,placeholder:"Select a value from the ValueSet",onChange:w=>y(w[0]),defaultValue:i,maxValues:1}),i?a.jsxs(Ne,{gap:"md",children:[a.jsxs(Pf,{children:[a.jsx(Ur,{term:"Code",children:i.code}),i.system&&a.jsx(Ur,{term:"System",children:i.system}),i.display&&a.jsx(Ur,{term:"Display",children:i.display})]}),f&&a.jsxs(xe,{gap:"xs",children:[a.jsx(Pr,{size:"sm"}),a.jsx(ge,{size:"sm",c:"dimmed",children:"Loading properties..."})]}),!f&&m&&a.jsxs(qo,{icon:a.jsx(Ns,{size:16}),title:"Lookup Failed",color:"red",children:["Failed to retrieve code information: ",We(m)]}),!f&&!m&&S&&a.jsx(zS,{children:a.jsxs(Ne,{gap:"xs",mt:"lg",children:[a.jsx(ge,{fw:500,size:"sm",c:"dimmed",className:vO.propertiesTitle,children:"Properties"}),a.jsx(qoe,{properties:x})]})})]}):null]})})}function Woe(){const{resourceType:e,id:t}=Yt(),n=Wt({reference:e+"/"+t});return n?n.resourceType==="Questionnaire"?a.jsx(Boe,{resourceType:e,id:t}):n.resourceType==="ValueSet"?a.jsx(Goe,{valueSet:n}):null:null}function Qoe(){const e=Re(),{resourceType:t,id:n}=Yt(),[r,i]=v.useState(),[s,c]=v.useState();return v.useEffect(()=>{e.readResource(t,n).then(u=>i(gi(u))).catch(u=>{Ae({color:"red",message:We(u)})})},[e,t,n]),r?a.jsxs(lt,{children:[a.jsxs(ze,{order:2,children:["Available ",t," profiles"]}),a.jsx(Ne,{children:a.jsxs(a.Fragment,{children:[a.jsx(mO,{resource:r,currentProfile:s,onChange:c}),s?a.jsx(Yoe,{profile:s,resource:r,onResourceUpdated:u=>i(u)},s.url):a.jsx(ge,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const Yoe=({profile:e,resource:t,onResourceUpdated:n})=>{const r=Re(),[i,s]=v.useState(),[c,u]=v.useState(()=>t.meta?.profile?.includes(e.url)),f=v.useCallback(h=>{s(void 0);const m=Cs(h);c?Ck(m,e.url):QB(m,e.url),r.updateResource(m).then(g=>{n(g),Ae({color:"green",message:"Success"})}).catch(g=>{s(rn(g)),Ae({color:"red",message:We(g),autoClose:!1})})},[r,e.url,n,c]);return a.jsxs(Ne,{children:[a.jsx(bf,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:h=>u(h.currentTarget.checked),"data-testid":"profile-toggle"}),c?a.jsx(nm,{profileUrl:e.url,defaultValue:t,onSubmit:f,outcome:i}):a.jsx("form",{noValidate:!0,onSubmit:h=>{h.preventDefault(),f(t)},children:a.jsx(xe,{justify:"flex-end",mt:"xl",children:a.jsx(Me,{type:"submit",children:"OK"})})})]})},yO={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},Koe=Object.keys(yO);function Xoe(){const e=Re(),{id:t}=Yt(),n=Wt({reference:`Questionnaire/${t}`}),[r,i]=v.useState(),[s,c]=v.useState("create"),[u,f]=v.useState(0),h=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>Joe(g,n));function m(){r&&n&&e.createResource({resourceType:"Subscription",status:"active",reason:`Connect bot ${r.name} to questionnaire responses`,criteria:`QuestionnaireResponse?questionnaire=${n.url?`${n.url},${$t(n)}`:$t(n)}`,channel:{type:"rest-hook",endpoint:$t(r)},...s?{extension:[{url:"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",valueCode:s}]}:void 0}).then(()=>{i(void 0),f(Date.now()),e.invalidateSearches("Subscription"),Ae({color:"green",message:"Success"})}).catch(g=>Ae({color:"red",message:We(g),autoClose:!1}))}return a.jsxs(lt,{children:[a.jsx(ze,{children:"Bots"}),a.jsxs(Ne,{children:[h.length===0&&a.jsx("p",{children:"No bots found."}),h.map(g=>a.jsxs("div",{children:[a.jsx("h3",{children:a.jsx(Hl,{value:{reference:g.channel?.endpoint},link:!0})}),a.jsxs("p",{children:["Criteria: ",g.criteria]})]},g.id))]}),a.jsx(dn,{}),a.jsxs(Ne,{mt:10,children:[a.jsx(cf,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),a.jsxs(xe,{children:[a.jsx(Eu,{name:"bot",resourceType:"Bot",onChange:g=>i(g)}),a.jsx(Me,{onClick:m,children:"Connect"})]}),a.jsx(xe,{children:a.jsx(pn,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:Koe,onChange:g=>c(yO[g.target.value])})})]}),a.jsx("div",{style:{display:"none"},children:u})]})}function Joe(e,t){if(!t)return!1;const n=e.criteria||"",r=e.channel?.endpoint||"";return n.startsWith("QuestionnaireResponse?")&&r.startsWith("Bot/")&&(n.includes($t(t))||(t.url?n.includes(t.url):!1))}function Zoe(){const{id:e}=Yt(),t=Fn(),r=Re().readReference({reference:`Questionnaire/${e}`}).read(),[i,s]=v.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:fe.EQUALS,value:r.url?`${r.url},Questionnaire/${e}`:`Questionnaire/${e}`}],fields:["id","_lastUpdated"]});return a.jsx(lt,{children:a.jsx(ql,{search:i,onClick:c=>t(`/${c.resource.resourceType}/${c.resource.id}`)?.catch(console.error),onChange:c=>s(c.definition),hideFilters:!0,hideToolbar:!0})})}function eae(){const e=Re(),{resourceType:t,id:n}=Yt(),r=Wt({reference:t+"/"+n}),i=v.useCallback(s=>{e.updateResource(Cs(s)).then(()=>{Ae({color:"green",message:"Success"})}).catch(c=>{Ae({color:"red",message:We(c),autoClose:!1})})},[e]);return r?a.jsx(lt,{children:a.jsx(VZ,{onSubmit:i,definition:r})}):null}function tae(){const{resourceType:e,id:t}=Yt(),n=Wt({reference:e+"/"+t});return n?a.jsx(lt,{children:e==="MeasureReport"?a.jsx(iZ,{measureReport:n}):a.jsx(e1,{value:n})}):null}const nae="_container_1ue98_1",rae="_entry_1ue98_14",iae="_active_1ue98_21",Rx={container:nae,entry:rae,active:iae};function oae(e){const t=Re(),n=Wt(e.value),[r,i]=v.useState();return v.useEffect(()=>{if(!n)return;const s=g1(n);if(!s)return;const c="reference"in s?s.reference:$t(s);t.search("ServiceRequest","subject="+c).then(u=>{const h=(u.entry??[]).map(m=>m.resource);nN(h),h.reverse(),i(h)}).catch(u=>Ae({color:"red",message:We(u),autoClose:!1}))},[t,n]),r?a.jsx("div",{"data-testid":"quick-service-requests",className:Rx.container,children:r.map(s=>a.jsxs("div",{className:Ft(Rx.entry,{[Rx.active]:s.id===n?.id}),children:[a.jsx("p",{children:a.jsx(jt,{to:s,children:aae(s)})}),s.category?.[0]?.text&&a.jsx("p",{children:s.category[0]?.text}),s.code?.coding?.[0]?.code&&a.jsx("p",{children:s.code.coding[0]?.code}),a.jsx("p",{children:sae(s)})]},s.id))}):null}function aae(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function sae(e){return e.authoredOn?e.authoredOn.substring(0,10):e.meta?.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const lae="_container_1l2dh_1",cae={container:lae};function uae(e){const t=Wt(e.valueSet);if(!t)return null;const n=[""],r=t.compose?.include?.[0]?.concept?.map(i=>i.code);return r&&n.push(...r),e.defaultValue&&!n.includes(e.defaultValue)&&n.push(e.defaultValue),a.jsx("div",{className:cae.container,children:a.jsx(pn,{defaultValue:e.defaultValue,onChange:i=>e.onChange(i.currentTarget.value),data:n})})}function dae(e){const t=Wt(e.specimen);return t?a.jsxs(vt,{children:[a.jsxs(vt.Entry,{children:[a.jsx(vt.Key,{children:"Type"}),a.jsx(vt.Value,{children:"Specimen"})]}),a.jsxs(vt.Entry,{children:[a.jsx(vt.Key,{children:"Collected"}),a.jsx(vt.Value,{children:Nr(t.collection?.collectedDateTime)})]}),a.jsxs(vt.Entry,{children:[a.jsx(vt.Key,{children:"Specimen Age"}),a.jsx(vt.Value,{children:fae(t)})]}),t.collection?.collectedDateTime&&t.receivedTime?a.jsxs(vt.Entry,{children:[a.jsx(vt.Key,{children:"Specimen Stability"}),a.jsx(vt.Value,{children:hae(t)})]}):a.jsx(a.Fragment,{})]}):null}function fae(e){const t=e.collection?.collectedDateTime;if(!t)return;const n=new Date(t);return xO(bO(n,new Date))}function hae(e){if(!e.collection?.collectedDateTime||!e.receivedTime)return;const t=new Date(e.collection.collectedDateTime),n=new Date(e.receivedTime);return xO(bO(t,n))}function xO(e){return e.toString().padStart(3,"0")+"D"}function bO(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function pae(e){const t=["Timeline"];return e==="Bot"&&t.push("Editor","Subscriptions"),e==="PlanDefinition"&&t.push("Apply","Builder"),e==="Questionnaire"&&t.push("Preview","Builder","Bots","Responses"),e==="ValueSet"&&t.push("Preview"),(e==="DiagnosticReport"||e==="MeasureReport")&&t.push("Report"),e==="RequestGroup"&&t.push("Checklist"),e==="ObservationDefinition"&&t.push("Ranges"),e==="Agent"&&t.push("Tools"),t.push("Details","Edit","Event","History","Blame","JSON","Apps","Profiles"),e==="Patient"&&t.push("Export"),t}function mae(){const e=Re(),{resourceType:t,id:n}=Yt(),r={reference:t+"/"+n},[i,s]=v.useState(),c=Wt(r,s),u=pae(t);async function f(){const w=(await e.readHistory(t,n)).entry?.find(C=>!!C.resource)?.resource;w?h(w):Ae({color:"red",message:"No history to restore",autoClose:!1})}function h(S){e.updateResource(Cs(S)).then(()=>{s(void 0),Ae({color:"green",message:"Success"})}).catch(w=>{Ae({color:"red",message:We(w),autoClose:!1})})}if(i)return oU(i)?a.jsxs(lt,{children:[a.jsx(ze,{children:"Deleted"}),a.jsx("p",{children:"The resource was deleted."}),a.jsx(Me,{color:"red",onClick:f,children:"Restore"})]}):a.jsx(xr,{outcome:i});function m(S){const w=c,C=w.orderDetail||[];C.length===0&&C.push({}),C[0].text!==S&&(C[0].text=S,h({...w,orderDetail:C}))}const g=c&&g1(c),y=c&&ire(c),x=e.getUserConfiguration()?.option?.find(S=>S.id==="statusValueSet")?.valueString;return a.jsxs(a.Fragment,{children:[c?.resourceType==="ServiceRequest"&&x&&a.jsx(uae,{valueSet:{reference:x},defaultValue:c.orderDetail?.[0]?.text,onChange:m},$t(c)+"-"+c.orderDetail?.[0]?.text),c&&a.jsx(oae,{value:c}),c&&a.jsxs(gr,{children:[g&&a.jsx(dN,{patient:g}),y&&a.jsx(dae,{specimen:y}),t!=="Patient"&&a.jsx(fO,{resource:r}),a.jsx(ti,{children:a.jsx(Of,{baseUrl:`/${t}/${n}`,tabs:u})})]}),a.jsx(h1,{})]})}function vp(){const e=Fn(),{resourceType:t,id:n,versionId:r,tab:i}=Yt(),s=Re(),[c,u]=v.useState(!0),[f,h]=v.useState(),[m,g]=v.useState();if(v.useEffect(()=>{g(void 0),u(!0),s.readHistory(t,n).then(E=>h(E)).then(()=>u(!1)).catch(E=>{g(E),u(!1)})},[s,t,n]),c)return a.jsx(Ui,{});const y=f?.entry??[],x=y.findIndex(E=>E.resource?.meta?.versionId===r);if(x===-1)return a.jsxs(lt,{children:[a.jsx(ze,{children:"Version not found"}),a.jsx(jt,{to:`/${t}/${n}`,children:"Return to resource"})]});const S=y[x].resource,w=x<y.length-1?y[x+1].resource:void 0,C="diff",T=i||C,R=y.length-x;return a.jsx(gf,{maw:1200,children:a.jsx(Os,{children:a.jsxs(Ne,{gap:"lg",children:[m&&a.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)}),a.jsxs(qm,{cols:2,mb:"lg",children:[a.jsx(qi,{total:y.length,value:R,getControlProps:sN,onChange:E=>e(`/${t}/${n}/_history/${y[y.length-E]?.resource?.meta?.versionId}/${T}`)?.catch(console.error)}),a.jsx(xe,{justify:"right",children:a.jsx(Cl,{data:[{value:"diff",label:"Diff"},{value:"raw",label:"Raw"}],value:T,onChange:E=>e(`/${t}/${n}/_history/${r}/${E||C}`)?.catch(console.error)})})]}),a.jsx(le,{mb:"lg",children:a.jsxs(Pf,{compact:!0,children:[a.jsx(Ur,{term:"Version ID",children:S.meta?.versionId}),a.jsx(Ur,{term:"Author",children:a.jsx(Pd,{value:S.meta?.author,link:!0},S.meta?.author?.reference)}),a.jsx(Ur,{term:"Date/Time",children:Nr(S.meta?.lastUpdated)})]})}),T==="diff"&&a.jsx(vee,{original:w??{resourceType:t,id:n},revised:S}),T==="raw"&&a.jsx("pre",{style:{fontSize:"9pt"},children:JSON.stringify(S,void 0,2)})]})})})}function gae(){const{resourceType:e,id:t}=Yt(),n=Fn(),[r,i]=v.useState({resourceType:"Subscription",filters:[{code:"url",operator:fe.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return a.jsx(lt,{children:a.jsx(ql,{search:r,onClick:s=>n(`/${s.resource.resourceType}/${s.resource.id}`)?.catch(console.error),onChange:s=>i(s.definition),hideFilters:!0})})}function vae(e){const t=Re(),{resource:n,opened:r,onClose:i}=e,[s,c]=v.useState(!1),[u,f]=v.useState(),[h,m]=v.useState(!1),g=v.useCallback(async()=>{if(n?.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:s&&u?$t(u):void 0,verbose:h}),Ae({color:"green",message:"Done"}),i()}catch(y){Ae({color:"red",message:We(y),autoClose:!1})}},[t,n,i,s,u,h]);return a.jsx(Mn,{opened:r,onClose:i,title:"Resend Subscriptions",children:a.jsx(pt,{onSubmit:g,children:a.jsxs(Ne,{children:[a.jsx(fn,{label:"Choose subscription (all subscriptions by default)",onChange:y=>c(y.currentTarget.checked)}),s&&a.jsx(Eu,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:f}),a.jsx(fn,{label:"Verbose mode",onChange:y=>m(y.currentTarget.checked)}),a.jsx(xe,{justify:"flex-end",children:a.jsx(Me,{type:"submit",children:"Resend"})})]})})})}function H_(){const e=Re(),t=ju(),{resourceType:n,id:r}=Yt(),i={reference:n+"/"+r},[s,c]=v.useState(),u=Ts(!1);function f(R,E){return e.updateResource({...R,priority:E})}function h(R,E){f(R,"stat").then(E).catch(console.error)}function m(R,E){f(R,"routine").then(E).catch(console.error)}function g(R){t(`/${R.resourceType}/${R.id}`)}function y(R){t(`/${R.resourceType}/${R.id}/edit`)}function x(R){t(`/${R.resourceType}/${R.id}/delete`)}function S(R){c(R),u[1].open()}function w(R){t(`/${R.resourceType}/${R.id}/_history/${R.meta?.versionId}`)}function C(R,E){const _="aws-textract";Ae({id:_,title:"AWS Textract in Progress",message:"Extracting text... This may take a moment...",loading:!0,autoClose:!1}),e.post(e.fhirUrl(R.resourceType,R.id,"$aws-textract"),{}).then(()=>{E(),hl({id:_,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:a.jsx(Go,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(P=>hl({id:_,title:"AWS Textract Error",color:"red",message:We(P),icon:a.jsx(ws,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function T(R){const{primaryResource:E,currentResource:_,reloadTimeline:P}=R,O=_.resourceType===E.resourceType&&_.id===E.id,k=_.resourceType==="Communication"&&_.priority!=="stat",A=_.resourceType==="Communication"&&_.priority==="stat",z=O,U=!O,K=!O,W=!O,ee=e.getProjectMembership()?.admin,B=ee,G=hoe()&&(_.resourceType==="DocumentReference"||_.resourceType==="Media");return a.jsxs(be.Dropdown,{children:[a.jsx(be.Label,{children:"Resource"}),k&&a.jsx(be.Item,{leftSection:a.jsx(YG,{size:14}),onClick:()=>h(_,P),"aria-label":`Pin ${$t(_)}`,children:"Pin"}),A&&a.jsx(be.Item,{leftSection:a.jsx(XG,{size:14}),onClick:()=>m(_,P),"aria-label":`Unpin ${$t(_)}`,children:"Unpin"}),U&&a.jsx(be.Item,{leftSection:a.jsx(uR,{size:14}),onClick:()=>g(_),"aria-label":`Details ${$t(_)}`,children:"Details"}),z&&a.jsx(be.Item,{leftSection:a.jsx(uR,{size:14}),onClick:()=>w(_),"aria-label":`Details ${$t(_)}`,children:"Details"}),K&&a.jsx(be.Item,{leftSection:a.jsx(oP,{size:14}),onClick:()=>y(_),"aria-label":`Edit ${$t(_)}`,children:"Edit"}),ee&&a.jsxs(a.Fragment,{children:[a.jsx(be.Divider,{}),a.jsx(be.Label,{children:"Admin"}),B&&a.jsx(be.Item,{leftSection:a.jsx(aW,{size:14}),onClick:()=>S(_),"aria-label":`Resend Subscriptions ${$t(_)}`,children:"Resend Subscriptions"})]}),G&&a.jsxs(a.Fragment,{children:[a.jsx(be.Divider,{}),a.jsx(be.Label,{children:"AWS AI"}),a.jsx(be.Item,{leftSection:a.jsx(CW,{size:14}),onClick:()=>C(_,P),"aria-label":`AWS Textract ${$t(_)}`,children:"AWS Textract"})]}),W&&a.jsxs(a.Fragment,{children:[a.jsx(be.Divider,{}),a.jsx(be.Label,{children:"Danger zone"}),a.jsx(be.Item,{color:"red",leftSection:a.jsx(rg,{size:14}),onClick:()=>x(_),"aria-label":`Delete ${$t(_)}`,children:"Delete"})]})]})}return a.jsxs(a.Fragment,{children:[n==="Encounter"&&a.jsx(GX,{encounter:i,getMenu:T}),n==="Patient"&&a.jsx(cZ,{patient:i,getMenu:T}),n==="ServiceRequest"&&a.jsx(Cee,{serviceRequest:i,getMenu:T}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&a.jsx(qX,{resource:i,getMenu:T}),a.jsx(vae,{resource:s,opened:u[0],onClose:u[1].close},`resend-subscriptions-${s?.id}`)]})}function yae(e){const{opened:t,close:n,version:r,loadingStatus:i,handleStatus:s,handleUpgrade:c}=e,[u,f]=v.useState(),[h,m]=v.useState(!1);return v.useEffect(()=>{t&&(u||AH("app-tools-page").then(f).catch(console.error),s())},[t,u,s]),u&&r&&!i?r==="unknown"?a.jsx("p",{children:"Unable to determine the current version of the agent. Check the network connectivity of the agent."}):r.startsWith(u)?a.jsxs("p",{children:["This agent is already on the latest version (",u,")."]}):a.jsxs(a.Fragment,{children:[a.jsxs("p",{children:["Are you sure you want to upgrade this agent from version ",r," to version ",u,"?"]}),a.jsxs(xe,{children:[a.jsx(Me,{onClick:()=>{c(h),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"}),a.jsx(fn,{label:"Force",onChange:g=>m(g.currentTarget.checked)})]})]}):a.jsx(Ui,{})}function xae(){const e=Re(),{id:t}=Yt(),n=v.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,i]=v.useState(!1),[s,c]=v.useState(!1),[u,f]=v.useState(!1),[h,m]=v.useState(!1),[g,y]=v.useState(),[x,S]=v.useState(),[w,C]=v.useState(),[T,R]=v.useState(),[E,_]=v.useState(!1),[P,O]=v.useState(!1),[k,A]=v.useState(),[z,{open:U,close:K}]=Ts(!1);v.useEffect(()=>{if(r||s||u||E){O(!0);return}O(!1)},[r,s,u,E]);const W=v.useCallback(()=>{i(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(V=>{y(V.parameter?.find(X=>X.name==="status")?.valueCode),S(V.parameter?.find(X=>X.name==="version")?.valueString),C(V.parameter?.find(X=>X.name==="lastUpdated")?.valueInstant)}).catch(V=>$(We(V))).finally(()=>i(!1))},[e,t]),ee=v.useCallback(V=>{const X=V.host,M=V.pingCount||1;X&&(_(!0),e.pushToAgent(n,X,`PING ${M}`,tn.PING,!0).then(F=>R(F)).catch(F=>$(We(F))).finally(()=>_(!1)))},[e,n]),B=v.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(V=>{I("Agent config reloaded successfully.")}).catch(V=>$(We(V))).finally(()=>c(!1))},[e,t]),G=v.useCallback(V=>{f(!0);const X=e.fhirUrl("Agent",t,"$upgrade");X.searchParams.set("force",String(V)),e.get(X,{cache:"reload"}).then(M=>{I("Agent upgraded successfully.")}).catch(M=>$(We(M))).finally(()=>f(!1))},[e,t]),L=v.useCallback(V=>{m(!0);const X=V.logLimit||20;e.get(e.fhirUrl("Agent",t,`$fetch-logs${X!==void 0?`?limit=${X}`:""}`),{cache:"reload"}).then(M=>{const F=M?.parameter?.find(ie=>ie.name==="logs");F&&A(F?.valueString)}).catch(M=>$(We(M))).finally(()=>m(!1))},[e,t]);function I(V){Ae({color:"green",title:"Success",icon:a.jsx(Go,{size:"1rem"}),message:V})}function $(V){Ae({color:"red",title:"Error",message:V,autoClose:!1})}return a.jsxs(lt,{children:[a.jsx(Mn,{opened:z,onClose:K,title:"Upgrade Agent",centered:!0,children:a.jsx(yae,{opened:z,close:K,version:x,loadingStatus:r,handleStatus:W,handleUpgrade:G})}),a.jsx(ze,{order:1,children:"Agent Tools"}),a.jsxs("div",{style:{marginBottom:10},children:["Agent: ",a.jsx(Hl,{value:n,link:!0})]}),a.jsx(dn,{my:"lg"}),a.jsx(ze,{order:2,children:"Agent Status"}),a.jsx("p",{children:"Retrieve the status of the agent. This tests whether the agent is connected to the Medplum server, and the last time it was able to communicate."}),a.jsx(Me,{onClick:W,loading:r,disabled:P&&!r,children:"Get Status"}),!r&&g&&a.jsx(Z,{children:a.jsxs(Z.Tbody,{children:[a.jsxs(Z.Tr,{children:[a.jsx(Z.Td,{children:"Status"}),a.jsx(Z.Td,{children:a.jsx(pg,{status:g})})]}),a.jsxs(Z.Tr,{children:[a.jsx(Z.Td,{children:"Version"}),a.jsx(Z.Td,{children:x})]}),a.jsxs(Z.Tr,{children:[a.jsx(Z.Td,{children:"Last Updated"}),a.jsx(Z.Td,{children:Nr(w,void 0,{timeZoneName:"longOffset"})})]})]})}),a.jsx(dn,{my:"lg"}),a.jsx(ze,{order:2,children:"Reload Config"}),a.jsx("p",{children:"Reload the configuration of this agent, syncing it with the current version of the Agent resource on the Medplum server."}),a.jsx(Me,{onClick:B,loading:s,disabled:P&&!s,"aria-label":"Reload config",children:"Reload Config"}),a.jsx(dn,{my:"lg"}),a.jsx(ze,{order:2,children:"Upgrade Agent"}),a.jsx("p",{children:"Upgrade the version of this agent, to either the latest (default) or a specified version."}),a.jsx(Me,{onClick:U,loading:u,disabled:P&&!u,"aria-label":"Upgrade agent",children:"Upgrade"}),a.jsx(dn,{my:"lg"}),a.jsxs(pt,{onSubmit:L,children:[a.jsx(ze,{order:2,children:"Fetch Logs"}),a.jsx("p",{children:"Fetch logs from the agent."}),k?.length?a.jsx(mf,{block:!0,mb:15,children:k}):null,a.jsxs(xe,{children:[a.jsx(hr,{w:100,id:"logLimit",name:"logLimit",placeholder:"20",label:"Log Limit"}),a.jsx(Me,{mt:22,loading:h,disabled:P&&!h,"aria-label":"Fetch logs",type:"submit",children:"Fetch Logs"})]})]}),a.jsx(dn,{my:"lg"}),a.jsx(ze,{order:2,children:"Ping from Agent"}),a.jsx("p",{children:"Send a ping command from the agent to a valid IP address or hostname. Use this tool to troubleshoot local network connectivity."}),a.jsx(pt,{onSubmit:ee,children:a.jsxs(xe,{children:[a.jsx(Fe,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:a.jsx(Pn,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:E,disabled:P&&!E,children:a.jsx(uW,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),a.jsx(hr,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!E&&T&&a.jsxs(a.Fragment,{children:[a.jsx(ze,{order:5,mt:"sm",mb:0,children:"Last Ping"}),a.jsx("pre",{children:T})]})]})}function bae(){const e=Fn(),t=Re(),[n,r]=v.useState();v.useEffect(()=>{t.get("auth/me",{cache:"no-cache"}).then(r).catch(s=>Ae({color:"red",message:We(s),autoClose:!1}))},[t]);function i(s){t.post("auth/revoke",{loginId:s}).then(()=>t.get("auth/me",{cache:"no-cache"})).then(r).then(()=>Ae({color:"green",message:"Login revoked"})).catch(c=>Ae({color:"red",message:We(c),autoClose:!1}))}return n?a.jsxs(a.Fragment,{children:[a.jsxs(lt,{children:[a.jsx(ze,{children:"Security"}),a.jsxs(Pf,{children:[a.jsx(Ur,{term:"ID",children:a.jsx(wt,{href:`/${$t(n.profile)}`,children:n.profile.id})}),a.jsx(Ur,{term:"Resource Type",children:n.profile.resourceType}),a.jsx(Ur,{term:"Name",children:Na(n.profile.name?.[0])})]})]}),a.jsxs(lt,{children:[a.jsx(ze,{children:"Sessions"}),a.jsxs(Z,{children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{children:"OS"}),a.jsx("th",{children:"Browser"}),a.jsx("th",{children:"IP Address"}),a.jsx("th",{children:"Auth Method"}),a.jsx("th",{children:"Last Updated"}),a.jsx("th",{})]})}),a.jsx("tbody",{children:n.security.sessions.map(s=>a.jsxs("tr",{children:[a.jsx("td",{children:s.os}),a.jsx("td",{children:s.browser}),a.jsx("td",{children:s.remoteAddress}),a.jsx("td",{children:s.authMethod}),a.jsx("td",{children:Nr(s.lastUpdated)}),a.jsx("td",{children:a.jsx(wt,{href:"#",onClick:()=>i(s.id),children:"Revoke"})})]},s.id))})]})]}),a.jsxs(lt,{children:[a.jsx(ze,{children:"Password"}),a.jsx(Me,{onClick:()=>e("/changepassword")?.catch(console.error),children:"Change password"})]}),a.jsxs(lt,{children:[a.jsx(ze,{children:"Multi Factor Auth"}),a.jsxs("p",{children:["Enrolled: ",n.security.mfaEnrolled.toString()]}),!n.security.mfaEnrolled&&a.jsx(Me,{onClick:()=>e("/mfa")?.catch(console.error),children:"Enroll"})]})]}):null}function Sae(){const{id:e,secret:t}=Yt(),n=Re(),[r,i]=v.useState(),[s,c]=v.useState(!1),u=Ms(r,void 0);return a.jsxs(lt,{width:450,children:[a.jsx(xr,{issues:u}),a.jsxs(pt,{onSubmit:f=>{if(f.password!==f.confirmPassword){i(Oo("Passwords do not match","confirmPassword"));return}i(void 0);const h={id:e,secret:t,password:f.password};n.post("auth/setpassword",h).then(()=>c(!0)).catch(m=>i(rn(m)))},children:[a.jsxs(ar,{direction:"column",align:"center",justify:"center",children:[a.jsx(Wi,{size:32}),a.jsx(ze,{children:"Set password"})]}),!s&&a.jsxs(Ne,{children:[a.jsx(ao,{name:"password",label:"New password",required:!0,error:Ut(r,"password")}),a.jsx(ao,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Ut(r,"confirmPassword")}),a.jsx(xe,{justify:"flex-end",mt:"xl",children:a.jsx(Me,{type:"submit",children:"Set password"})})]}),s&&a.jsxs("div",{"data-testid":"success",children:["Password set. You can now ",a.jsx(jt,{to:"/signin",children:"sign in"}),"."]})]})]})}function jae(){const e=_f(),t=Fn(),[n]=Sg(),r=Bf(),i=v.useCallback(()=>{const s=n.get("next");t(s?.startsWith("/")?s:"/")?.catch(console.error)},[n,t]);return v.useEffect(()=>{e&&n.has("next")&&i()},[e,n,i]),a.jsxs(NP,{onSuccess:()=>i(),onForgotPassword:()=>t("/resetpassword")?.catch(console.error),onRegister:w1()?()=>t("/register")?.catch(console.error):void 0,googleClientId:r.googleClientId,login:n.get("login")||void 0,projectId:n.get("project")||void 0,children:[a.jsx(Wi,{size:32}),n.get("project")!=="new"&&a.jsxs(ze,{order:3,py:"lg",ta:"center",children:["Sign in to ",dP()]}),n.get("project")==="new"&&a.jsx(ze,{order:3,py:"lg",ta:"center",children:"Sign in again to create a new project"})]})}function wae(){const e=Fn(),t=Fr(),[n,r]=v.useState(),[i,s]=v.useState(),[c,u]=v.useState();return v.useEffect(()=>{const f=Object.fromEntries(new URLSearchParams(t.search).entries());r(f.resourceType),s(f.query),u(JSON.parse(f.fields))},[t]),!n||!i||!c?null:a.jsx(HJ,{resourceType:n,checkboxesEnabled:!0,query:i,fields:c,onClick:f=>e(`/${n}/${f.resource.id}`)?.catch(console.error),onAuxClick:f=>window.open(`/${n}/${f.resource.id}`,"_blank"),onBulk:f=>{e(`/bulk/${n}?ids=${f.join(",")}`)?.catch(console.error)}})}function Cae(){const{id:e,secret:t}=Yt(),n=Re(),[r,i]=v.useState(),[s,c]=v.useState(!1),u=Ms(r,void 0);return a.jsxs(lt,{width:450,children:[a.jsx(xr,{issues:u}),a.jsxs(pt,{onSubmit:()=>{i(void 0);const f={id:e,secret:t};n.post("auth/verifyemail",f).then(()=>c(!0)).catch(h=>i(rn(h)))},children:[a.jsxs(ar,{direction:"column",align:"center",justify:"center",children:[a.jsx(Wi,{size:32}),a.jsx(ze,{children:"Email address verification required"})]}),!s&&a.jsxs(Ne,{children:[a.jsx("p",{children:"In order to sign in, click the button below to verify your ability to receive email at the address this link was sent to."}),a.jsx(xe,{justify:"flex-end",mt:"xl",children:a.jsx(Me,{type:"submit",children:"Verify email"})})]}),s&&a.jsxs("div",{"data-testid":"success",children:["Email verified. You can now ",a.jsx(jt,{to:"/signin",children:"sign in"}),"."]})]})]})}function Eae(){return a.jsx(Sne,{children:a.jsxs(Be,{errorElement:a.jsx(Jie,{}),children:[a.jsx(Be,{path:"/signin",element:a.jsx(jae,{})}),a.jsx(Be,{path:"/oauth",element:a.jsx(poe,{})}),a.jsx(Be,{path:"/resetpassword",element:a.jsx(goe,{})}),a.jsx(Be,{path:"/setpassword/:id/:secret",element:a.jsx(Sae,{})}),a.jsx(Be,{path:"/verifyemail/:id/:secret",element:a.jsx(Cae,{})}),a.jsx(Be,{path:"/register",element:a.jsx(moe,{})}),a.jsx(Be,{path:"/changepassword",element:a.jsx(Yie,{})}),a.jsx(Be,{path:"/security",element:a.jsx(bae,{})}),a.jsx(Be,{path:"/mfa",element:a.jsx(doe,{})}),a.jsx(Be,{path:"/batch",element:a.jsx(Wie,{})}),a.jsx(Be,{path:"/bulk/:resourceType",element:a.jsx(Qie,{})}),a.jsx(Be,{path:"/smart",element:a.jsx(wae,{})}),a.jsx(Be,{path:"/forms/:id",element:a.jsx(Zie,{})}),a.jsx(Be,{path:"/admin/super",element:a.jsx(Lre,{})}),a.jsx(Be,{path:"/admin/super/asyncjob/:tab",element:a.jsx(C_,{})}),a.jsx(Be,{path:"/admin/super/asyncjob",element:a.jsx(C_,{})}),a.jsx(Be,{path:"/admin/super/db/:tab",element:a.jsx(j_,{})}),a.jsx(Be,{path:"/admin/super/db",element:a.jsx(j_,{})}),a.jsx(Be,{path:"/admin/config",element:a.jsx(Cre,{})}),a.jsxs(Be,{path:"/admin",element:a.jsx(Tre,{}),children:[a.jsx(Be,{path:"bots/new",element:a.jsx(sre,{})}),a.jsx(Be,{path:"bots",element:a.jsx(ore,{})}),a.jsx(Be,{path:"clients/new",element:a.jsx(lre,{})}),a.jsx(Be,{path:"clients",element:a.jsx(are,{})}),a.jsx(Be,{path:"details",element:a.jsx(w_,{})}),a.jsx(Be,{path:"invite",element:a.jsx(wre,{})}),a.jsx(Be,{path:"patients",element:a.jsx(xne,{to:"/admin/users",replace:!0})}),a.jsx(Be,{path:"users",element:a.jsx(Vre,{})}),a.jsx(Be,{path:"project",element:a.jsx(w_,{})}),a.jsx(Be,{path:"secrets",element:a.jsx(Rre,{})}),a.jsx(Be,{path:"sites",element:a.jsx(_re,{})})]}),a.jsx(Be,{path:"/lab/assays",element:a.jsx(coe,{})}),a.jsx(Be,{path:"/lab/panels",element:a.jsx(uoe,{})}),a.jsxs(Be,{path:"/:resourceType/new",element:a.jsx(Xie,{}),children:[a.jsx(Be,{index:!0,element:a.jsx(Tx,{})}),a.jsx(Be,{path:"form",element:a.jsx(Tx,{})}),a.jsx(Be,{path:"json",element:a.jsx($oe,{})}),a.jsx(Be,{path:"profiles",element:a.jsx(Tx,{})})]}),a.jsxs(Be,{path:"/:resourceType/:id",element:a.jsx(mae,{}),children:[a.jsx(Be,{index:!0,element:a.jsx(H_,{})}),a.jsx(Be,{path:"apply",element:a.jsx(yoe,{})}),a.jsx(Be,{path:"apps",element:a.jsx(xoe,{})}),a.jsx(Be,{path:"event",element:a.jsx(Soe,{})}),a.jsx(Be,{path:"blame",element:a.jsx(joe,{})}),a.jsx(Be,{path:"bots",element:a.jsx(Xoe,{})}),a.jsx(Be,{path:"builder",element:a.jsx(koe,{})}),a.jsx(Be,{path:"checklist",element:a.jsx(Poe,{})}),a.jsx(Be,{path:"delete",element:a.jsx(Noe,{})}),a.jsx(Be,{path:"details",element:a.jsx(Loe,{})}),a.jsx(Be,{path:"edit",element:a.jsx(Ioe,{})}),a.jsx(Be,{path:"editor",element:a.jsx(Doe,{})}),a.jsxs(Be,{path:"history",children:[a.jsx(Be,{index:!0,element:a.jsx(F_,{})}),a.jsx(Be,{path:":versionId/:tab",element:a.jsx(vp,{})}),a.jsx(Be,{path:":versionId",element:a.jsx(vp,{})})]}),a.jsxs(Be,{path:"_history",children:[a.jsx(Be,{index:!0,element:a.jsx(F_,{})}),a.jsx(Be,{path:":versionId/:tab",element:a.jsx(vp,{})}),a.jsx(Be,{path:":versionId",element:a.jsx(vp,{})})]}),a.jsx(Be,{path:"json",element:a.jsx(Uoe,{})}),a.jsx(Be,{path:"preview",element:a.jsx(Woe,{})}),a.jsx(Be,{path:"responses",element:a.jsx(Zoe,{})}),a.jsx(Be,{path:"report",element:a.jsx(tae,{})}),a.jsx(Be,{path:"ranges",element:a.jsx(eae,{})}),a.jsx(Be,{path:"subscriptions",element:a.jsx(gae,{})}),a.jsx(Be,{path:"timeline",element:a.jsx(H_,{})}),a.jsx(Be,{path:"tools",element:a.jsx(xae,{})}),a.jsx(Be,{path:"profiles",element:a.jsx(Qoe,{})}),a.jsx(Be,{path:"export",element:a.jsx(zoe,{})})]}),a.jsx(Be,{path:"/:resourceType",element:a.jsx(U_,{})}),a.jsx(Be,{path:"/",element:a.jsx(U_,{})})]})})}function Tae(){const e=Re(),t=e.getUserConfiguration(),n=Fr(),[r]=Sg();return e.isLoading()?a.jsx(Ui,{}):a.jsx(cY,{logo:a.jsx(Wi,{size:24}),pathname:n.pathname,searchParams:r,version:Bk,menus:Rae(t),displayAddBookmark:!!t?.id,children:a.jsx(v.Suspense,{fallback:a.jsx(Ui,{}),children:a.jsx(Eae,{})})})}function Rae(e){const t=e?.menu?.map(n=>({title:n.title,links:n.link?.map(r=>({label:r.name,href:r.target,icon:_ae(r.target)}))||[]}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:a.jsx(NG,{})}]}),t}const q_={Patient:yW,Practitioner:TG,Organization:Bq,ServiceRequest:rW,DiagnosticReport:lW,Questionnaire:CG,Project:jG,admin:Nq,AccessPolicy:kG,Subscription:AW,batch:qG,Observation:BG};function _ae(e){if(e.includes("admin/super/db"))return a.jsx(iG,{});try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in q_){const n=q_[t];return a.jsx(n,{})}}catch{}}async function Dae(){const e=Bf(),t=new Vk({baseUrl:e.baseUrl,clientId:e.clientId,storagePrefix:"@medplum:",cacheTime:6e4,autoBatchTime:100,onUnauthenticated:()=>{window.location.pathname!=="/signin"&&window.location.pathname!=="/oauth"&&(window.location.href="/signin?next="+encodeURIComponent(window.location.pathname+window.location.search))}}),n={headings:{sizes:{h1:{fontSize:"1.125rem",fontWeight:"500",lineHeight:"2.0"}}},fontSizes:{xs:"0.6875rem",sm:"0.875rem",md:"0.875rem",lg:"1.0rem",xl:"1.125rem"}},r=Gne([{path:"*",element:a.jsx(Tae,{})}]),i=c=>r.navigate(c);Aee.createRoot(document.getElementById("root")).render(a.jsx(v.StrictMode,{children:a.jsx(kH,{medplum:t,navigate:i,children:a.jsxs(m2,{theme:n,children:[a.jsx(Pa,{position:"bottom-right"}),a.jsx(gne,{router:r})]})})}))}Dae().catch(console.error);
235
- //# sourceMappingURL=index-9rhutH6g.js.map
235
+ //# sourceMappingURL=index-zDrX6kYo.js.map