@medplum/app 4.3.0 → 4.3.2

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.
@@ -75,7 +75,7 @@ function p3(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
75
75
  allowNegative: `+s+`
76
76
  `),s=!1),Object.assign(Object.assign({},e),{allowNegative:s})}function e6(e){e=JL(e),e.decimalSeparator,e.allowedDecimalSeparators,e.thousandsGroupStyle;var t=e.suffix,n=e.allowNegative,r=e.allowLeadingZeros,i=e.onKeyDown;i===void 0&&(i=Lo);var s=e.onBlur;s===void 0&&(s=Lo);var c=e.thousandSeparator,u=e.decimalScale,f=e.fixedDecimalScale,p=e.prefix;p===void 0&&(p="");var m=e.defaultValue,g=e.value,y=e.valueIsNumericString,b=e.onValueChange,S=jD(e,["decimalSeparator","allowedDecimalSeparators","thousandsGroupStyle","suffix","allowNegative","allowLeadingZeros","onKeyDown","onBlur","thousandSeparator","decimalScale","fixedDecimalScale","prefix","defaultValue","value","valueIsNumericString","onValueChange"]),j=Mp(e),C=j.decimalSeparator,T=j.allowedDecimalSeparators,D=function(P){return GC(P,e)},E=function(P,L){return XL(P,L,e)},R=ic(g)?m:g,A=y??KL(R,p,t);ic(g)?ic(m)||(A=A||typeof m=="number"):A=A||typeof g=="number";var k=function(P){return CD(P)?P:(typeof P=="number"&&(P=RD(P)),A&&typeof u=="number"?HC(P,u,!!f):P)},M=AD(k(g),k(m),!!A,D,E,b),I=M[0],$=I.numAsString,V=I.formattedValue,Y=M[1],Q=function(P){var L=P.target,z=P.key,H=L.selectionStart,O=L.selectionEnd,U=L.value;if(U===void 0&&(U=""),(z==="Backspace"||z==="Delete")&&O<p.length){P.preventDefault();return}if(H!==O){i(P);return}z==="Backspace"&&U[0]==="-"&&H===p.length+1&&n&&Es(L,1),u&&f&&(z==="Backspace"&&U[H-1]===C?(Es(L,H-1),P.preventDefault()):z==="Delete"&&U[H]===C&&P.preventDefault()),T!=null&&T.includes(z)&&U[H]===C&&Es(L,H+1);var X=c===!0?",":c;z==="Backspace"&&U[H-1]===X&&Es(L,H-1),z==="Delete"&&U[H]===X&&Es(L,H+1),i(P)},J=function(P){var L=$;if(L.match(/\d/g)||(L=""),r||(L=LL(L)),f&&u&&(L=HC(L,u,f)),L!==$){var z=GC(L,e);Y({formattedValue:z,value:L,floatValue:parseFloat(L)},{event:P,source:nd.event})}s(P)},G=function(P){return P===C?!0:rd(P)},K=function(P){var L=P.currentValue,z=P.lastValue,H=P.formattedValue,O=P.currentValueIndex,U=P.formattedValueIndex,X=L[O],ee=H[U],Se=DD(z,L),be=Se.to,xe=function(qe){return E(qe).indexOf(".")+p.length};return g===0&&f&&u&&L[be.start]===C&&xe(L)<O&&xe(H)>U?!1:O>=be.start&&O<be.end&&T&&T.includes(X)&&ee===C?!0:X===ee};return Object.assign(Object.assign({},S),{value:V,valueIsNumericString:!1,isValidInputCharacter:G,isCharacterSame:K,onValueChange:Y,format:D,removeFormatting:E,getCaretBoundary:function(P){return ZL(P,e)},onKeyDown:Q,onBlur:J})}function t6(e){var t=e6(e);return En.createElement(QL,Object.assign({},t))}function QC({direction:e,style:t,...n}){return o.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:o.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"})})}var Ay={root:"m_e2f5cd4e",controls:"m_95e17d22",control:"m_80b4b171"};const n6=/^(0\.0*|-0(\.0*)?)$/,r6=/^-?0\d+(\.\d+)?\.?$/;function _y(e){return typeof e=="string"&&e!==""&&!Number.isNaN(Number(e))}function Uv(e){return typeof e=="number"?e<Number.MAX_SAFE_INTEGER:e===""||_y(e)&&Number(e)<Number.MAX_SAFE_INTEGER}function i6(e){return e.toString().replace(".","").length}function a6(e,t){return(typeof e=="number"?e<Number.MAX_SAFE_INTEGER:!Number.isNaN(Number(e)))&&!Number.isNaN(e)&&i6(t)<14&&t!==""}function WC(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 o6={step:1,clampBehavior:"blur",allowDecimal:!0,allowNegative:!0,withKeyboardEvents:!0,allowLeadingZeros:!0,trimLeadingZeroesOnBlur:!0,startValue:0},s6=(e,{size:t})=>({controls:{"--ni-chevron-size":rt(t,"ni-chevron-size")}});function l6(e,t,n){const r=e.toString().replace(/^0+/,""),i=parseFloat(r);return Number.isNaN(i)?r:i>Number.MAX_SAFE_INTEGER?t!==void 0?String(t):r:mh(i,n,t)}const Ip=ve((e,t)=>{const n=se("NumberInput",o6,e),{className:r,classNames:i,styles:s,unstyled:c,vars:u,onChange:f,onValueChange:p,value:m,defaultValue:g,max:y,min:b,step:S,hideControls:j,rightSection:C,isAllowed:T,clampBehavior:D,onBlur:E,allowDecimal:R,decimalScale:A,onKeyDown:k,onKeyDownCapture:M,handlersRef:I,startValue:$,disabled:V,rightSectionPointerEvents:Y,allowNegative:Q,readOnly:J,size:G,rightSectionWidth:K,stepHoldInterval:P,stepHoldDelay:L,allowLeadingZeros:z,withKeyboardEvents:H,trimLeadingZeroesOnBlur:O,...U}=n,X=Ie({name:"NumberInput",classes:Ay,props:n,classNames:i,styles:s,unstyled:c,vars:u,varsResolver:s6}),{resolvedClassNames:ee,resolvedStyles:Se}=Ys({classNames:i,styles:s,props:n}),[be,xe]=Yn({value:m,defaultValue:g,finalValue:"",onChange:f}),qe=L!==void 0&&P!==void 0,Me=v.useRef(null),tt=v.useRef(null),ke=v.useRef(0),vt=(we,$e)=>{$e.source==="event"&&xe(a6(we.floatValue,we.value)&&!n6.test(we.value)&&!(z&&r6.test(we.value))?we.floatValue:we.value),p==null||p(we,$e)},It=we=>{const $e=String(we).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return $e?Math.max(0,($e[1]?$e[1].length:0)-($e[2]?+$e[2]:0)):0},Lt=we=>{Me.current&&typeof we<"u"&&Me.current.setSelectionRange(we,we)},gt=v.useRef(Th);gt.current=()=>{if(!Uv(be))return;let we;const $e=It(be),yt=It(S),ft=Math.max($e,yt),Gt=10**ft;if(!_y(be)&&(typeof be!="number"||Number.isNaN(be)))we=mh($,b,y);else if(y!==void 0){const un=(Math.round(Number(be)*Gt)+Math.round(S*Gt))/Gt;we=un<=y?un:y}else we=(Math.round(Number(be)*Gt)+Math.round(S*Gt))/Gt;const kt=we.toFixed(ft);xe(parseFloat(kt)),p==null||p({floatValue:parseFloat(kt),formattedValue:kt,value:kt},{source:"increment"}),setTimeout(()=>{var un;return Lt((un=Me.current)==null?void 0:un.value.length)},0)};const At=v.useRef(Th);At.current=()=>{if(!Uv(be))return;let we;const $e=b!==void 0?b:Q?Number.MIN_SAFE_INTEGER:0,yt=It(be),ft=It(S),Gt=Math.max(yt,ft),kt=10**Gt;if(!_y(be)&&typeof be!="number"||Number.isNaN(be))we=mh($,$e,y);else{const wt=(Math.round(Number(be)*kt)-Math.round(S*kt))/kt;we=$e!==void 0&&wt<$e?$e:wt}const un=we.toFixed(Gt);xe(parseFloat(un)),p==null||p({floatValue:parseFloat(un),formattedValue:un,value:un},{source:"decrement"}),setTimeout(()=>{var wt;return Lt((wt=Me.current)==null?void 0:wt.value.length)},0)};const nn=we=>{k==null||k(we),!(J||!H)&&(we.key==="ArrowUp"&&(we.preventDefault(),gt.current()),we.key==="ArrowDown"&&(we.preventDefault(),At.current()))},Ee=we=>{if(M==null||M(we),we.key==="Backspace"){const $e=Me.current;$e.selectionStart===0&&$e.selectionStart===$e.selectionEnd&&(we.preventDefault(),window.setTimeout(()=>Lt(0),0))}},De=we=>{let $e=be;D==="blur"&&typeof $e=="number"&&($e=mh($e,b,y)),O&&typeof $e=="string"&&It($e)<15&&($e=l6($e,y,b)),be!==$e&&xe($e),E==null||E(we)};Zu(I,{increment:gt.current,decrement:At.current});const Qe=we=>{we?gt.current():At.current(),ke.current+=1},Re=we=>{if(Qe(we),qe){const $e=typeof P=="number"?P:P(ke.current);tt.current=window.setTimeout(()=>Re(we),$e)}},me=(we,$e)=>{var yt;we.preventDefault(),(yt=Me.current)==null||yt.focus(),Qe($e),qe&&(tt.current=window.setTimeout(()=>Re($e),L))},ge=()=>{tt.current&&window.clearTimeout(tt.current),tt.current=null,ke.current=0},Pe=o.jsxs("div",{...X("controls"),children:[o.jsx(tr,{...X("control"),tabIndex:-1,"aria-hidden":!0,disabled:V||typeof be=="number"&&y!==void 0&&be>=y,mod:{direction:"up"},onMouseDown:we=>we.preventDefault(),onPointerDown:we=>{me(we,!0)},onPointerUp:ge,onPointerLeave:ge,children:o.jsx(QC,{direction:"up"})}),o.jsx(tr,{...X("control"),tabIndex:-1,"aria-hidden":!0,disabled:V||typeof be=="number"&&b!==void 0&&be<=b,mod:{direction:"down"},onMouseDown:we=>we.preventDefault(),onPointerDown:we=>{me(we,!1)},onPointerUp:ge,onPointerLeave:ge,children:o.jsx(QC,{direction:"down"})})]});return o.jsx(Pr,{component:t6,allowNegative:Q,className:Ut(Ay.root,r),size:G,...U,readOnly:J,disabled:V,value:be,getInputRef:$n(t,Me),onValueChange:vt,rightSection:j||J||!Uv(be)?C:C||Pe,classNames:ee,styles:Se,unstyled:c,__staticSelector:"NumberInput",decimalScale:R?A:0,onKeyDown:nn,onKeyDownCapture:Ee,rightSectionPointerEvents:Y??(V?"none":void 0),rightSectionWidth:K??`var(--ni-right-section-width-${G||"sm"})`,allowLeadingZeros:z,onBlur:De,isAllowed:we=>D==="strict"?T?T(we)&&WC(we.floatValue,b,y):WC(we.floatValue,b,y):T?T(we):!0})});Ip.classes={...Pr.classes,...Ay};Ip.displayName="@mantine/core/NumberInput";const[c6,Lp]=vr("Pagination.Root component was not found in tree");var bd={root:"m_4addd315",control:"m_326d024a",dots:"m_4ad7767d"};const u6={withPadding:!0},Sd=ve((e,t)=>{const n=se("PaginationControl",u6,e),{classNames:r,className:i,style:s,styles:c,vars:u,active:f,disabled:p,withPadding:m,mod:g,...y}=n,b=Lp(),S=p||b.disabled;return o.jsx(tr,{ref:t,disabled:S,mod:[{active:f,disabled:S,"with-padding":m},g],...b.getStyles("control",{className:i,style:s,classNames:r,styles:c,active:!S}),...y})});Sd.classes=bd;Sd.displayName="@mantine/core/PaginationControl";function wd({style:e,children:t,path:n,...r}){return o.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:o.jsx("path",{d:n,fill:"currentColor"})})}const d6=e=>o.jsx(wd,{...e,path:"M8.781 8l-3.3-3.3.943-.943L10.667 8l-4.243 4.243-.943-.943 3.3-3.3z"}),f6=e=>o.jsx(wd,{...e,path:"M7.219 8l3.3 3.3-.943.943L5.333 8l4.243-4.243.943.943-3.3 3.3z"}),h6=e=>o.jsx(wd,{...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"}),p6=e=>o.jsx(wd,{...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"}),m6=e=>o.jsx(wd,{...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"}),g6={icon:m6},zp=ve((e,t)=>{const n=se("PaginationDots",g6,e),{classNames:r,className:i,style:s,styles:c,vars:u,icon:f,...p}=n,m=Lp(),g=f;return o.jsx(ce,{ref:t,...m.getStyles("dots",{className:i,style:s,styles:c,classNames:r}),...p,children:o.jsx(g,{style:{width:"calc(var(--pagination-control-size) / 1.8)",height:"calc(var(--pagination-control-size) / 1.8)"}})})});zp.classes=bd;zp.displayName="@mantine/core/PaginationDots";function $p({icon:e,name:t,action:n,type:r}){const i={icon:e},s=v.forwardRef((c,u)=>{const{icon:f,...p}=se(t,i,c),m=f,g=Lp(),y=r==="next"?g.active===g.total:g.active===1;return o.jsx(Sd,{disabled:g.disabled||y,ref:u,onClick:g[n],withPadding:!1,...p,children:o.jsx(m,{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 _D=$p({icon:d6,name:"PaginationNext",action:"onNext",type:"next"}),kD=$p({icon:f6,name:"PaginationPrevious",action:"onPrevious",type:"previous"}),PD=$p({icon:h6,name:"PaginationFirst",action:"onFirst",type:"previous"}),ND=$p({icon:p6,name:"PaginationLast",action:"onLast",type:"next"});function A0({dotsIcon:e}){const t=Lp(),n=t.range.map((r,i)=>{var s,c,u;return r==="dots"?o.jsx(zp,{icon:e},i):o.jsx(Sd,{active:r===t.active,"aria-current":r===t.active?"page":void 0,onClick:()=>t.onChange(r),disabled:t.disabled,...(s=t.getItemProps)==null?void 0:s.call(t,r),children:((u=(c=t.getItemProps)==null?void 0:c.call(t,r))==null?void 0:u.children)??r},i)});return o.jsx(o.Fragment,{children:n})}A0.displayName="@mantine/core/PaginationItems";const v6={siblings:1,boundaries:1},y6=(e,{size:t,radius:n,color:r,autoContrast:i})=>({root:{"--pagination-control-radius":n===void 0?void 0:Vt(n),"--pagination-control-size":rt(t,"pagination-control-size"),"--pagination-control-fz":On(t),"--pagination-active-bg":r?Ht(r,e):void 0,"--pagination-active-color":Ks(i,e)?Ga({color:r,theme:e,autoContrast:i}):void 0}}),Up=ve((e,t)=>{const n=se("PaginationRoot",v6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,total:p,value:m,defaultValue:g,onChange:y,disabled:b,siblings:S,boundaries:j,color:C,radius:T,onNextPage:D,onPreviousPage:E,onFirstPage:R,onLastPage:A,getItemProps:k,autoContrast:M,...I}=n,$=Ie({name:"Pagination",classes:bd,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:y6}),{range:V,setPage:Y,next:Q,previous:J,active:G,first:K,last:P}=TN({page:m,initialPage:g,onChange:y,total:p,siblings:S,boundaries:j}),L=Rr(D,Q),z=Rr(E,J),H=Rr(R,K),O=Rr(A,P);return o.jsx(c6,{value:{total:p,range:V,active:G,disabled:b,getItemProps:k,onChange:Y,onNext:L,onPrevious:z,onFirst:H,onLast:O,getStyles:$},children:o.jsx(ce,{ref:t,...$("root"),...I})})});Up.classes=bd;Up.displayName="@mantine/core/PaginationRoot";const x6={withControls:!0,withPages:!0,siblings:1,boundaries:1,gap:8},$i=ve((e,t)=>{const n=se("Pagination",x6,e),{withEdges:r,withControls:i,getControlProps:s,nextIcon:c,previousIcon:u,lastIcon:f,firstIcon:p,dotsIcon:m,total:g,gap:y,hideWithOnePage:b,withPages:S,...j}=n;return g<=0||b&&g===1?null:o.jsx(Up,{ref:t,total:g,...j,children:o.jsxs(je,{gap:y,children:[r&&o.jsx(PD,{icon:p,...s==null?void 0:s("first")}),i&&o.jsx(kD,{icon:u,...s==null?void 0:s("previous")}),S&&o.jsx(A0,{dotsIcon:m}),i&&o.jsx(_D,{icon:c,...s==null?void 0:s("next")}),r&&o.jsx(ND,{icon:f,...s==null?void 0:s("last")})]})})});$i.classes=bd;$i.displayName="@mantine/core/Pagination";$i.Root=Up;$i.Control=Sd;$i.Dots=zp;$i.First=PD;$i.Last=ND;$i.Next=_D;$i.Previous=kD;$i.Items=A0;const b6=({reveal:e})=>o.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:o.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"})});var ky={root:"m_f61ca620",input:"m_ccf8da4c",innerInput:"m_f2d85dd2",visibilityToggle:"m_b1072d44"};const S6={visibilityToggleIcon:b6},w6=(e,{size:t})=>({root:{"--psi-icon-size":rt(t,"psi-icon-size"),"--psi-button-size":rt(t,"psi-button-size")}}),Ni=ve((e,t)=>{const n=se("PasswordInput",S6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,required:p,error:m,leftSection:g,disabled:y,id:b,variant:S,inputContainer:j,description:C,label:T,size:D,errorProps:E,descriptionProps:R,labelProps:A,withAsterisk:k,inputWrapperOrder:M,wrapperProps:I,radius:$,rightSection:V,rightSectionWidth:Y,rightSectionPointerEvents:Q,leftSectionWidth:J,visible:G,defaultVisible:K,onVisibilityChange:P,visibilityToggleIcon:L,visibilityToggleButtonProps:z,rightSectionProps:H,leftSectionProps:O,leftSectionPointerEvents:U,withErrorStyles:X,mod:ee,...Se}=n,be=yr(b),[xe,qe]=Yn({value:G,defaultValue:K,finalValue:!1,onChange:P}),Me=()=>qe(!xe),tt=Ie({name:"PasswordInput",classes:ky,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:w6}),{resolvedClassNames:ke,resolvedStyles:vt}=Ys({classNames:r,styles:c,props:n}),{styleProps:It,rest:Lt}=Qa(Se),gt=L,At=(E==null?void 0:E.id)||`${be}-error`,nn=(R==null?void 0:R.id)||`${be}-description`,Qe=`${!!m&&typeof m!="boolean"?At:""} ${!!C?nn:""}`,Re=Qe.trim().length>0?Qe.trim():void 0,me=o.jsx(_n,{...tt("visibilityToggle"),disabled:y,radius:$,"aria-hidden":!z,tabIndex:-1,...z,variant:(z==null?void 0:z.variant)??"subtle",color:"gray",unstyled:u,onTouchEnd:ge=>{var Pe;ge.preventDefault(),(Pe=z==null?void 0:z.onTouchEnd)==null||Pe.call(z,ge),Me()},onMouseDown:ge=>{var Pe;ge.preventDefault(),(Pe=z==null?void 0:z.onMouseDown)==null||Pe.call(z,ge),Me()},onKeyDown:ge=>{var Pe;(Pe=z==null?void 0:z.onKeyDown)==null||Pe.call(z,ge),ge.key===" "&&(ge.preventDefault(),Me())},children:o.jsx(gt,{reveal:xe})});return o.jsx(mn.Wrapper,{required:p,id:be,label:T,error:m,description:C,size:D,classNames:ke,styles:vt,__staticSelector:"PasswordInput",unstyled:u,withAsterisk:k,inputWrapperOrder:M,inputContainer:j,variant:S,labelProps:{...A,htmlFor:be},descriptionProps:{...R,id:nn},errorProps:{...E,id:At},mod:ee,...tt("root"),...It,...I,children:o.jsx(mn,{component:"div",error:m,leftSection:g,size:D,classNames:{...ke,input:Ut(ky.input,ke.input)},styles:vt,radius:$,disabled:y,__staticSelector:"PasswordInput",rightSectionWidth:Y,rightSection:V??me,variant:S,unstyled:u,leftSectionWidth:J,rightSectionPointerEvents:Q||"all",rightSectionProps:H,leftSectionProps:O,leftSectionPointerEvents:U,withAria:!1,withErrorStyles:X,children:o.jsx("input",{required:p,"data-invalid":!!m||void 0,"data-with-left-section":!!g||void 0,...tt("innerInput"),disabled:y,id:be,ref:t,...Lt,"aria-describedby":Re,autoComplete:Lt.autoComplete||"off",type:xe?"text":"password"})})})});Ni.classes={...Pr.classes,...ky};Ni.displayName="@mantine/core/PasswordInput";const[j6,OD]=Ha(),[C6,E6]=Ha();var MD={card:"m_9dc8ae12"};const T6={withBorder:!0},R6=(e,{radius:t})=>({card:{"--card-radius":Vt(t)}}),_0=ve((e,t)=>{const n=se("RadioCard",T6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,checked:p,mod:m,withBorder:g,value:y,onClick:b,name:S,onKeyDown:j,...C}=n,T=Ie({name:"RadioCard",classes:MD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:R6,rootSelector:"card"}),{dir:D}=Zs(),E=OD(),R=typeof p=="boolean"?p:(E==null?void 0:E.value)===y||!1,A=S||(E==null?void 0:E.name),k=M=>{if(j==null||j(M),["ArrowDown","ArrowUp","ArrowLeft","ArrowRight"].includes(M.nativeEvent.code)){M.preventDefault();const I=Array.from(document.querySelectorAll(`[role="radio"][name="${A||"__mantine"}"]`)),$=I.findIndex(Q=>Q===M.target),V=$+1>=I.length?0:$+1,Y=$-1<0?I.length-1:$-1;M.nativeEvent.code==="ArrowDown"&&(I[V].focus(),I[V].click()),M.nativeEvent.code==="ArrowUp"&&(I[Y].focus(),I[Y].click()),M.nativeEvent.code==="ArrowLeft"&&(I[D==="ltr"?Y:V].focus(),I[D==="ltr"?Y:V].click()),M.nativeEvent.code==="ArrowRight"&&(I[D==="ltr"?V:Y].focus(),I[D==="ltr"?V:Y].click())}};return o.jsx(C6,{value:{checked:R},children:o.jsx(tr,{ref:t,mod:[{"with-border":g,checked:R},m],...T("card"),...C,role:"radio","aria-checked":R,name:A,onClick:M=>{b==null||b(M),E==null||E.onChange(y||"")},onKeyDown:k})})});_0.displayName="@mantine/core/RadioCard";_0.classes=MD;const D6={},k0=ve((e,t)=>{const{value:n,defaultValue:r,onChange:i,size:s,wrapperProps:c,children:u,name:f,readOnly:p,...m}=se("RadioGroup",D6,e),g=yr(f),[y,b]=Yn({value:n,defaultValue:r,finalValue:"",onChange:i}),S=j=>!p&&b(typeof j=="string"?j:j.currentTarget.value);return o.jsx(j6,{value:{value:y,onChange:S,size:s,name:g},children:o.jsx(mn.Wrapper,{size:s,ref:t,...c,...m,labelElement:"div",__staticSelector:"RadioGroup",children:o.jsx(i0,{role:"radiogroup",children:u})})})});k0.classes=mn.Wrapper.classes;k0.displayName="@mantine/core/RadioGroup";function ID({size:e,style:t,...n}){return o.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 5 5",style:{width:le(e),height:le(e),...t},"aria-hidden":!0,...n,children:o.jsx("circle",{cx:"2.5",cy:"2.5",r:"2.5",fill:"currentColor"})})}var LD={indicator:"m_717d7ff6",icon:"m_3e4da632","indicator--outline":"m_2980836c"};const A6={icon:ID},_6=(e,{radius:t,color:n,size:r,iconColor:i,variant:s,autoContrast:c})=>{const u=hi({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":rt(r,"radio-size"),"--radio-radius":t===void 0?void 0:Vt(t),"--radio-color":s==="outline"?f:Ht(n,e),"--radio-icon-size":rt(r,"radio-icon-size"),"--radio-icon-color":i?Ht(i,e):Ks(c,e)?Ga({color:n,theme:e,autoContrast:c}):void 0}}},P0=ve((e,t)=>{const n=se("RadioIndicator",A6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,icon:p,radius:m,color:g,iconColor:y,autoContrast:b,checked:S,mod:j,variant:C,disabled:T,...D}=n,E=p,R=Ie({name:"RadioIndicator",classes:LD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:_6,rootSelector:"indicator"}),A=E6(),k=typeof S=="boolean"?S:(A==null?void 0:A.checked)||!1;return o.jsx(ce,{ref:t,...R("indicator",{variant:C}),variant:C,mod:[{checked:k,disabled:T},j],...D,children:o.jsx(E,{...R("icon")})})});P0.displayName="@mantine/core/RadioIndicator";P0.classes=LD;var zD={root:"m_f3f1af94",inner:"m_89c4f5e4",icon:"m_f3ed6b2b",radio:"m_8a3dbb89","radio--outline":"m_1bfe9d39"};const k6={labelPosition:"right"},P6=(e,{size:t,radius:n,color:r,iconColor:i,variant:s,autoContrast:c})=>{const u=hi({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":rt(t,"radio-size"),"--radio-radius":n===void 0?void 0:Vt(n),"--radio-color":s==="outline"?f:Ht(r,e),"--radio-icon-color":i?Ht(i,e):Ks(c,e)?Ga({color:r,theme:e,autoContrast:c}):void 0,"--radio-icon-size":rt(t,"radio-icon-size")}}},Us=ve((e,t)=>{const n=se("Radio",k6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,id:p,size:m,label:g,labelPosition:y,description:b,error:S,radius:j,color:C,variant:T,disabled:D,wrapperProps:E,icon:R=ID,rootRef:A,iconColor:k,onChange:M,mod:I,...$}=n,V=Ie({name:"Radio",classes:zD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:P6}),Y=OD(),Q=(Y==null?void 0:Y.size)??m,J=n.size?m:Q,{styleProps:G,rest:K}=Qa($),P=yr(p),L=Y?{checked:Y.value===K.value,name:K.name??Y.name,onChange:z=>{Y.onChange(z),M==null||M(z)}}:{};return o.jsx(Sp,{...V("root"),__staticSelector:"Radio",__stylesApiProps:n,id:P,size:J,labelPosition:y,label:g,description:b,error:S,disabled:D,classNames:r,styles:c,unstyled:u,"data-checked":L.checked||void 0,variant:T,ref:A,mod:I,...G,...E,children:o.jsxs(ce,{...V("inner"),mod:{"label-position":y},children:[o.jsx(ce,{...V("radio",{focusable:!0,variant:T}),onChange:M,...K,...L,component:"input",mod:{error:!!S},ref:t,id:P,disabled:D,type:"radio"}),o.jsx(R,{...V("icon"),"aria-hidden":!0})]})})});Us.classes=zD;Us.displayName="@mantine/core/Radio";Us.Group=k0;Us.Card=_0;Us.Indicator=P0;const N6={duration:100,transition:"fade"};function O6(e,t){return{...N6,...t,...e}}function M6({offset:e,position:t,defaultOpened:n}){const[r,i]=v.useState(n),s=v.useRef(null),{x:c,y:u,elements:f,refs:p,update:m,placement:g}=kx({placement:t,middleware:[Rx({crossAxis:!0,padding:5,rootBoundary:"document"})]}),y=g.includes("right")?e:t.includes("left")?e*-1:0,b=g.includes("bottom")?e:t.includes("top")?e*-1:0,S=v.useCallback(({clientX:j,clientY:C})=>{p.setPositionReference({getBoundingClientRect(){return{width:0,height:0,x:j,y:C,left:j+y,top:C+b,right:j,bottom:C}}})},[f.reference]);return v.useEffect(()=>{if(p.floating.current){const j=s.current;j.addEventListener("mousemove",S);const C=Ia(p.floating.current);return C.forEach(T=>{T.addEventListener("scroll",m)}),()=>{j.removeEventListener("mousemove",S),C.forEach(T=>{T.removeEventListener("scroll",m)})}}},[f.reference,p.floating.current,m,S,r]),{handleMouseMove:S,x:c,y:u,opened:r,setOpened:i,boundaryRef:s,floating:p.setFloating}}var Bp={tooltip:"m_1b3c8819",arrow:"m_f898399f"};const I6={refProp:"ref",withinPortal:!0,offset:10,defaultOpened:!1,position:"right",zIndex:Wr("popover")},L6=(e,{radius:t,color:n})=>({tooltip:{"--tooltip-radius":t===void 0?void 0:Vt(t),"--tooltip-bg":n?Ht(n,e):void 0,"--tooltip-color":n?"var(--mantine-color-white)":void 0}}),N0=ve((e,t)=>{const n=se("TooltipFloating",I6,e),{children:r,refProp:i,withinPortal:s,style:c,className:u,classNames:f,styles:p,unstyled:m,radius:g,color:y,label:b,offset:S,position:j,multiline:C,zIndex:T,disabled:D,defaultOpened:E,variant:R,vars:A,portalProps:k,...M}=n,I=Sn(),$=Ie({name:"TooltipFloating",props:n,classes:Bp,className:u,style:c,classNames:f,styles:p,unstyled:m,rootSelector:"tooltip",vars:A,varsResolver:L6}),{handleMouseMove:V,x:Y,y:Q,opened:J,boundaryRef:G,floating:K,setOpened:P}=M6({offset:S,position:j,defaultOpened:E});if(!Fa(r))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 L=$n(G,sp(r),t),z=r.props,H=U=>{var X;(X=z.onMouseEnter)==null||X.call(z,U),V(U),P(!0)},O=U=>{var X;(X=z.onMouseLeave)==null||X.call(z,U),P(!1)};return o.jsxs(o.Fragment,{children:[o.jsx(Go,{...k,withinPortal:s,children:o.jsx(ce,{...M,...$("tooltip",{style:{...AR(c,I),zIndex:T,display:!D&&J?"block":"none",top:(Q&&Math.round(Q))??"",left:(Y&&Math.round(Y))??""}}),variant:R,ref:K,mod:{multiline:C},children:b})}),v.cloneElement(r,{...z,[i]:L,onMouseEnter:H,onMouseLeave:O})]})});N0.classes=Bp;N0.displayName="@mantine/core/TooltipFloating";const $D=v.createContext(!1),z6=$D.Provider,$6=()=>v.useContext($D),U6={openDelay:0,closeDelay:0};function O0(e){const{openDelay:t,closeDelay:n,children:r}=se("TooltipGroup",U6,e);return o.jsx(z6,{value:!0,children:o.jsx(m9,{delay:{open:t,close:n},children:r})})}O0.displayName="@mantine/core/TooltipGroup";O0.extend=e=>e;function B6(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 V6(e){const t=B6(e.middlewares),n=[WR(e.offset)];return t.shift&&n.push(Rx(typeof t.shift=="boolean"?{padding:8}:{padding:8,...t.shift})),t.flip&&n.push(typeof t.flip=="boolean"?Ph():Ph(t.flip)),n.push(YR({element:e.arrowRef,padding:e.arrowOffset})),t.inline?n.push(typeof t.inline=="boolean"?Wu():Wu(t.inline)):e.inline&&n.push(Wu()),n}function F6(e){var k,M,I;const[t,n]=v.useState(e.defaultOpened),i=typeof e.opened=="boolean"?e.opened:t,s=$6(),c=yr(),u=v.useCallback($=>{n($),$&&D(c)},[c]),{x:f,y:p,context:m,refs:g,update:y,placement:b,middlewareData:{arrow:{x:S,y:j}={}}}=kx({strategy:e.strategy,placement:e.position,open:i,onOpenChange:u,middleware:V6(e)}),{delay:C,currentId:T,setCurrentId:D}=g9(m,{id:c}),{getReferenceProps:E,getFloatingProps:R}=j9([h9(m,{enabled:(k=e.events)==null?void 0:k.hover,delay:s?C:{open:e.openDelay,close:e.closeDelay},mouseOnly:!((M=e.events)!=null&&M.touch)}),w9(m,{enabled:(I=e.events)==null?void 0:I.focus,visibleOnly:!0}),E9(m,{role:"tooltip"}),b9(m,{enabled:typeof e.opened>"u"})]);S2({opened:i,position:e.position,positionDependencies:e.positionDependencies,floating:{refs:g,update:y}}),za(()=>{var $;($=e.onPositionChange)==null||$.call(e,b)},[b]);const A=i&&T&&T!==c;return{x:f,y:p,arrowX:S,arrowY:j,reference:g.setReference,floating:g.setFloating,getFloatingProps:R,getReferenceProps:E,isGroupPhase:A,opened:i,placement:b}}const YC={position:"top",refProp:"ref",withinPortal:!0,inline:!1,defaultOpened:!1,arrowSize:4,arrowOffset:5,arrowRadius:0,arrowPosition:"side",offset:5,transitionProps:{duration:100,transition:"fade"},events:{hover:!0,focus:!1,touch:!1},zIndex:Wr("popover"),positionDependencies:[],middlewares:{flip:!0,shift:!0,inline:!1}},H6=(e,{radius:t,color:n})=>({tooltip:{"--tooltip-radius":t===void 0?void 0:Vt(t),"--tooltip-bg":n?Ht(n,e):void 0,"--tooltip-color":n?"var(--mantine-color-white)":void 0}}),el=ve((e,t)=>{const n=se("Tooltip",YC,e),{children:r,position:i,refProp:s,label:c,openDelay:u,closeDelay:f,onPositionChange:p,opened:m,defaultOpened:g,withinPortal:y,radius:b,color:S,classNames:j,styles:C,unstyled:T,style:D,className:E,withArrow:R,arrowSize:A,arrowOffset:k,arrowRadius:M,arrowPosition:I,offset:$,transitionProps:V,multiline:Y,events:Q,zIndex:J,disabled:G,positionDependencies:K,onClick:P,onMouseEnter:L,onMouseLeave:z,inline:H,variant:O,keepMounted:U,vars:X,portalProps:ee,mod:Se,floatingStrategy:be,middlewares:xe,...qe}=se("Tooltip",YC,n),{dir:Me}=Zs(),tt=v.useRef(null),ke=F6({position:p2(Me,i),closeDelay:f,openDelay:u,onPositionChange:p,opened:m,defaultOpened:g,events:Q,arrowRef:tt,arrowOffset:k,offset:typeof $=="number"?$+(R?A/2:0):$,positionDependencies:[...K,r],inline:H,strategy:be,middlewares:xe}),vt=Ie({name:"Tooltip",props:n,classes:Bp,className:E,style:D,classNames:j,styles:C,unstyled:T,rootSelector:"tooltip",vars:X,varsResolver:H6});if(!Fa(r))throw new Error("[@mantine/core] Tooltip component children should be an element or a component that accepts ref, fragments, strings, numbers and other primitive values are not supported");const It=$n(ke.reference,sp(r),t),Lt=O6(V,{duration:100,transition:"fade"}),gt=r.props;return o.jsxs(o.Fragment,{children:[o.jsx(Go,{...ee,withinPortal:y,children:o.jsx(da,{...Lt,keepMounted:U,mounted:!G&&!!ke.opened,duration:ke.isGroupPhase?10:Lt.duration,children:At=>o.jsxs(ce,{...qe,"data-fixed":be==="fixed"||void 0,variant:O,mod:[{multiline:Y},Se],...ke.getFloatingProps({ref:ke.floating,className:vt("tooltip").className,style:{...vt("tooltip").style,...At,zIndex:J,top:ke.y??0,left:ke.x??0}}),children:[c,o.jsx(Mx,{ref:tt,arrowX:ke.arrowX,arrowY:ke.arrowY,visible:R,position:ke.placement,arrowSize:A,arrowOffset:k,arrowRadius:M,arrowPosition:I,...vt("arrow")})]})})}),v.cloneElement(r,ke.getReferenceProps({onClick:P,onMouseEnter:L,onMouseLeave:z,onMouseMove:n.onMouseMove,onPointerDown:n.onPointerDown,onPointerEnter:n.onPointerEnter,className:Ut(E,gt.className),...gt,[s]:It}))]})});el.classes=Bp;el.displayName="@mantine/core/Tooltip";el.Floating=N0;el.Group=O0;function q6({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 UD({size:e,value:t,offset:n,sum:r,thickness:i,root:s,color:c,lineRoundCaps:u,tooltip:f,getStyles:p,display:m,...g}){const y=Sn();return o.jsx(el.Floating,{disabled:!f,label:f,children:o.jsx(ce,{component:"circle",...g,...p("curve"),__vars:{"--curve-color":c?Ht(c,y):void 0},fill:"none",strokeLinecap:u?"round":"butt",...q6({sum:r,size:e,thickness:i,value:t,offset:n,root:s})})})}UD.displayName="@mantine/core/Curve";function G6({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=[],p=[];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}),p.push({...f[f.length-1],lineRoundCaps:!1}),f.length>2){p.push({...f[0],lineRoundCaps:r}),p.push({...f[f.length-2],lineRoundCaps:r});for(let m=1;m<=f.length-3;m+=1)p.push({...f[m],lineRoundCaps:!1})}else p.push({...f[0],lineRoundCaps:r});return p}var BD={root:"m_b32e4812",svg:"m_d43b5134",curve:"m_b1ca1fbf",label:"m_b23f9dc4"};function Q6(e,t){return Math.min(e||12,(t||120)/4)}const W6={size:120,thickness:12},Y6=(e,{size:t,thickness:n,transitionDuration:r})=>({root:{"--rp-size":le(t),"--rp-label-offset":le(n*2),"--rp-transition-duration":r?`${r}ms`:void 0}}),Vp=ve((e,t)=>{const n=se("RingProgress",W6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,label:p,sections:m,size:g,thickness:y,roundCaps:b,rootColor:S,transitionDuration:j,...C}=n,T=Ie({name:"RingProgress",classes:BD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:Y6}),D=Q6(y,g),E=G6({size:g,thickness:D,sections:m,renderRoundedLineCaps:b,rootColor:S}).map(({data:R,sum:A,root:k,lineRoundCaps:M,offset:I},$)=>v.createElement(UD,{...R,key:$,size:g,thickness:D,sum:A,offset:I,color:R==null?void 0:R.color,root:k,lineRoundCaps:M,getStyles:T}));return o.jsxs(ce,{...T("root"),size:g,ref:t,...C,children:[o.jsx("svg",{...T("svg"),children:E}),p&&o.jsx("div",{...T("label"),children:p})]})});Vp.classes=BD;Vp.displayName="@mantine/core/RingProgress";var VD={root:"m_cf365364",indicator:"m_9e182ccd",label:"m_1738fcb2",input:"m_1714d588",control:"m_69686b9b",innerLabel:"m_78882f40"};const K6={withItemsBorders:!0},X6=(e,{radius:t,color:n,transitionDuration:r,size:i,transitionTimingFunction:s})=>({root:{"--sc-radius":t===void 0?void 0:Vt(t),"--sc-color":n?Ht(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":rt(i,"sc-padding"),"--sc-font-size":On(i)}}),Fp=ve((e,t)=>{var Me,tt;const n=se("SegmentedControl",K6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,data:p,value:m,defaultValue:g,onChange:y,size:b,name:S,disabled:j,readOnly:C,fullWidth:T,orientation:D,radius:E,color:R,transitionDuration:A,transitionTimingFunction:k,variant:M,autoContrast:I,withItemsBorders:$,mod:V,...Y}=n,Q=Ie({name:"SegmentedControl",props:n,classes:VD,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:X6}),J=Sn(),G=p.map(ke=>typeof ke=="string"?{label:ke,value:ke}:ke),K=PN(),[P,L]=v.useState(Rh()),[z,H]=v.useState(null),[O,U]=v.useState({}),X=(ke,vt)=>{O[vt]=ke,U(O)},[ee,Se]=Yn({value:m,defaultValue:g,finalValue:Array.isArray(p)?((Me=G.find(ke=>!ke.disabled))==null?void 0:Me.value)??((tt=p[0])==null?void 0:tt.value)??null:null,onChange:y}),be=yr(S),xe=G.map(ke=>v.createElement(ce,{...Q("control"),mod:{active:ee===ke.value,orientation:D},key:ke.value},v.createElement("input",{...Q("input"),disabled:j||ke.disabled,type:"radio",name:be,value:ke.value,id:`${be}-${ke.value}`,checked:ee===ke.value,onChange:()=>!C&&Se(ke.value),"data-focus-ring":J.focusRing,key:`${ke.value}-input`}),v.createElement(ce,{component:"label",...Q("label"),mod:{active:ee===ke.value&&!(j||ke.disabled),disabled:j||ke.disabled,"read-only":C},htmlFor:`${be}-${ke.value}`,ref:vt=>X(vt,ke.value),__vars:{"--sc-label-color":R!==void 0?Ga({color:R,theme:J,autoContrast:I}):void 0},key:`${ke.value}-label`},o.jsx("span",{...Q("innerLabel"),children:ke.label})))),qe=$n(t,ke=>H(ke));return AN(()=>{L(Rh())},[p.length]),p.length===0?null:o.jsxs(ce,{...Q("root"),variant:M,size:b,ref:qe,mod:[{"full-width":T,orientation:D,initialized:K,"with-items-borders":$},V],...Y,role:"radiogroup","data-disabled":j,children:[typeof ee=="string"&&o.jsx(Bx,{target:O[ee],parent:z,component:"span",transitionDuration:"var(--sc-transition-duration)",...Q("indicator")},P),xe]})});Fp.classes=VD;Fp.displayName="@mantine/core/SegmentedControl";function Z6({spacing:e,verticalSpacing:t,cols:n,selector:r}){var m;const i=Sn(),s=t===void 0?e:t,c=qo({"--sg-spacing-x":Nn(_i(e)),"--sg-spacing-y":Nn(_i(s)),"--sg-cols":(m=_i(n))==null?void 0:m.toString()}),u=sn(i.breakpoints).reduce((g,y)=>(g[y]||(g[y]={}),typeof e=="object"&&e[y]!==void 0&&(g[y]["--sg-spacing-x"]=Nn(e[y])),typeof s=="object"&&s[y]!==void 0&&(g[y]["--sg-spacing-y"]=Nn(s[y])),typeof n=="object"&&n[y]!==void 0&&(g[y]["--sg-cols"]=n[y]),g),{}),p=Xu(sn(u),i.breakpoints).filter(g=>sn(u[g.value]).length>0).map(g=>({query:`(min-width: ${i.breakpoints[g.value]})`,styles:u[g.value]}));return o.jsx(Xs,{styles:c,media:p,selector:r})}function Bv(e){return typeof e=="object"&&e!==null?sn(e):[]}function J6(e){return e.sort((t,n)=>Ku(t)-Ku(n))}function ez({spacing:e,verticalSpacing:t,cols:n}){const r=Array.from(new Set([...Bv(e),...Bv(t),...Bv(n)]));return J6(r)}function tz({spacing:e,verticalSpacing:t,cols:n,selector:r}){var p;const i=t===void 0?e:t,s=qo({"--sg-spacing-x":Nn(_i(e)),"--sg-spacing-y":Nn(_i(i)),"--sg-cols":(p=_i(n))==null?void 0:p.toString()}),c=ez({spacing:e,verticalSpacing:t,cols:n}),u=c.reduce((m,g)=>(m[g]||(m[g]={}),typeof e=="object"&&e[g]!==void 0&&(m[g]["--sg-spacing-x"]=Nn(e[g])),typeof i=="object"&&i[g]!==void 0&&(m[g]["--sg-spacing-y"]=Nn(i[g])),typeof n=="object"&&n[g]!==void 0&&(m[g]["--sg-cols"]=n[g]),m),{}),f=c.map(m=>({query:`simple-grid (min-width: ${m})`,styles:u[m]}));return o.jsx(Xs,{styles:s,container:f,selector:r})}var FD={container:"m_925c2d2c",root:"m_2415a157"};const nz={cols:1,spacing:"md",type:"media"},M0=ve((e,t)=>{const n=se("SimpleGrid",nz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,cols:p,verticalSpacing:m,spacing:g,type:y,...b}=n,S=Ie({name:"SimpleGrid",classes:FD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f}),j=fd();return y==="container"?o.jsxs(o.Fragment,{children:[o.jsx(tz,{...n,selector:`.${j}`}),o.jsx("div",{...S("container"),children:o.jsx(ce,{ref:t,...S("root",{className:j}),...b})})]}):o.jsxs(o.Fragment,{children:[o.jsx(Z6,{...n,selector:`.${j}`}),o.jsx(ce,{ref:t,...S("root",{className:j}),...b})]})});M0.classes=FD;M0.displayName="@mantine/core/SimpleGrid";const rz={},Hp=ve((e,t)=>{const{w:n,h:r,miw:i,mih:s,...c}=se("Space",rz,e);return o.jsx(ce,{ref:t,...c,w:n,miw:i??n,h:r,mih:s??r})});Hp.displayName="@mantine/core/Space";var HD={root:"m_6d731127"};const iz={gap:"md",align:"stretch",justify:"flex-start"},az=(e,{gap:t,align:n,justify:r})=>({root:{"--stack-gap":Nn(t),"--stack-align":n,"--stack-justify":r}}),Ge=ve((e,t)=>{const n=se("Stack",iz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,align:p,justify:m,gap:g,variant:y,...b}=n,S=Ie({name:"Stack",props:n,classes:HD,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:az});return o.jsx(ce,{ref:t,...S("root"),variant:y,...b})});Ge.classes=HD;Ge.displayName="@mantine/core/Stack";const[oz,sz]=vr("Stepper component was not found in tree"),Oh=()=>null;Oh.displayName="@mantine/core/StepperCompleted";var I0={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 ih=(e,t)=>typeof e=="function"?o.jsx(e,{step:t||0}):e,lz={withIcon:!0,allowStepClick:!0,iconPosition:"left"},L0=ve((e,t)=>{const{classNames:n,className:r,style:i,styles:s,vars:c,step:u,state:f,color:p,icon:m,completedIcon:g,progressIcon:y,label:b,description:S,withIcon:j,iconSize:C,loading:T,allowStepClick:D,allowStepSelect:E,iconPosition:R,orientation:A,mod:k,...M}=se("StepperStep",lz,e),I=sz(),$=Sn(),V={classNames:n,styles:s},Y=f==="stepCompleted"?null:f==="stepProgress"?y:m,Q={"data-progress":f==="stepProgress"||void 0,"data-completed":f==="stepCompleted"||void 0};return o.jsxs(tr,{...I.getStyles("step",{className:r,style:i,variant:I.orientation,...V}),mod:[{"icon-position":R||I.iconPosition,"allow-click":D},k],ref:t,...Q,...M,__vars:{"--step-color":p?Ht(p,$):void 0},tabIndex:D?0:-1,children:[j&&o.jsxs("span",{...I.getStyles("stepWrapper",V),children:[o.jsxs("span",{...I.getStyles("stepIcon",V),...Q,children:[o.jsx(da,{mounted:f==="stepCompleted",transition:"pop",duration:200,children:J=>o.jsx("span",{...I.getStyles("stepCompletedIcon",{style:J,...V}),children:T?o.jsx(_r,{color:"var(--mantine-color-white)",size:"calc(var(--stepper-icon-size) / 2)",...I.getStyles("stepLoader",V)}):ih(g,u)||o.jsx(wp,{size:"60%"})})}),f!=="stepCompleted"?T?o.jsx(_r,{...I.getStyles("stepLoader",V),size:"calc(var(--stepper-icon-size) / 2)",color:p}):ih(Y||m,u):null]}),A==="vertical"&&o.jsx("span",{...I.getStyles("verticalSeparator",V),"data-active":f==="stepCompleted"||void 0})]}),(b||S)&&o.jsxs("span",{...I.getStyles("stepBody",V),"data-orientation":I.orientation,"data-icon-position":R||I.iconPosition,children:[b&&o.jsx("span",{...I.getStyles("stepLabel",V),children:ih(b,u)}),S&&o.jsx("span",{...I.getStyles("stepDescription",V),children:ih(S,u)})]})]})});L0.classes=I0;L0.displayName="@mantine/core/StepperStep";const cz={orientation:"horizontal",iconPosition:"left",allowNextStepsSelect:!0,wrap:!0},uz=(e,{color:t,iconSize:n,size:r,contentPadding:i,radius:s,autoContrast:c})=>({root:{"--stepper-color":t?Ht(t,e):void 0,"--stepper-icon-color":Ks(c,e)?Ga({color:t,theme:e,autoContrast:c}):void 0,"--stepper-icon-size":n===void 0?rt(r,"stepper-icon-size"):le(n),"--stepper-content-padding":Nn(i),"--stepper-radius":s===void 0?void 0:Vt(s),"--stepper-fz":On(r),"--stepper-spacing":Nn(r)}}),mc=ve((e,t)=>{var z,H,O;const n=se("Stepper",cz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,children:p,onStepClick:m,active:g,icon:y,completedIcon:b,progressIcon:S,color:j,iconSize:C,contentPadding:T,orientation:D,iconPosition:E,size:R,radius:A,allowNextStepsSelect:k,wrap:M,autoContrast:I,...$}=n,V=Ie({name:"Stepper",classes:I0,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:uz}),Y=v.Children.toArray(p),Q=Y.filter(U=>U.type!==Oh),J=Y.find(U=>U.type===Oh),G=Q.reduce((U,X,ee)=>{const Se=g===ee?"stepProgress":g>ee?"stepCompleted":"stepInactive",xe=typeof m!="function"?!1:typeof X.props.allowStepSelect=="boolean"?X.props.allowStepSelect:Se==="stepCompleted"||k;return U.push(v.cloneElement(X,{icon:X.props.icon||y||ee+1,key:ee,step:ee,state:Se,onClick:()=>xe&&(m==null?void 0:m(ee)),allowStepClick:xe,completedIcon:X.props.completedIcon||b,progressIcon:X.props.progressIcon||S,color:X.props.color||j,iconSize:C,iconPosition:X.props.iconPosition||E,orientation:D})),D==="horizontal"&&ee!==Q.length-1&&U.push(v.createElement("div",{...V("separator"),"data-active":ee<g||void 0,"data-orientation":D,key:`separator-${ee}`})),U},[]),K=(H=(z=Q[g])==null?void 0:z.props)==null?void 0:H.children,P=(O=J==null?void 0:J.props)==null?void 0:O.children,L=g>Q.length-1?P:K;return o.jsx(oz,{value:{getStyles:V,orientation:D,iconPosition:E},children:o.jsxs(ce,{...V("root"),ref:t,size:R,...$,children:[o.jsx(ce,{...V("steps"),mod:{orientation:D,"icon-position":E,wrap:M&&D!=="vertical"},children:G}),L&&o.jsx("div",{...V("content"),children:L})]})})});mc.classes=I0;mc.displayName="@mantine/core/Stepper";mc.Completed=Oh;mc.Step=L0;const qD=v.createContext(null),dz=qD.Provider,fz=()=>v.useContext(qD),hz={},z0=ve((e,t)=>{const{value:n,defaultValue:r,onChange:i,size:s,wrapperProps:c,children:u,readOnly:f,...p}=se("SwitchGroup",hz,e),[m,g]=Yn({value:n,defaultValue:r,finalValue:[],onChange:i}),y=b=>{const S=b.currentTarget.value;!f&&g(m.includes(S)?m.filter(j=>j!==S):[...m,S])};return o.jsx(dz,{value:{value:m,onChange:y,size:s},children:o.jsx(mn.Wrapper,{size:s,ref:t,...c,...p,labelElement:"div",__staticSelector:"SwitchGroup",children:o.jsx(i0,{role:"group",children:u})})})});z0.classes=mn.Wrapper.classes;z0.displayName="@mantine/core/SwitchGroup";var GD={root:"m_5f93f3bb",input:"m_926b4011",track:"m_9307d992",thumb:"m_93039a1d",trackLabel:"m_8277e082"};const pz={labelPosition:"right"},mz=(e,{radius:t,color:n,size:r})=>({root:{"--switch-radius":t===void 0?void 0:Vt(t),"--switch-height":rt(r,"switch-height"),"--switch-width":rt(r,"switch-width"),"--switch-thumb-size":rt(r,"switch-thumb-size"),"--switch-label-font-size":rt(r,"switch-label-font-size"),"--switch-track-label-padding":rt(r,"switch-track-label-padding"),"--switch-color":n?Ht(n,e):void 0}}),jd=ve((e,t)=>{const n=se("Switch",pz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,color:p,label:m,offLabel:g,onLabel:y,id:b,size:S,radius:j,wrapperProps:C,thumbIcon:T,checked:D,defaultChecked:E,onChange:R,labelPosition:A,description:k,error:M,disabled:I,variant:$,rootRef:V,mod:Y,...Q}=n,J=fz(),G=S||(J==null?void 0:J.size),K=Ie({name:"Switch",props:n,classes:GD,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:mz}),{styleProps:P,rest:L}=Qa(Q),z=yr(b),H=J?{checked:J.value.includes(L.value),onChange:J.onChange}:{},[O,U]=Yn({value:H.checked??D,defaultValue:E,finalValue:!1});return o.jsxs(Sp,{...K("root"),__staticSelector:"Switch",__stylesApiProps:n,id:z,size:G,labelPosition:A,label:m,description:k,error:M,disabled:I,bodyElement:"label",labelElement:"span",classNames:r,styles:c,unstyled:u,"data-checked":H.checked||D||void 0,variant:$,ref:V,mod:Y,...P,...C,children:[o.jsx("input",{...L,disabled:I,checked:O,"data-checked":H.checked||D||void 0,onChange:X=>{var ee;J?(ee=H.onChange)==null||ee.call(H,X):R==null||R(X),U(X.currentTarget.checked)},id:z,ref:t,type:"checkbox",role:"switch",...K("input")}),o.jsxs(ce,{"aria-hidden":"true",component:"span",mod:{error:M,"label-position":A,"without-labels":!y&&!g},...K("track"),children:[o.jsx(ce,{component:"span",mod:"reduce-motion",...K("thumb"),children:T}),o.jsx("span",{...K("trackLabel"),children:O?y:g})]})]})});jd.classes={...GD,...X2};jd.displayName="@mantine/core/Switch";jd.Group=z0;const[gz,vz]=vr("Table component was not found in the tree");var Cd={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 yz(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 tl(e,t){const n=`Table${e.charAt(0).toUpperCase()}${e.slice(1)}`,r=ve((i,s)=>{const c=se(n,{},i),{classNames:u,className:f,style:p,styles:m,...g}=c,y=vz();return o.jsx(ce,{component:e,ref:s,...yz(y,t),...y.getStyles(e,{className:f,classNames:u,style:p,styles:m,props:c}),...g})});return r.displayName=`@mantine/core/${n}`,r.classes=Cd,r}const Py=tl("th",{columnBorder:!0}),QD=tl("td",{columnBorder:!0}),yh=tl("tr",{rowBorder:!0,striped:!0,highlightOnHover:!0}),WD=tl("thead",{stickyHeader:!0}),YD=tl("tbody"),KD=tl("tfoot"),XD=tl("caption",{captionSide:!0});function $0({data:e}){return o.jsxs(o.Fragment,{children:[e.caption&&o.jsx(XD,{children:e.caption}),e.head&&o.jsx(WD,{children:o.jsx(yh,{children:e.head.map((t,n)=>o.jsx(Py,{children:t},n))})}),e.body&&o.jsx(YD,{children:e.body.map((t,n)=>o.jsx(yh,{children:t.map((r,i)=>o.jsx(QD,{children:r},i))},n))}),e.foot&&o.jsx(KD,{children:o.jsx(yh,{children:e.foot.map((t,n)=>o.jsx(Py,{children:t},n))})})]})}$0.displayName="@mantine/core/TableDataRenderer";const xz={type:"scrollarea"},bz=(e,{minWidth:t,maxHeight:n,type:r})=>({scrollContainer:{"--table-min-width":le(t),"--table-max-height":le(n),"--table-overflow":r==="native"?"auto":void 0}}),U0=ve((e,t)=>{const n=se("TableScrollContainer",xz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,children:p,minWidth:m,maxHeight:g,type:y,scrollAreaProps:b,...S}=n,j=Ie({name:"TableScrollContainer",classes:Cd,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:bz,rootSelector:"scrollContainer"});return o.jsx(ce,{component:y==="scrollarea"?Yr:"div",...y==="scrollarea"?g?{offsetScrollbars:"xy",...b}:{offsetScrollbars:"x",...b}:{},ref:t,...j("scrollContainer"),...S,children:o.jsx("div",{...j("scrollContainerInner"),children:p})})});U0.classes=Cd;U0.displayName="@mantine/core/TableScrollContainer";const Sz={withRowBorders:!0,verticalSpacing:7},wz=(e,{layout:t,captionSide:n,horizontalSpacing:r,verticalSpacing:i,borderColor:s,stripedColor:c,highlightOnHoverColor:u,striped:f,highlightOnHover:p,stickyHeaderOffset:m,stickyHeader:g})=>({table:{"--table-layout":t,"--table-caption-side":n,"--table-horizontal-spacing":Nn(r),"--table-vertical-spacing":Nn(i),"--table-border-color":s?Ht(s,e):void 0,"--table-striped-color":f&&c?Ht(c,e):void 0,"--table-highlight-on-hover-color":p&&u?Ht(u,e):void 0,"--table-sticky-header-offset":g?le(m):void 0}}),ye=ve((e,t)=>{const n=se("Table",Sz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,horizontalSpacing:p,verticalSpacing:m,captionSide:g,stripedColor:y,highlightOnHoverColor:b,striped:S,highlightOnHover:j,withColumnBorders:C,withRowBorders:T,withTableBorder:D,borderColor:E,layout:R,variant:A,data:k,children:M,stickyHeader:I,stickyHeaderOffset:$,mod:V,tabularNums:Y,...Q}=n,J=Ie({name:"Table",props:n,className:i,style:s,classes:Cd,classNames:r,styles:c,unstyled:u,rootSelector:"table",vars:f,varsResolver:wz});return o.jsx(gz,{value:{getStyles:J,stickyHeader:I,striped:S===!0?"odd":S||void 0,highlightOnHover:j,withColumnBorders:C,withRowBorders:T,captionSide:g||"bottom"},children:o.jsx(ce,{component:"table",variant:A,ref:t,mod:[{"data-with-table-border":D,"data-tabular-nums":Y},V],...J("table"),...Q,children:M||!!k&&o.jsx($0,{data:k})})})});ye.classes=Cd;ye.displayName="@mantine/core/Table";ye.Td=QD;ye.Th=Py;ye.Tr=yh;ye.Thead=WD;ye.Tbody=YD;ye.Tfoot=KD;ye.Caption=XD;ye.ScrollContainer=U0;ye.DataRenderer=$0;const[jz,B0]=vr("Tabs component was not found in the tree");var Ed={root:"m_89d60db1","list--default":"m_576c9d4",list:"m_89d33d6d",panel:"m_b0c91715",tab:"m_4ec4dce6",tabSection:"m_fc420b1f","tab--default":"m_539e827b","list--outline":"m_6772fbd5","tab--outline":"m_b59ab47c","tab--pills":"m_c3381914"};const Cz={},V0=ve((e,t)=>{const n=se("TabsList",Cz,e),{children:r,className:i,grow:s,justify:c,classNames:u,styles:f,style:p,mod:m,...g}=n,y=B0();return o.jsx(ce,{...g,...y.getStyles("list",{className:i,style:p,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})});V0.classes=Ed;V0.displayName="@mantine/core/TabsList";const Ez={},F0=ve((e,t)=>{const n=se("TabsPanel",Ez,e),{children:r,className:i,value:s,classNames:c,styles:u,style:f,mod:p,keepMounted:m,...g}=n,y=B0(),b=y.value===s,S=y.keepMounted||m||b?r:null;return o.jsx(ce,{...g,...y.getStyles("panel",{className:i,classNames:c,styles:u,style:[f,b?void 0:{display:"none"}],props:n}),ref:t,mod:[{orientation:y.orientation},p],role:"tabpanel",id:y.getPanelId(s),"aria-labelledby":y.getTabId(s),children:S})});F0.classes=Ed;F0.displayName="@mantine/core/TabsPanel";const Tz={},H0=ve((e,t)=>{const n=se("TabsTab",Tz,e),{className:r,children:i,rightSection:s,leftSection:c,value:u,onClick:f,onKeyDown:p,disabled:m,color:g,style:y,classNames:b,styles:S,vars:j,mod:C,tabIndex:T,...D}=n,E=Sn(),{dir:R}=Zs(),A=B0(),k=u===A.value,M=$=>{A.onChange(A.allowTabDeactivation&&u===A.value?null:u),f==null||f($)},I={classNames:b,styles:S,props:n};return o.jsxs(tr,{...D,...A.getStyles("tab",{className:r,style:y,variant:A.variant,...I}),disabled:m,unstyled:A.unstyled,variant:A.variant,mod:[{active:k,disabled:m,orientation:A.orientation,inverted:A.inverted,placement:A.orientation==="vertical"&&A.placement},C],ref:t,role:"tab",id:A.getTabId(u),"aria-selected":k,tabIndex:T!==void 0?T:k||A.value===null?0:-1,"aria-controls":A.getPanelId(u),onClick:M,__vars:{"--tabs-color":g?Ht(g,E):void 0},onKeyDown:fR({siblingSelector:'[role="tab"]',parentSelector:'[role="tablist"]',activateOnFocus:A.activateTabWithKeyboard,loop:A.loop,orientation:A.orientation||"horizontal",dir:R,onKeyDown:p}),children:[c&&o.jsx("span",{...A.getStyles("tabSection",I),"data-position":"left",children:c}),i&&o.jsx("span",{...A.getStyles("tabLabel",I),children:i}),s&&o.jsx("span",{...A.getStyles("tabSection",I),"data-position":"right",children:s})]})});H0.classes=Ed;H0.displayName="@mantine/core/TabsTab";const KC="Tabs.Tab or Tabs.Panel component was rendered with invalid value or without value",Rz={keepMounted:!0,orientation:"horizontal",loop:!0,activateTabWithKeyboard:!0,allowTabDeactivation:!1,unstyled:!1,inverted:!1,variant:"default",placement:"left"},Dz=(e,{radius:t,color:n,autoContrast:r})=>({root:{"--tabs-radius":Vt(t),"--tabs-color":Ht(n,e),"--tabs-text-color":Ks(r,e)?Ga({color:n,theme:e,autoContrast:r}):void 0}}),Et=ve((e,t)=>{const n=se("Tabs",Rz,e),{defaultValue:r,value:i,onChange:s,orientation:c,children:u,loop:f,id:p,activateTabWithKeyboard:m,allowTabDeactivation:g,variant:y,color:b,radius:S,inverted:j,placement:C,keepMounted:T,classNames:D,styles:E,unstyled:R,className:A,style:k,vars:M,autoContrast:I,mod:$,...V}=n,Y=yr(p),[Q,J]=Yn({value:i,defaultValue:r,finalValue:null,onChange:s}),G=Ie({name:"Tabs",props:n,classes:Ed,className:A,style:k,classNames:D,styles:E,unstyled:R,vars:M,varsResolver:Dz});return o.jsx(jz,{value:{placement:C,value:Q,orientation:c,id:Y,loop:f,activateTabWithKeyboard:m,getTabId:Hj(`${Y}-tab`,KC),getPanelId:Hj(`${Y}-panel`,KC),onChange:J,allowTabDeactivation:g,variant:y,color:b,radius:S,inverted:j,keepMounted:T,unstyled:R,getStyles:G},children:o.jsx(ce,{ref:t,id:Y,variant:y,mod:[{orientation:c,inverted:c==="horizontal"&&j,placement:c==="vertical"&&C},$],...G("root"),...V,children:u})})});Et.classes=Ed;Et.displayName="@mantine/core/Tabs";Et.Tab=H0;Et.Panel=F0;Et.List=V0;const Az={},ze=ve((e,t)=>{const n=se("TextInput",Az,e);return o.jsx(Pr,{component:"input",ref:t,...n,__staticSelector:"TextInput"})});ze.classes=Pr.classes;ze.displayName="@mantine/core/TextInput";var ZD={root:"m_7341320d"};const _z={},kz=(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":rt(t,"ti-size"),"--ti-radius":n===void 0?void 0:Vt(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}}},q0=ve((e,t)=>{const n=se("ThemeIcon",_z,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,autoContrast:p,...m}=n,g=Ie({name:"ThemeIcon",classes:ZD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:kz});return o.jsx(ce,{ref:t,...g("root"),...m})});q0.classes=ZD;q0.displayName="@mantine/core/ThemeIcon";const Pz=["h1","h2","h3","h4","h5","h6"],Nz=["xs","sm","md","lg","xl"];function Oz(e,t){const n=t!==void 0?t:`h${e}`;return Pz.includes(n)?{fontSize:`var(--mantine-${n}-font-size)`,fontWeight:`var(--mantine-${n}-font-weight)`,lineHeight:`var(--mantine-${n}-line-height)`}:Nz.includes(n)?{fontSize:`var(--mantine-font-size-${n})`,fontWeight:`var(--mantine-h${e}-font-weight)`,lineHeight:`var(--mantine-h${e}-line-height)`}:{fontSize:le(n),fontWeight:`var(--mantine-h${e}-font-weight)`,lineHeight:`var(--mantine-h${e}-line-height)`}}var JD={root:"m_8a5d1357"};const Mz={order:1},Iz=(e,{order:t,size:n,lineClamp:r,textWrap:i})=>{const s=Oz(t,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}}},Le=ve((e,t)=>{const n=se("Title",Mz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,order:f,vars:p,size:m,variant:g,lineClamp:y,textWrap:b,mod:S,...j}=n,C=Ie({name:"Title",props:n,classes:JD,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:p,varsResolver:Iz});return[1,2,3,4,5,6].includes(f)?o.jsx(ce,{...C("root"),component:`h${f}`,variant:g,ref:t,mod:[{order:f,"data-line-clamp":typeof y=="number"},S],size:m,...j}):null});Le.classes=JD;Le.displayName="@mantine/core/Title";function Lz(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 zz(e){return v.useSyncExternalStore(e.subscribe,()=>e.getState(),()=>e.getState())}function $z(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 Uz=()=>Lz({notifications:[],queue:[],defaultPosition:"bottom-right",limit:5}),nl=Uz(),Bz=(e=nl)=>zz(e);function kc(e,t){const n=e.getState(),r=t([...n.notifications,...n.queue]),i=$z(r,n.defaultPosition,n.limit);e.setState({notifications:i.notifications,queue:i.queue,limit:n.limit,defaultPosition:n.defaultPosition})}function Oe(e,t=nl){const n=e.id||Rh();return kc(t,r=>e.id&&r.some(i=>i.id===e.id)?r:[...r,{...e,id:n}]),n}function eA(e,t=nl){return kc(t,n=>n.filter(r=>{var i;return r.id===e?((i=r.onClose)==null||i.call(r,r),!1):!0})),e}function As(e,t=nl){return kc(t,n=>n.map(r=>r.id===e.id?{...r,...e}:r)),e.id}function Vz(e=nl){kc(e,()=>[])}function Fz(e=nl){kc(e,t=>t.slice(0,e.getState().limit))}const di={show:Oe,hide:eA,update:As,clean:Vz,cleanQueue:Fz,updateState:kc};function Ny(e,t){return Ny=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},Ny(e,t)}function tA(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,Ny(e,t)}var Vv={exports:{}},Fv,XC;function Hz(){if(XC)return Fv;XC=1;var e="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";return Fv=e,Fv}var Hv,ZC;function qz(){if(ZC)return Hv;ZC=1;var e=Hz();function t(){}function n(){}return n.resetWarningCache=t,Hv=function(){function r(c,u,f,p,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},Hv}var JC;function Gz(){return JC||(JC=1,Vv.exports=qz()()),Vv.exports}var Qz=Gz();const an=sx(Qz),eE={disabled:!1},Mh=En.createContext(null);var Wz=function(t){return t.scrollTop},qu="unmounted",ws="exited",js="entering",ec="entered",Oy="exiting",Xa=function(e){tA(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=ws,s.appearStatus=js):f=ec:r.unmountOnExit||r.mountOnEnter?f=qu:f=ws,s.state={status:f},s.nextCallback=null,s}t.getDerivedStateFromProps=function(i,s){var c=i.in;return c&&s.status===qu?{status:ws}: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!==js&&c!==ec&&(s=js):(c===js||c===ec)&&(s=Oy)}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===js){if(this.props.unmountOnExit||this.props.mountOnEnter){var c=this.props.nodeRef?this.props.nodeRef.current:Hu.findDOMNode(this);c&&Wz(c)}this.performEnter(i)}else this.performExit();else this.props.unmountOnExit&&this.state.status===ws&&this.setState({status:qu})},n.performEnter=function(i){var s=this,c=this.props.enter,u=this.context?this.context.isMounting:i,f=this.props.nodeRef?[u]:[Hu.findDOMNode(this),u],p=f[0],m=f[1],g=this.getTimeouts(),y=u?g.appear:g.enter;if(!i&&!c||eE.disabled){this.safeSetState({status:ec},function(){s.props.onEntered(p)});return}this.props.onEnter(p,m),this.safeSetState({status:js},function(){s.props.onEntering(p,m),s.onTransitionEnd(y,function(){s.safeSetState({status:ec},function(){s.props.onEntered(p,m)})})})},n.performExit=function(){var i=this,s=this.props.exit,c=this.getTimeouts(),u=this.props.nodeRef?void 0:Hu.findDOMNode(this);if(!s||eE.disabled){this.safeSetState({status:ws},function(){i.props.onExited(u)});return}this.props.onExit(u),this.safeSetState({status:Oy},function(){i.props.onExiting(u),i.onTransitionEnd(c.exit,function(){i.safeSetState({status:ws},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:Hu.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],p=f[0],m=f[1];this.props.addEndListener(p,m)}i!=null&&setTimeout(this.nextCallback,i)},n.render=function(){var i=this.state.status;if(i===qu)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=m0(s,["children","in","mountOnEnter","unmountOnExit","appear","enter","exit","timeout","addEndListener","onEnter","onEntering","onEntered","onExit","onExiting","onExited","nodeRef"]);return En.createElement(Mh.Provider,{value:null},typeof c=="function"?c(i,u):En.cloneElement(En.Children.only(c),u))},t}(En.Component);Xa.contextType=Mh;Xa.propTypes={};function Ql(){}Xa.defaultProps={in:!1,mountOnEnter:!1,unmountOnExit:!1,appear:!1,enter:!0,exit:!0,onEnter:Ql,onEntering:Ql,onEntered:Ql,onExit:Ql,onExiting:Ql,onExited:Ql};Xa.UNMOUNTED=qu;Xa.EXITED=ws;Xa.ENTERING=js;Xa.ENTERED=ec;Xa.EXITING=Oy;function Yz(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function G0(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 Kz(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 p=r[f][c];u[r[f][c]]=n(p)}u[f]=n(f)}for(c=0;c<i.length;c++)u[i[c]]=n(i[c]);return u}function _s(e,t,n){return n[t]!=null?n[t]:e.props[t]}function Xz(e,t){return G0(e.children,function(n){return v.cloneElement(n,{onExited:t.bind(null,n),in:!0,appear:_s(n,"appear",e),enter:_s(n,"enter",e),exit:_s(n,"exit",e)})})}function Zz(e,t,n){var r=G0(e.children),i=Kz(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,p=t[s],m=v.isValidElement(p)&&!p.props.in;f&&(!u||m)?i[s]=v.cloneElement(c,{onExited:n.bind(null,c),in:!0,exit:_s(c,"exit",e),enter:_s(c,"enter",e)}):!f&&u&&!m?i[s]=v.cloneElement(c,{in:!1}):f&&u&&v.isValidElement(p)&&(i[s]=v.cloneElement(c,{onExited:n.bind(null,c),in:p.props.in,exit:_s(c,"exit",e),enter:_s(c,"enter",e)}))}}),i}var Jz=Object.values||function(e){return Object.keys(e).map(function(t){return e[t]})},e8={component:"div",childFactory:function(t){return t}},Oo=function(e){tA(t,e);function t(r,i){var s;s=e.call(this,r,i)||this;var c=s.handleExited.bind(Yz(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?Xz(i,u):Zz(i,c,u),firstRender:!1}},n.handleExited=function(i,s){var c=G0(this.props.children);i.key in c||(i.props.onExited&&i.props.onExited(s),this.mounted&&this.setState(function(u){var f=Nh({},u.children);return delete f[i.key],{children:f}}))},n.render=function(){var i=this.props,s=i.component,c=i.childFactory,u=m0(i,["component","childFactory"]),f=this.state.contextValue,p=Jz(this.state.children).map(c);return delete u.appear,delete u.enter,delete u.exit,s===null?En.createElement(Mh.Provider,{value:f},p):En.createElement(Mh.Provider,{value:f},En.createElement(s,u,p))},t}(En.Component);Oo.propTypes={};Oo.defaultProps=e8;const nA=["bottom-center","bottom-left","bottom-right","top-center","top-left","top-right"];function t8(e,t){return e.reduce((n,r)=>(n[r.position||t].push(r),n),nA.reduce((n,r)=>(n[r]=[],n),{}))}const tE={left:"translateX(-100%)",right:"translateX(100%)","top-center":"translateY(-100%)","bottom-center":"translateY(100%)"},n8={left:"translateX(0)",right:"translateX(0)","top-center":"translateY(0)","bottom-center":"translateY(0)"};function r8({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:tE[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:n8[c]},p={opacity:0,maxHeight:0,transform:tE[c]};return{...u,...{entering:f,entered:f,exiting:p,exited:p}[e]}}function i8(e,t){return typeof t=="number"?t:t===!1||e===!1?!1:e}const rA=v.forwardRef(({data:e,onHide:t,autoClose:n,...r},i)=>{const{autoClose:s,message:c,...u}=e,f=i8(n,e.autoClose),p=v.useRef(-1),m=()=>window.clearTimeout(p.current),g=()=>{t(e.id),m()},y=()=>{typeof f=="number"&&(p.current=window.setTimeout(g,f))};return v.useEffect(()=>{var b;(b=e.onOpen)==null||b.call(e,e)},[]),v.useEffect(()=>(y(),m),[f]),o.jsx(R0,{...r,...u,onClose:g,ref:i,onMouseEnter:m,onMouseLeave:y,children:c})});rA.displayName="@mantine/notifications/NotificationContainer";var iA={root:"m_b37d9ac7",notification:"m_5ed0edd0"};const a8=Xa,o8={position:"bottom-right",autoClose:4e3,transitionDuration:250,containerWidth:440,notificationMaxHeight:200,limit:5,zIndex:Wr("overlay"),store:nl,withinPortal:!0},s8=(e,{zIndex:t,containerWidth:n})=>({root:{"--notifications-z-index":t==null?void 0:t.toString(),"--notifications-container-width":le(n)}}),Za=ve((e,t)=>{const n=se("Notifications",o8,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,position:p,autoClose:m,transitionDuration:g,containerWidth:y,notificationMaxHeight:b,limit:S,zIndex:j,store:C,portalProps:T,withinPortal:D,...E}=n,R=Sn(),A=Bz(C),k=wN(),M=fx(),I=v.useRef({}),$=v.useRef(0),Y=(R.respectReducedMotion?M:!1)?1:g,Q=Ie({name:"Notifications",classes:iA,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:s8});v.useEffect(()=>{C==null||C.updateState(K=>({...K,limit:S||5,defaultPosition:p}))},[S,p]),za(()=>{A.notifications.length>$.current&&setTimeout(()=>k(),0),$.current=A.notifications.length},[A.notifications]);const J=t8(A.notifications,p),G=nA.reduce((K,P)=>(K[P]=J[P].map(({style:L,...z})=>o.jsx(a8,{timeout:Y,onEnter:()=>I.current[z.id].offsetHeight,nodeRef:{current:I.current[z.id]},children:H=>o.jsx(rA,{ref:O=>{I.current[z.id]=O},data:z,onHide:O=>eA(O,C),autoClose:m,...Q("notification",{style:{...r8({state:H,position:P,transitionDuration:Y,maxHeight:b}),...L}})})},z.id)),K),{});return o.jsxs(Go,{withinPortal:D,...T,children:[o.jsx(ce,{...Q("root"),"data-position":"top-center",ref:t,...E,children:o.jsx(Oo,{children:G["top-center"]})}),o.jsx(ce,{...Q("root"),"data-position":"top-left",...E,children:o.jsx(Oo,{children:G["top-left"]})}),o.jsx(ce,{...Q("root",{className:lc.classNames.fullWidth}),"data-position":"top-right",...E,children:o.jsx(Oo,{children:G["top-right"]})}),o.jsx(ce,{...Q("root",{className:lc.classNames.fullWidth}),"data-position":"bottom-right",...E,children:o.jsx(Oo,{children:G["bottom-right"]})}),o.jsx(ce,{...Q("root"),"data-position":"bottom-left",...E,children:o.jsx(Oo,{children:G["bottom-left"]})}),o.jsx(ce,{...Q("root"),"data-position":"bottom-center",...E,children:o.jsx(Oo,{children:G["bottom-center"]})})]})});Za.classes=iA;Za.displayName="@mantine/notifications/Notifications";Za.show=di.show;Za.hide=di.hide;Za.update=di.update;Za.clean=di.clean;Za.cleanQueue=di.cleanQueue;Za.updateState=di.updateState;class l8{constructor(t,n){this.operator=t,this.child=n}toString(){return`${this.operator}(${this.child.toString()})`}}class Td{constructor(t,n,r){this.operator=t,this.left=n,this.right=r}toString(){return`(${this.left.toString()} ${this.operator} ${this.right.toString()})`}}class c8{constructor(){this.prefixParselets={},this.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 u8(t,this.prefixParselets,this.infixParselets)}}class u8{constructor(t,n,r){this.tokens=t,this.prefixParselets=n,this.infixParselets=r}hasMore(){return this.tokens.length>0}match(t){const n=this.peek();return(n==null?void 0:n.id)!==t?!1:(this.consume(),!0)}consumeAndParse(t=1/0){const n=this.consume(),r=this.prefixParselets[n.id];if(!r)throw 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){var r,i;if(!this.tokens.length)throw Error("Cant consume unknown more tokens.");if(t&&((r=this.peek())==null?void 0:r.id)!==t){const s=this.peek();throw Error(`Expected ${t} but got "${s.id}" (${s.value}) at line ${s.line} column ${s.column}.`)}if(n&&((i=this.peek())==null?void 0:i.value)!==n){const s=this.peek();throw Error(`Expected "${n}" but got "${s.value}" at line ${s.line} column ${s.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]}}class aA{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}}const Rd="http://hl7.org",oA="ok",d8="created",f8="gone",h8="not-modified",p8="not-found",m8="unauthorized",g8="forbidden",v8="accepted",y8={resourceType:"OperationOutcome",id:oA,issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},x8={resourceType:"OperationOutcome",id:p8,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},id={resourceType:"OperationOutcome",id:m8,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},b8={...id,issue:[...id.issue,{severity:"error",code:"expired",details:{text:"Token expired"}}]},nE={...id,issue:[...id.issue,{severity:"error",code:"invalid",details:{text:"Token not issued for this audience"}}]},Q0={resourceType:"OperationOutcome",id:g8,issue:[{severity:"error",code:"forbidden",details:{text:"Forbidden"}}]};function ra(e,t){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"invalid",details:{text:e},...t?{expression:[t]}:void 0}]}}function yn(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"structure",details:{text:e}}]}}function S8(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"exception",details:{text:"Internal server error"},diagnostics:e.toString()}]}}function w8(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 qp(e){return typeof e=="object"&&e!==null&&e.resourceType==="OperationOutcome"}function sA(e){return e.id===oA||e.id===d8||e.id===h8||e.id===v8}function j8(e){return e.id===f8}class dt extends Error{constructor(t,n){super(lA(t)),this.outcome=t,this.cause=n}}function Zt(e){return e instanceof dt?e.outcome:qp(e)?e:ra(Ye(e))}function Ye(e){return e?typeof e=="string"?e:w8(e)?e.message:qp(e)?lA(e):typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:JSON.stringify(e):"Unknown error"}function lA(e){var n;const t=((n=e.issue)==null?void 0:n.map(cA))??[];return t.length>0?t.join("; "):"Unknown error"}function cA(e){var n,r;let t;return(n=e.details)!=null&&n.text?e.diagnostics?t=`${e.details.text} (${e.diagnostics})`:t=e.details.text:e.diagnostics?t=e.diagnostics:t="Unknown error",(r=e.expression)!=null&&r.length&&(t+=` (${e.expression.join(", ")})`),t}function C8(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 E8(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,C8(i,s)])),constraints:[],innerTypes:[]};return t}const T8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]}}},R8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]}}},D8={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"}]}}},A8={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"}]}}},_8={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"}]}}},k8={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"}]}}},P8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},coding:{max:9007199254740991,type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},N8={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"}]}}},O8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:9007199254740991,type:[{code:"ContactPoint"}]}}},M8={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"}]}}},I8={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"}]}}},L8={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"}]}}},z8={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"}]}}},$8={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"}]}}},U8={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"}]}}},B8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},V8={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"}]}}},F8={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"]}]}}},H8={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"]}]}}},q8={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"}]}}},G8={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"}]}}},Q8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},W8={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"}]}}},Y8={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"}]}}},K8={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"}]}}},X8={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"}]}}},Z8={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"]}]}}},J8={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"]}]}}},e$={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"}]}}},t$={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"}]}}},n$={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"}]}}},r$={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"}]}}},i$={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"]}]}}},a$={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"}]}}},o$={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"}]}}},s$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},l$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},c$={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"]}]}}},u$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},d$={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"}]}}},f$={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"}]}}},h$={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"}]}}},p$={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"}]}}},m$={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"]}]}}},g$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},v$={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"}]}}},y$={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"]}]}}},x$={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"}]}}},b$={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"}]}}},S$={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"}]}}},w$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]},highLimit:{type:[{code:"Quantity"}]}}},j$={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"}]}}},C$={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"}]}}},E$={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"}]}}},T$={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"]}]}}},R$={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"}]}}},D$={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"}]}}},A$={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"}]}}},_$={Element:T8,BackboneElement:R8,Address:D8,Age:A8,Annotation:_8,Attachment:k8,CodeableConcept:P8,Coding:N8,ContactDetail:O8,ContactPoint:M8,Contributor:I8,Count:L8,DataRequirement:z8,DataRequirementCodeFilter:$8,DataRequirementDateFilter:U8,DataRequirementSort:B8,Distance:V8,Dosage:F8,DosageDoseAndRate:H8,Duration:q8,ElementDefinition:G8,ElementDefinitionSlicingDiscriminator:Q8,ElementDefinitionSlicing:W8,ElementDefinitionBase:Y8,ElementDefinitionType:K8,ElementDefinitionExample:X8,ElementDefinitionConstraint:Z8,ElementDefinitionBinding:J8,ElementDefinitionMapping:e$,Expression:t$,Extension:n$,HumanName:r$,Identifier:i$,MarketingStatus:a$,Meta:o$,Money:s$,Narrative:l$,ParameterDefinition:c$,Period:u$,Population:d$,ProdCharacteristic:f$,ProductShelfLife:h$,Quantity:p$,Range:m$,Ratio:g$,Reference:v$,RelatedArtifact:y$,SampledData:x$,Signature:b$,SubstanceAmount:S$,SubstanceAmountReferenceRange:w$,Timing:j$,TimingRepeat:C$,TriggerDefinition:E$,UsageContext:T$,MoneyQuantity:R$,SimpleQuantity:D$,IdentityProvider:A$};function k$(e){return new N$(e).parse()}const Ih=E8(_$),W0=Object.create(null),rE=Object.create(null),P$={"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 uA(e){let t;return t=rE[e],t||(t=rE[e]=Object.create(null)),t}function iE(e){var r;const n=(Array.isArray(e)?e:((r=e.entry)==null?void 0:r.map(i=>i.resource))??[]).filter(i=>(i==null?void 0:i.resourceType)==="StructureDefinition");CU(n);for(const i of n)dA(i)}function dA(e){var s,c;if(!(e!=null&&e.name))throw new Error("Failed loading StructureDefinition from bundle");if(e.resourceType!=="StructureDefinition")return;const t=k$(e),n=P$[e.url];let r,i;n?(r=Ih,i=n):e.url===`http://hl7.org/fhir/StructureDefinition/${e.type}`||e.url===`https://medplum.com/fhir/StructureDefinition/${e.type}`||(s=e.type)!=null&&s.startsWith("http://")||(c=e.type)!=null&&c.startsWith("https://")?(r=Ih,i=e.type):(r=uA(e.url),i=e.type),r[i]=t;for(const u of t.innerTypes)u.parentType=t,r[u.name]=u;W0[e.url]=t}function fA(e){return!!Ih[e]}function Gp(e,t){if(t){const n=uA(t)[e];if(n)return n}return Ih[e]}function hA(e,t){const n=Gp(e,t);if(!n)throw new dt(ra("Unknown data type: "+e));return n}function Y0(e){return!!W0[e]}function Pc(e){return W0[e]}class N${constructor(t){var n;if(!((n=t.snapshot)!=null&&n.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:I$(t),elements:{},constraints:this.parseElementDefinition(this.root).constraints,innerTypes:[],summaryProperties:new Set,mandatoryProperties:new Set},this.innerTypes=[]}parse(){var n,r,i,s,c;let t=this.next();for(;t;){if(t.sliceName)this.parseSliceStart(t);else if((n=t.id)!=null&&n.includes(":")){if((r=this.slicingContext)!=null&&r.current){const u=qv(t,this.slicingContext.path);this.slicingContext.current.elements[u]=this.parseElementDefinition(t)}}else{const u=this.parseElementDefinition(t);this.checkFieldEnter(t,u);let f=this.backboneContext;for(;f;){if((i=t.path)!=null&&i.startsWith(f.path+".")){f.type.elements[qv(t,f.path)]=u;break}f=f.parent}if(!f){const p=qv(t,this.root.path);t.isSummary&&((s=this.resourceSchema.summaryProperties)==null||s.add(p.replace("[x]",""))),u.min>0&&((c=this.resourceSchema.mandatoryProperties)==null||c.add(p.replace("[x]",""))),this.resourceSchema.elements[p]=u}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&&!Wl(this.slicingContext.path,t==null?void 0:t.path)&&(this.slicingContext=void 0),t.slicing&&!this.slicingContext&&this.enterSlice(t,n)}enterInnerType(t){var r,i,s;for(;this.backboneContext&&!Wl((r=this.backboneContext)==null?void 0:r.path,t.path);)this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;const n=hE(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:Wl((i=this.backboneContext)==null?void 0:i.path,t.path)?this.backboneContext:(s=this.backboneContext)==null?void 0:s.parent}}enterSlice(t,n){var r,i,s,c;M$(t)&&!((r=this.peek())!=null&&r.sliceName)||(n.slicing={discriminator:(((i=t.slicing)==null?void 0:i.discriminator)??[]).map(u=>{if(u.type!=="value"&&u.type!=="pattern"&&u.type!=="type")throw new Error(`Unsupported slicing discriminator type: ${u.type}`);return{path:u.path,type:u.type}}),slices:[],ordered:((s=t.slicing)==null?void 0:s.ordered)??!1,rule:(c=t.slicing)==null?void 0:c.rules},this.slicingContext={field:n.slicing,path:t.path??""})}checkFieldExit(t=void 0){if(this.backboneContext&&!Wl(this.backboneContext.path,t==null?void 0:t.path))if(this.backboneContext.parent)do this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;while(this.backboneContext&&!Wl(this.backboneContext.path,t==null?void 0: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(){var n,r,i,s,c;const t=this.elements[this.index];if(t){if(this.elementIndex[t.path??""]=t,t.contentReference){const u=t.contentReference.slice(t.contentReference.indexOf("#")+1),f=this.elementIndex[u];return f?{...f,id:t.id,path:t.path,min:t.min??f.min,max:t.max??f.max,base:{path:((n=f.base)==null?void 0:n.path)??u,min:((r=t.base)==null?void 0:r.min)??((i=f.base)==null?void 0:i.min)??f.min,max:((s=t.base)==null?void 0:s.max)??((c=f.base)==null?void 0:c.max)??f.max},contentReference:t.contentReference,definition:t.definition}:void 0}return t}}isInnerType(t){var r;const n=this.peek();return!!(Wl(t==null?void 0:t.path,n==null?void 0:n.path)&&((r=t.type)!=null&&r.some(i=>["BackboneElement","Element"].includes(i.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=>{var i;let r;return(n.code==="BackboneElement"||n.code==="Element")&&(r=hE(t)),r||(r=(i=Ja(n,"http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type"))==null?void 0:i.valueUrl),r||(r=n.code??""),{code:r,targetProfile:n.targetProfile,profile:n.profile}})}parseElementDefinition(t){var s,c;const n=aE(t.max),r=(s=t.base)!=null&&s.max?aE(t.base.max):n,i={type:"ElementDefinition",value:t};return{description:t.definition||"",path:t.path||((c=t.base)==null?void 0:c.path)||"",min:t.min??0,max:n,isArray:r>1,constraints:(t.constraint??[]).map(u=>({key:u.key??"",severity:u.severity??"error",expression:u.expression??"",description:u.human??""})),type:this.parseElementDefinitionType(t),fixed:oE(gc(i,"fixed[x]")),pattern:oE(gc(i,"pattern[x]")),binding:t.binding}}}function aE(e){return e==="*"?Number.POSITIVE_INFINITY:Number.parseInt(e,10)}function qv(e,t=""){return O$(e.path,t)}function O$(e,t){return e?t&&e.startsWith(t)?e.substring(t.length+1):e:""}function Wl(e,t){return!e||!t?!1:t.startsWith(e+".")||t===e}function oE(e){return Array.isArray(e)&&e.length>0?e[0]:Rn(e)?void 0:e}function M$(e){var n,r;const t=(n=e.slicing)==null?void 0:n.discriminator;return!!((r=e.type)!=null&&r.some(i=>i.code==="Extension")&&(t==null?void 0:t.length)===1&&t[0].type==="value"&&t[0].path==="url")}function I$(e){let t=e.description;return t!=null&&t.startsWith(`Base StructureDefinition for ${e.name} Type: `)&&(t=t.substring(`Base StructureDefinition for ${e.name} Type: `.length)),t}function L$(e,t,n){if(e===void 0)return[void 0];if(t==="$this")return[e];const r=n!=null&&n.withPath?z$:gc,[i,...s]=t.split(".");let c=[r(e,i,n)];for(const u of s){const f=[];for(const p of c)if(Array.isArray(p))for(const m of p)f.push(r(m,u,n));else(n!=null&&n.withPath&&p&&p.value!==void 0||!(n!=null&&n.withPath)&&p!==void 0)&&f.push(r(p,u,n));c=f}return c}function z$(e,t,n){const r=e.path;return $$(gc(e,t,n),r,t)}function $$(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 pA={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 U$(e,t,n,r){var c;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 Z0(e,i.pattern);if(i.fixed)return sa(e,i.fixed);if(((c=i.binding)==null?void 0:c.strength)==="required"&&i.binding.valueSet)return!0;break;case"type":return!e||!(s!=null&&s.length)?!1:s.some(u=>u.code===e.type)}return!1}function We(e){return[{type:oe.boolean,value:e}]}function mi(e){return e==null?{type:"undefined",value:void 0}:Number.isSafeInteger(e)?{type:oe.integer,value:e}:typeof e=="number"?{type:oe.decimal,value:e}:typeof e=="boolean"?{type:oe.boolean,value:e}:typeof e=="string"?{type:oe.string,value:e}:fi(e)?{type:oe.Quantity,value:e}:fa(e)?{type:e.resourceType,value:e}:CA(e)?{type:oe.CodeableConcept,value:e}:jA(e)?{type:oe.Coding,value:e}:{type:oe.BackboneElement,value:e}}function ea(e){return e.length===0?!1:!!e[0].value}function Ba(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 gc(e,t,n){if(!e.value)return;const r=Yo(e.type,t,n==null?void 0:n.profileUrl);return r?mA(e,t,r):Dd(e,t)}function mA(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("."),p=n.path.substring(f+1);for(const m of i){const g=p.replace("[x]",Hn(m.code));if(s=r[g],u=r["_"+g],s!==void 0||u!==void 0){c=m.code;break}}if(u)if(Array.isArray(s)){s=s.slice();for(let m=0;m<Math.max(s.length,u.length);m++)s[m]=uE(s[m],u[m])}else s=uE(s,u);if(!Rn(s))return(c==="Element"||c==="BackboneElement")&&(c=n.type[0].code),Array.isArray(s)?s.map(m=>sE(m,c)):sE(s,c)}function sE(e,t){return t==="Resource"&&fa(e)&&(t=e.resourceType),{type:t,value:e}}function Dd(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(oe)){const c=i+Hn(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||Rn(r[0]))return}else if(Rn(r))return;return r}function gA(e){const t=[];for(const n of e){let r=!1;for(const i of t)if(ea(Qp(n,i))){r=!0;break}r||t.push(n)}return t}function B$(e){return We(!ea(e))}function V$(e,t){return e.length===0||t.length===0?[]:e.length!==t.length?We(!1):We(e.every((n,r)=>ea(Qp(n,t[r]))))}function F$(e,t){return e.length===0||t.length===0?[]:e.length!==t.length?We(!0):We(e.some((n,r)=>!ea(Qp(n,t[r]))))}function Qp(e,t){var i,s;const n=(i=e.value)==null?void 0:i.valueOf(),r=(s=t.value)==null?void 0:s.valueOf();return typeof n=="number"&&typeof r=="number"?We(Math.abs(n-r)<1e-8):fi(n)&&fi(r)?We(bA(n,r)):We(typeof n=="object"&&typeof r=="object"?K0(e,t):n===r)}function vA(e,t){return e.length===0&&t.length===0?We(!0):e.length!==t.length?We(!1):(e.sort(lE),t.sort(lE),We(e.every((n,r)=>ea(H$(n,t[r])))))}function H$(e,t){const{type:n,value:r}=e,{type:i,value:s}=t,c=r==null?void 0:r.valueOf(),u=s==null?void 0:s.valueOf();return typeof c=="number"&&typeof u=="number"?We(Math.abs(c-u)<.01):fi(c)&&fi(u)?We(bA(c,u)):We(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"?K0({...c,id:void 0},{...u,id:void 0}):typeof c=="string"&&typeof u=="string"?c.toLowerCase()===u.toLowerCase():c===u)}function lE(e,t){var i,s;const n=(i=e.value)==null?void 0:i.valueOf(),r=(s=t.value)==null?void 0:s.valueOf();return typeof n=="number"&&typeof r=="number"?n-r:typeof n=="string"&&typeof r=="string"?n.localeCompare(r):0}function yA(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 q$(n);case"DateTime":return Lh(n);case"Time":return typeof n=="string"&&!!/^T\d/.exec(n);case"Period":return xA(n);case"Quantity":return fi(n);default:return e.type===r||typeof n=="object"&&(n==null?void 0:n.resourceType)===r}}function q$(e){return typeof e=="string"&&!!pA.date.exec(e)}function Lh(e){return typeof e=="string"&&!!pA.dateTime.exec(e)}function xA(e){return!!(e&&typeof e=="object"&&("start"in e&&Lh(e.start)||"end"in e&&Lh(e.end)))}function fi(e){return!!(e&&typeof e=="object"&&"value"in e&&typeof e.value=="number")}function bA(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 K0(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(cE(s)&&cE(c)){if(!K0(s,c))return!1}else if(s!==c)return!1}return!0}function cE(e){return e!==null&&typeof e=="object"}function uE(e,t){if(t){if(typeof t!="object")throw new Error("Primitive extension must be an object");return G$(e??{},t)}return e}function G$(e,t){return delete t.__proto__,delete t.constructor,Object.assign(e,t)}function Q$(e,t){return fa(e,t)&&"id"in e&&typeof e.id=="string"}function on(e){const t=zt(e)??"undefined/undefined",n=Va(e);return n===t?{reference:t}:{reference:t,display:n}}function zt(e){if(Ko(e))return e.reference;if(Q$(e))return`${e.resourceType}/${e.id}`}function Bs(e){if(e)return Ko(e)?e.reference.split("/")[1]:e.id}function W$(e){return e.resourceType==="Patient"||e.resourceType==="Practitioner"||e.resourceType==="RelatedPerson"}function Va(e){if(W$(e)){const t=Y$(e);if(t)return t}if(e.resourceType==="Device"){const t=K$(e);if(t)return t}if(e.resourceType==="MedicationRequest"&&e.medicationCodeableConcept)return Fo(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]),CA(t))return Fo(t);if(oU(t))return t.text}return zt(e)??""}function Y$(e){const t=e.name;if(t&&t.length>0)return Nc(t[0])}function K$(e){const t=e.deviceName;if(t&&t.length>0)return t[0].name}function X$(e){if(!("photo"in e))return;const t=e.photo;if(t)if(Array.isArray(t))for(const n of t){const r=dE(n);if(r)return r}else return dE(t)}function dE(e){var t;if(e.url&&((t=e.contentType)!=null&&t.startsWith("image/")))return e.url}function SA(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(),p=r.getUTCDate();let m=u-i;(f<s||f===s&&p<c)&&m--;let g=u*12+f-(i*12+s);p<c&&g--;const y=Math.floor((r.getTime()-n.getTime())/(1e3*60*60*24));return{years:m,months:g,days:y}}function Z$(e,t){const{years:n,months:r,days:i}=SA(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 Ja(e,...t){var r;let n=e;for(let i=0;i<t.length&&n;i++)n=(r=n==null?void 0:n.extension)==null?void 0:r.find(s=>s.url===t[i]);return n}function Ii(e,t){const n=X0(e);return JSON.stringify(n,null,t?2:void 0)??""}function X0(e){if(!(e==null||e===""))return typeof e=="object"?Array.isArray(e)?J$(e):eU(e):e}function J$(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=X0(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 eU(e){let t,n=0;for(const r in e){const i=e[r],s=X0(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 Rn(e){if(e==null)return!0;const t=typeof e;return t==="string"||t==="object"?!Tn(e):!1}function Tn(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 sa(e,t,n){return e===t||Rn(e)&&Rn(t)?!0:Rn(e)||Rn(t)?!1:Array.isArray(e)&&Array.isArray(t)?tU(e,t):Array.isArray(e)||Array.isArray(t)?!1:sr(e)&&sr(t)?nU(e,t,n):(sr(e)||sr(t),!1)}function tU(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!sa(e[n],t[n]))return!1;return!0}function nU(e,t,n){const r=new Set;Object.keys(e).forEach(i=>r.add(i)),Object.keys(t).forEach(i=>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(!sa(s,c,i))return!1}return!0}function Z0(e,t){return Rn(e)?!0:Rn(t)?!1:Array.isArray(e)&&Array.isArray(t)?rU(e,t):Array.isArray(e)||Array.isArray(t)?!1:sr(e)&&sr(t)?iU(e,t):sr(e)||sr(t)?!1:e===t}function rU(e,t){return t.every(n=>e.some(r=>Z0(r,n)))}function iU(e,t){return Object.entries(t).every(([n,r])=>n in e&&Z0(e[n],r))}function Qr(e){return e===void 0?e:JSON.parse(JSON.stringify(e))}function wA(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 sr(e){return e!==null&&typeof e=="object"}function aU(e){return typeof e=="string"}function jA(e){return sr(e)&&"code"in e&&typeof e.code=="string"}function CA(e){return sr(e)&&"coding"in e&&Array.isArray(e.coding)&&e.coding.every(jA)}function oU(e){return sr(e)&&"text"in e&&typeof e.text=="string"}const EA=[];for(let e=0;e<256;e++)EA.push(e.toString(16).padStart(2,"0"));function sU(e){const t=TA(e),n=new Uint8Array(t),r=new Array(n.length);for(let i=0;i<n.length;i++)r[i]=EA[n[i]];return r.join("")}function lU(e){const t=TA(e),n=new Uint8Array(t),r=new Array(n.length);for(let i=0;i<n.length;i++)r[i]=String.fromCharCode(n[i]);return window.btoa(r.join(""))}function TA(e){return ArrayBuffer.isView(e)?e.buffer:e}function Hn(e){return e?e.charAt(0).toUpperCase()+e.substring(1):""}function J0(e){return e.length>0&&e.startsWith(e[0].toUpperCase())}function ks(e,t){const n=e+".";if(t.startsWith(n))return t.slice(n.length)}function cU(e,t){var n,r;return(r=(n=e.coding)==null?void 0:n.find(i=>i.system===t))==null?void 0:r.code}function uU(e){if(e!==void 0)return Array.isArray(e)?e:[e]}const fE=e=>new Promise(t=>{setTimeout(t,e)});function My(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 dU(e){let t,n=!1;return function(){return n||(t=e(),n=!0),t}}function Lu(e,t){return e?(e.push(t),e):[t]}function ad(e){return e.sort((t,n)=>t.localeCompare(n))}function eb(e){return e.endsWith("/")?e:e+"/"}function fU(e){return e.startsWith("/")?e.slice(1):e}function Xi(e,t){return new URL(fU(t),eb(e.toString())).toString()}function hU(e,t){return Xi(e,t).toString().replace("http://","ws://").replace("https://","wss://")}function pU(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 RA(e,t){var n,r;return(r=(n=e==null?void 0:e.meta)==null?void 0:n.profile)!=null&&r.includes(t)||(e.meta=e.meta??{},e.meta.profile=e.meta.profile??[],e.meta.profile.push(t)),e}function mU(e,t){var n,r;if((r=(n=e==null?void 0:e.meta)==null?void 0:n.profile)!=null&&r.includes(t)){const i=e.meta.profile.indexOf(t);e.meta.profile.splice(i,1)}return e}function vc(e){if(!e)return"";switch(e.type){case"Address":return DA(e.value);case"CodeableConcept":return Fo(e.value);case"Coding":return Ad(e.value);case"ContactPoint":return e.value.value;case"HumanName":return Nc(e.value);case"Quantity":return Ps(e.value);case"Reference":return gU(e.value);default:return e.value.toString()}}function gU(e){return e?e.display??e.reference??Ii(e):""}function DA(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!=null&&t.use)&&n.push("["+e.use+"]"),n.join(", ").trim()}function Nc(e,t){if(!e)return"";const n=[];if(e.prefix&&(t==null?void 0:t.prefix)!==!1&&n.push(...e.prefix),e.given&&n.push(...e.given),e.family&&n.push(e.family),e.suffix&&(t==null?void 0:t.suffix)!==!1&&n.push(...e.suffix),e.use&&(t!=null&&t.all||t!=null&&t.use)&&n.push("["+e.use+"]"),n.length===0){const r=sd(e.text);if(r)return r}return n.join(" ").trim()}function Wp(e){return e instanceof Date&&!isNaN(e.getTime())}function vU(e,t,n){if(!e)return"";const r=new Date("2000-01-01T"+e+"Z");return Wp(r)?r.toLocaleTimeString(t,n):""}function gr(e,t,n){if(!e)return"";const r=new Date(e);return Wp(r)?r.toLocaleString(t,n):""}function yU(e,t,n){return!e||!e.start&&!e.end?"":gr(e.start,t,n)+" - "+gr(e.end,t,n)}const xU={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},bU={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},SU={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function AA(e){if(!e)return"";const t=[];return wU(t,e.repeat),e.event&&t.push(e.event.map(n=>gr(n)).join(", ")),Hn(t.join(" ").trim())}function wU(e,t){if(!(t!=null&&t.periodUnit))return;const n=t.frequency??1,r=t.period??1,i=t.periodUnit;n===1&&r===1?e.push(xU[i]):(n===1?e.push("once"):e.push(n+" times"),r===1?e.push("per "+bU[i]):e.push("per "+r+" "+SU[i])),t.dayOfWeek&&e.push("on "+t.dayOfWeek.map(Hn).join(", ")),t.timeOfDay&&e.push("at "+t.timeOfDay.map(s=>vU(s)).join(", "))}function od(e,t,n=!1){if(n&&t===void 0)throw new Error("Precision must be specified for exclusive ranges");const r=(e==null?void 0:e.low)&&{...e.low,comparator:void 0},i=(e==null?void 0:e.high)&&{...e.high,comparator:void 0};return(r==null?void 0:r.value)===void 0&&(i==null?void 0:i.value)===void 0?"":(r==null?void 0:r.value)!==void 0&&(i==null?void 0:i.value)===void 0?`>= ${Ps(r)}`:(r==null?void 0:r.value)===void 0&&(i==null?void 0:i.value)!==void 0?`<= ${Ps(i)}`:((r==null?void 0:r.unit)===(i==null?void 0:i.unit)&&(r==null||delete r.unit),`${Ps(r)} - ${Ps(i)}`)}function Ps(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[n.length-1]!==" "&&n.push(" "),n.push(e.unit)),n.join("").trim()}function jU(e){return(e==null?void 0:e.value)===void 0?"":e.value.toLocaleString(void 0,{style:"currency",currency:e.currency??"USD",currencyDisplay:"narrowSymbol"})}function Fo(e){if(!e)return"";const t=sd(e.text);return t||(e.coding?e.coding.map(n=>Ad(n)).join(", "):"")}function Ad(e,t){const n=sd(e==null?void 0:e.display);return n?`${n}`:sd(e==null?void 0:e.code)??""}function _A(e){if(!e)return"";const t=[];if(e.valueQuantity)t.push(Ps(e.valueQuantity));else if(e.valueCodeableConcept)t.push(Fo(e.valueCodeableConcept));else{const n=sd(e.valueString);n&&t.push(n)}return"component"in e&&t.push(e.component.map(n=>_A(n)).join(" / ")),t.join(" / ").trim()}function sd(e){return typeof e=="string"?e:void 0}const oe={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",Expression:"Expression",Extension:"Extension",HumanName:"HumanName",Identifier:"Identifier",MarketingStatus:"MarketingStatus",Meta:"Meta",Money:"Money",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",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"};function CU(e){var n;const t=Array.isArray(e)?e:((n=e.entry)==null?void 0:n.map(r=>r.resource))??[];for(const r of t)(r==null?void 0:r.resourceType)==="StructureDefinition"&&r.kind==="resource"&&kA(r.type)}function kA(e){let t=la.types[e];return t||(t={searchParamsDetails:{}},la.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 EU(e){for(const t of e.base??[]){const n=kA(t);n.searchParams||(n.searchParams={}),n.searchParams[e.code]=e}}function hE(e){var n,r,i,s;const t=(r=(n=e.type)==null?void 0:n[0])==null?void 0:r.code;return t==="BackboneElement"||t==="Element"?TU((s=((i=e.base)==null?void 0:i.path)??e.path)==null?void 0:s.split(".")):t}function TU(e){return e.length===1?e[0]:e.map(Hn).join("")}function tb(e){var t;return(t=la.types[e])==null?void 0:t.searchParams}function RU(e,t){var n,r;return(r=(n=la.types[e])==null?void 0:n.searchParams)==null?void 0:r[t]}function Vs(e){const t=e.replaceAll("[x]","").split(".").pop();return PA(t)}function PA(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(AU).join(" ").replace("_"," ").replace(/\s+/g," ")}const DU=new Set(["ID","IP","PKCE","JWKS","URI","URL","OMB","UDI"]);function AU(e){const t=e.toUpperCase();return e===t?e:DU.has(t)?t:t.charAt(0)+e.slice(1)}function Yo(e,t,n){const r=Gp(e,n);if(r)return _U(r.elements,t)}function _U(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 fa(e,t){return!(!e||typeof e!="object"||!("resourceType"in e)||t&&e.resourceType!==t)}function Ko(e){return!!(e&&typeof e=="object"&&"reference"in e&&typeof e.reference=="string")}const la={types:{}};function xh(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=()=>[],Tr={empty:(e,t)=>We(t.length===0||t.every(n=>Rn(n.value))),hasValue:(e,t)=>We(t.length!==0),exists:(e,t,n)=>We(n?t.filter(r=>ea(n.eval(e,[r]))).length>0:t.length>0&&t.every(r=>!Rn(r.value))),all:(e,t,n)=>We(t.every(r=>ea(n.eval(e,[r])))),allTrue:(e,t)=>{for(const n of t)if(!n.value)return We(!1);return We(!0)},anyTrue:(e,t)=>{for(const n of t)if(n.value)return We(!0);return We(!1)},allFalse:(e,t)=>{for(const n of t)if(n.value)return We(!1);return We(!0)},anyFalse:(e,t)=>{for(const n of t)if(!n.value)return We(!0);return We(!1)},subsetOf:(e,t,n)=>{if(t.length===0)return We(!0);const r=n.eval(e,xs(e));return r.length===0?We(!1):We(t.every(i=>r.some(s=>s.value===i.value)))},supersetOf:(e,t,n)=>{const r=n.eval(e,xs(e));return r.length===0?We(!0):t.length===0?We(!1):We(r.every(i=>t.some(s=>s.value===i.value)))},count:(e,t)=>[{type:oe.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)=>We(t.length===Tr.distinct(e,t).length),where:(e,t,n)=>t.filter(r=>ea(n.eval(e,[r]))),select:(e,t,n)=>t.map(r=>n.eval({parent:e,variables:{$this:r}},[r])).flat(),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(t.length-1,t.length),tail:(e,t)=>t.length===0?[]:t.slice(1,t.length),skip:(e,t,n)=>{var i;const r=(i=n.eval(e,t)[0])==null?void 0:i.value;if(typeof r!="number")throw new Error("Expected a number for skip(num)");return r>=t.length?[]:r<=0?t:t.slice(r,t.length)},take:(e,t,n)=>{var i;const r=(i=n.eval(e,t)[0])==null?void 0:i.value;if(typeof r!="number")throw new Error("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,xs(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,xs(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,xs(e));return gA([...t,...r])},combine:(e,t,n)=>{if(!n)return t;const r=n.eval(e,xs(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 ea(s)?r.eval(e,t):i?i.eval(e,t):[]},toBoolean:(e,t)=>{if(t.length===0)return[];const[{value:n}]=Zi(t,1);if(typeof n=="boolean")return[{type:oe.boolean,value:n}];if(typeof n=="number"&&(n===0||n===1))return We(!!n);if(typeof n=="string"){const r=n.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(r))return We(!0);if(["false","f","no","n","0","0.0"].includes(r))return We(!1)}return[]},convertsToBoolean:(e,t)=>t.length===0?[]:We(Tr.toBoolean(e,t).length===1),toInteger:(e,t)=>{if(t.length===0)return[];const[{value:n}]=Zi(t,1);return typeof n=="number"?[{type:oe.integer,value:n}]:typeof n=="string"&&/^[+-]?\d+$/.exec(n)?[{type:oe.integer,value:parseInt(n,10)}]:typeof n=="boolean"?[{type:oe.integer,value:n?1:0}]:[]},convertsToInteger:(e,t)=>t.length===0?[]:We(Tr.toInteger(e,t).length===1),toDate:(e,t)=>{if(t.length===0)return[];const[{value:n}]=Zi(t,1);return typeof n=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(n)?[{type:oe.date,value:xh(n)}]:[]},convertsToDate:(e,t)=>t.length===0?[]:We(Tr.toDate(e,t).length===1),toDateTime:(e,t)=>{if(t.length===0)return[];const[{value:n}]=Zi(t,1);return typeof n=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(n)?[{type:oe.dateTime,value:xh(n)}]:[]},convertsToDateTime:(e,t)=>t.length===0?[]:We(Tr.toDateTime(e,t).length===1),toDecimal:(e,t)=>{if(t.length===0)return[];const[{value:n}]=Zi(t,1);return typeof n=="number"?[{type:oe.decimal,value:n}]:typeof n=="string"&&/^-?\d{1,9}(\.\d{1,9})?$/.exec(n)?[{type:oe.decimal,value:parseFloat(n)}]:typeof n=="boolean"?[{type:oe.decimal,value:n?1:0}]:[]},convertsToDecimal:(e,t)=>t.length===0?[]:We(Tr.toDecimal(e,t).length===1),toQuantity:(e,t)=>{if(t.length===0)return[];const[{value:n}]=Zi(t,1);return fi(n)?[{type:oe.Quantity,value:n}]:typeof n=="number"?[{type:oe.Quantity,value:{value:n,unit:"1"}}]:typeof n=="string"&&/^-?\d{1,9}(\.\d{1,9})?/.exec(n)?[{type:oe.Quantity,value:{value:parseFloat(n),unit:"1"}}]:typeof n=="boolean"?[{type:oe.Quantity,value:{value:n?1:0,unit:"1"}}]:[]},convertsToQuantity:(e,t)=>t.length===0?[]:We(Tr.toQuantity(e,t).length===1),toString:(e,t)=>{if(t.length===0)return[];const[{value:n}]=Zi(t,1);return n==null?[]:fi(n)?[{type:oe.string,value:`${n.value} '${n.unit}'`}]:[{type:oe.string,value:n.toString()}]},convertsToString:(e,t)=>t.length===0?[]:We(Tr.toString(e,t).length===1),toTime:(e,t)=>{if(t.length===0)return[];const[{value:n}]=Zi(t,1);if(typeof n=="string"){const r=/^T?(\d{2}(:\d{2}(:\d{2})?)?)/.exec(n);if(r)return[{type:oe.time,value:xh("T"+r[1])}]}return[]},convertsToTime:(e,t)=>t.length===0?[]:We(Tr.toTime(e,t).length===1),indexOf:(e,t,n)=>li((r,i)=>r.indexOf(i),e,t,n),substring:(e,t,n,r)=>li((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)=>li((r,i)=>r.startsWith(i),e,t,n),endsWith:(e,t,n)=>li((r,i)=>r.endsWith(i),e,t,n),contains:(e,t,n)=>li((r,i)=>r.includes(i),e,t,n),upper:(e,t)=>li(n=>n.toUpperCase(),e,t),lower:(e,t)=>li(n=>n.toLowerCase(),e,t),replace:(e,t,n,r)=>li((i,s,c)=>i.replaceAll(s,c),e,t,n,r),matches:(e,t,n)=>li((r,i)=>!!new RegExp(i).exec(r),e,t,n),replaceMatches:(e,t,n,r)=>li((i,s,c)=>i.replaceAll(new RegExp(s,"g"),c),e,t,n,r),length:(e,t)=>li(n=>n.length,e,t),toChars:(e,t)=>li(n=>n?n.split(""):void 0,e,t),encode:Pa,decode:Pa,escape:Pa,unescape:Pa,trim:Pa,split:Pa,join:(e,t,n)=>{var i;const r=((i=n==null?void 0:n.eval(e,xs(e))[0])==null?void 0:i.value)??"";if(typeof r!="string")throw new Error("Separator must be a string.");return[{type:oe.string,value:t.map(s=>{var c;return((c=s.value)==null?void 0:c.toString())??""}).join(r)}]},abs:(e,t)=>Yi(Math.abs,e,t),ceiling:(e,t)=>Yi(Math.ceil,e,t),exp:(e,t)=>Yi(Math.exp,e,t),floor:(e,t)=>Yi(Math.floor,e,t),ln:(e,t)=>Yi(Math.log,e,t),log:(e,t,n)=>Yi((r,i)=>Math.log(r)/Math.log(i),e,t,n),power:(e,t,n)=>Yi(Math.pow,e,t,n),round:(e,t)=>Yi(Math.round,e,t),sqrt:(e,t)=>Yi(Math.sqrt,e,t),truncate:(e,t)=>Yi(n=>n|0,e,t),children:Pa,descendants:Pa,trace:(e,t,n)=>t,now:()=>[{type:oe.dateTime,value:new Date().toISOString()}],timeOfDay:()=>[{type:oe.time,value:new Date().toISOString().substring(11)}],today:()=>[{type:oe.date,value:new Date().toISOString().substring(0,10)}],between:(e,t,n,r,i)=>{var p;const s=Tr.toDateTime(e,n.eval(e,t));if(s.length===0)throw new Error("Invalid start date");const c=Tr.toDateTime(e,r.eval(e,t));if(c.length===0)throw new Error("Invalid end date");const u=(p=i.eval(e,t)[0])==null?void 0:p.value;if(u!=="years"&&u!=="months"&&u!=="days")throw new Error("Invalid units");const f=SA(s[0].value,c[0].value);return[{type:oe.Quantity,value:{value:f[u],unit:u}}]},is:(e,t,n)=>{let r="";return n instanceof zh?r=n.name:n instanceof nb&&(r=n.left.name+"."+n.right.name),r?t.map(i=>({type:oe.boolean,value:yA(i,r)})):[]},not:(e,t)=>Tr.toBoolean(e,t).map(n=>({type:oe.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!=null&&i.includes("?")){const[s]=i.split("?");return{type:s,value:{resourceType:s}}}if(i!=null&&i.includes("/")){const[s,c]=i.split("/");return{type:s,value:{resourceType:s,id:c}}}return{type:oe.BackboneElement,value:void 0}}).filter(n=>!!n.value),as:(e,t)=>t,type:(e,t)=>t.map(({value:n})=>typeof n=="boolean"?{type:oe.BackboneElement,value:{namespace:"System",name:"Boolean"}}:typeof n=="number"?{type:oe.BackboneElement,value:{namespace:"System",name:"Integer"}}:fa(n)?{type:oe.BackboneElement,value:{namespace:"FHIR",name:n.resourceType}}:{type:oe.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=>{var c;return{type:oe.boolean,value:((c=s.value)==null?void 0:c.resourceType)===i}})},getResourceKey:(e,t)=>{const n=t[0].value;return n!=null&&n.id?[{type:oe.id,value:n.id}]:[]},getReferenceKey:(e,t,n)=>{const r=t[0].value;if(!(r!=null&&r.reference))return[];let i="";return n instanceof zh&&(i=n.name),i&&!r.reference.startsWith(i+"/")?[]:[{type:oe.id,value:Bs(r)}]},extension:(e,t,n)=>{var s;const r=n.eval(e,t)[0].value,i=(s=t==null?void 0:t[0])==null?void 0:s.value;if(i){const c=Ja(i,r);if(c)return[{type:oe.Extension,value:c}]}return[]}};function li(e,t,n,...r){if(n.length===0)return[];const[{value:i}]=Zi(n,1);if(typeof i!="string")throw new Error("String function cannot be called with non-string");const s=e(i,...r.map(c=>{var u;return(u=c==null?void 0:c.eval(t,n)[0])==null?void 0:u.value}));return s===void 0?[]:Array.isArray(s)?s.map(mi):[mi(s)]}function Yi(e,t,n,...r){if(n.length===0)return[];const[{value:i}]=Zi(n,1),s=fi(i),c=s?i.value:i;if(typeof c!="number")throw new Error("Math function cannot be called with non-number");const u=e(c,...r.map(m=>{var g;return(g=m.eval(t,n)[0])==null?void 0:g.value})),f=s?oe.Quantity:n[0].type,p=s?{...i,value:u}:u;return[{type:f,value:p}]}function Zi(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 xs(e){var n;let t=e;for(;(n=t.parent)!=null&&n.variables.$this;)t=t.parent;return[t.variables.$this]}class NA{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 Yl{constructor(t){this.value=t}eval(){return[this.value]}toString(){const t=this.value.value;return typeof t=="string"?`'${t}'`:t.toString()}}class zh{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==null?void 0: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 fa(n,this.name)?t:gc(t,this.name)}toString(){return this.name}}class kU{eval(){return[]}toString(){return"{}"}}class PU extends l8{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 $h extends Td{constructor(t,n){super("as",t,n)}eval(t,n){return Tr.ofType(t,this.left.eval(t,n),this.right)}}class Nr extends Td{}class Di extends Nr{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=fi(s)?s.value:s,f=fi(c)?c.value:c,p=this.impl(u,f);return typeof p=="boolean"?We(p):fi(s)?[{type:oe.Quantity,value:{...s,value:p}}]:[mi(p)]}}class NU extends Td{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:oe.string,value:s.map(c=>c.value).join("")}]:s}}class OU extends Nr{constructor(t,n){super("contains",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return We(r.some(s=>s.value===i[0].value))}}class MU extends Nr{constructor(t,n){super("in",t,n)}eval(t,n){const r=Ba(this.left.eval(t,n)),i=this.right.eval(t,n);return r?We(i.some(s=>Qp(r,s)[0].value)):[]}}class nb extends Td{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 rb extends Td{constructor(t,n){super("|",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return gA([...r,...i])}}class IU extends Nr{constructor(t,n){super("=",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return V$(r,i)}}class LU extends Nr{constructor(t,n){super("!=",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return F$(r,i)}}class zU extends Nr{constructor(t,n){super("~",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return vA(r,i)}}class $U extends Nr{constructor(t,n){super("!~",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return B$(vA(r,i))}}class ib extends Nr{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 We(yA(r[0],i))}}class UU extends Nr{constructor(t,n){super("and",t,n)}eval(t,n){const r=Ba(this.left.eval(t,n),"boolean"),i=Ba(this.right.eval(t,n),"boolean");return(r==null?void 0:r.value)===!0&&(i==null?void 0:i.value)===!0?We(!0):(r==null?void 0:r.value)===!1||(i==null?void 0:i.value)===!1?We(!1):[]}}class BU extends Nr{constructor(t,n){super("or",t,n)}eval(t,n){const r=Ba(this.left.eval(t,n),"boolean"),i=Ba(this.right.eval(t,n),"boolean");return(r==null?void 0:r.value)===!1&&(i==null?void 0:i.value)===!1?We(!1):r!=null&&r.value||i!=null&&i.value?We(!0):[]}}class VU extends Nr{constructor(t,n){super("xor",t,n)}eval(t,n){const r=Ba(this.left.eval(t,n),"boolean"),i=Ba(this.right.eval(t,n),"boolean");return!r||!i?[]:We(r.value!==i.value)}}class FU extends Nr{constructor(t,n){super("implies",t,n)}eval(t,n){const r=Ba(this.left.eval(t,n),"boolean"),i=Ba(this.right.eval(t,n),"boolean");return(i==null?void 0:i.value)===!0||(r==null?void 0:r.value)===!1?We(!0):!r||!i?[]:We(!1)}}class ab{constructor(t,n){this.name=t,this.args=n}eval(t,n){const r=Tr[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 ob{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 HU=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"];class qU{constructor(t,n,r,i){this.result=[],this.pos={index:0,line:1,column:0},this.markStack=[],this.str=t,this.keywords=n,this.operators=r,this.dateTimeLiterals=!!(i!=null&&i.dateTimeLiterals),this.symbolRegex=(i==null?void 0: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()!==`
77
77
  `))}consumeString(t){this.advance();const r=this.consumeWhile(()=>this.prev()==="\\"||this.curr()!==t).replace(/\\u([0-9a-fA-F]{4})/g,(s,c)=>String.fromCodePoint(parseInt(c,16))),i=this.buildToken(t==="`"?"Symbol":"String",r);return this.advance(),i}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()===" "&&GU(this.peekToken())&&(n="Quantity",this.consumeToken()),this.buildToken(n,this.str.substring(t,this.pos.index)))}consumeSymbol(){var n;const t=this.consumeWhile(()=>this.symbolRegex.exec(this.curr()));return((n=this.prevToken())==null?void 0:n.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]}prev(){return this.str[this.pos.index-1]??""}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()===`
78
- `?(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 GU(e){return!!(e&&(e.id==="String"||e.id==="Symbol"&&HU.includes(e.value)))}const QU=["true","false"],WU=["!=","!~","<=",">=","{}","->"];function YU(e){return new qU(e,QU,WU).tokenize()}const Xt={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},KU={parse(e){var n;const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+((n=e.peek())==null?void 0:n.value)+"`");return t}},XU={parse(e,t){const n=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new ob(t,n)},precedence:Xt.Indexer},ZU={parse(e,t){if(!(t instanceof zh))throw new Error("Unexpected parentheses");const n=[];for(;!e.match(")");)n.push(e.consumeAndParse()),e.match(",");return new ab(t.name,n)},precedence:Xt.FunctionCall};function JU(e){const t=e.split(" "),n=parseFloat(t[0]);let r=t[1];return r!=null&&r.startsWith("'")&&r.endsWith("'")?r=r.substring(1,r.length-1):r="{"+r+"}",{value:n,unit:r}}function eB(){return new c8().registerPrefix("String",{parse:(e,t)=>new Yl({type:oe.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new Yl({type:oe.dateTime,value:xh(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new Yl({type:oe.Quantity,value:JU(t.value)})}).registerPrefix("Number",{parse:(e,t)=>new Yl({type:t.value.includes(".")?oe.decimal:oe.integer,value:parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new Yl({type:oe.boolean,value:!0})}).registerPrefix("false",{parse:()=>new Yl({type:oe.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new zh(t.value)}).registerPrefix("{}",{parse:()=>new kU}).registerPrefix("(",KU).registerInfix("[",XU).registerInfix("(",ZU).prefix("+",Xt.UnaryAdd,(e,t)=>new PU("+",t,n=>n)).prefix("-",Xt.UnarySubtract,(e,t)=>new Di("-",t,t,(n,r)=>-r)).infixLeft(".",Xt.Dot,(e,t,n)=>new nb(e,n)).infixLeft("/",Xt.Divide,(e,t,n)=>new Di("/",e,n,(r,i)=>r/i)).infixLeft("*",Xt.Multiply,(e,t,n)=>new Di("*",e,n,(r,i)=>r*i)).infixLeft("+",Xt.Add,(e,t,n)=>new Di("+",e,n,(r,i)=>r+i)).infixLeft("-",Xt.Subtract,(e,t,n)=>new Di("-",e,n,(r,i)=>r-i)).infixLeft("|",Xt.Union,(e,t,n)=>new rb(e,n)).infixLeft("=",Xt.Equals,(e,t,n)=>new IU(e,n)).infixLeft("!=",Xt.NotEquals,(e,t,n)=>new LU(e,n)).infixLeft("~",Xt.Equivalent,(e,t,n)=>new zU(e,n)).infixLeft("!~",Xt.NotEquivalent,(e,t,n)=>new $U(e,n)).infixLeft("<",Xt.LessThan,(e,t,n)=>new Di("<",e,n,(r,i)=>r<i)).infixLeft("<=",Xt.LessThanOrEquals,(e,t,n)=>new Di("<=",e,n,(r,i)=>r<=i)).infixLeft(">",Xt.GreaterThan,(e,t,n)=>new Di(">",e,n,(r,i)=>r>i)).infixLeft(">=",Xt.GreaterThanOrEquals,(e,t,n)=>new Di(">=",e,n,(r,i)=>r>=i)).infixLeft("&",Xt.Ampersand,(e,t,n)=>new NU(e,n)).infixLeft("and",Xt.And,(e,t,n)=>new UU(e,n)).infixLeft("as",Xt.As,(e,t,n)=>new $h(e,n)).infixLeft("contains",Xt.Contains,(e,t,n)=>new OU(e,n)).infixLeft("div",Xt.Divide,(e,t,n)=>new Di("div",e,n,(r,i)=>r/i|0)).infixLeft("in",Xt.In,(e,t,n)=>new MU(e,n)).infixLeft("is",Xt.Is,(e,t,n)=>new ib(e,n)).infixLeft("mod",Xt.Modulo,(e,t,n)=>new Di("mod",e,n,(r,i)=>r%i)).infixLeft("or",Xt.Or,(e,t,n)=>new BU(e,n)).infixLeft("xor",Xt.Xor,(e,t,n)=>new VU(e,n)).infixLeft("implies",Xt.Implies,(e,t,n)=>new FU(e,n))}const tB=eB();function sb(e){return new NA(e,tB.construct(YU(e)).consumeAndParse())}function Oc(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 Fs(e,n).map(r=>r.value)}function Fs(e,t,n={},r=void 0){let i;if(typeof e=="string"){const s=r==null?void 0:r.get(e);i=s??sb(e),r&&!s&&r.set(e,i)}else i=e;return i.eval({variables:n},t).map(s=>{var c;return{type:s.type,value:(c=s.value)==null?void 0:c.valueOf()}})}const Jn={BOOLEAN:"BOOLEAN",NUMBER:"NUMBER",QUANTITY:"QUANTITY",TEXT:"TEXT",REFERENCE:"REFERENCE",CANONICAL:"CANONICAL",DATE:"DATE",DATETIME:"DATETIME"};function Mc(e,t){var r,i;let n=(i=(r=la.types[e])==null?void 0:r.searchParamsDetails)==null?void 0:i[t.code];return n||(n=rB(e,t)),n}function nB(e,t,n){let r=la.types[e];r||(r={},la.types[e]=r),r.searchParamsDetails||(r.searchParamsDetails={}),r.searchParamsDetails[t]=n}function rB(e,t){const n=t.code,r=sB(e,t.expression),i={elementDefinitions:[],propertyTypes:new Set,array:!1};for(const c of r){const u=bh(c),f=dU(()=>u.join("."));u.length===1&&u[0]instanceof Nr?i.propertyTypes.add("boolean"):t.code.endsWith(":identifier")?i.propertyTypes.add("Identifier"):f().endsWith("extension.value.code")||f().endsWith("extension.value.coding.code")?(i.array=!0,i.propertyTypes.add("code")):OA(i,u,e,1),f().endsWith("extension.valueDateTime")&&(i.array=!1)}const s={type:oB(t,i.propertyTypes),elementDefinitions:i.elementDefinitions,parsedExpression:lB(e,t.expression),array:i.array};return nB(e,n,s),s}function OA(e,t,n,r){const i=t[r];if(i instanceof $h){e.propertyTypes.add(i.right.toString());return}if(i instanceof ab){iB(e,i);return}const s=i.toString(),c=Yo(n,s);if(!c)throw new Error(`Element definition not found for ${n} ${s}`);let u=!1,f=r+1;f<t.length&&t[f]instanceof ob&&(u=!0,f++);const p=t[f];if(c.isArray&&!u&&(e.array=!0),f===t.length-1&&p instanceof $h){e.elementDefinitions.push(c),e.propertyTypes.add(p.right.toString());return}if(f>=t.length){e.elementDefinitions.push(c);for(const m of c.type)e.propertyTypes.add(m.code);return}for(const m of c.type){let g=m.code;aB(g)&&(g=c.type[0].code),OA(e,t,g,f)}}function iB(e,t){if(t.name==="as"){e.propertyTypes.add(t.args[0].toString());return}if(t.name==="ofType"){e.propertyTypes.add(t.args[0].toString());return}if(t.name==="resolve"){e.propertyTypes.add("string");return}if(t.name==="where"&&t.args[0]instanceof ib){e.propertyTypes.add(t.args[0].right.toString());return}throw new Error(`Unhandled FHIRPath function: ${t.name}`)}function aB(e){return e==="Element"||e==="BackboneElement"}function oB(e,t){switch(e.type){case"date":return t.size===1&&t.has(oe.date)?Jn.DATE:Jn.DATETIME;case"number":return Jn.NUMBER;case"quantity":return Jn.QUANTITY;case"reference":return t.has(oe.canonical)?Jn.CANONICAL:Jn.REFERENCE;case"token":return t.size===1&&t.has(oe.boolean)?Jn.BOOLEAN:Jn.TEXT;default:return Jn.TEXT}}function sB(e,t){const n=[],r=sb(t);return Uh(e,r.child,n),n}function lB(e,t){const n=[],r=sb(t);if(Uh(e,r.child,n),n.length===0)return r;let i=n[0];for(let s=1;s<n.length;s++)i=new rb(i,n[s]);return new NA("<original-not-available>",i)}function Uh(e,t,n){t instanceof rb?(Uh(e,t.left,n),Uh(e,t.right,n)):t.toString().includes(e+".")&&n.push(t)}function bh(e){if(e instanceof $h||e instanceof ob)return[bh(e.left),e].flat();if(e instanceof Nr)return[e];if(e instanceof nb)return[bh(e.left),bh(e.right)].flat();if(e instanceof ab){if(e.name==="where"&&!(e.args[0]instanceof ib))return[];if(e.name==="last")return[]}return[e]}const Yp=20,ue={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"},MA={contains:ue.CONTAINS,exact:ue.EXACT,above:ue.ABOVE,below:ue.BELOW,text:ue.TEXT,not:ue.NOT,in:ue.IN,"not-in":ue.NOT_IN,"of-type":ue.OF_TYPE,missing:ue.MISSING,identifier:ue.IDENTIFIER,iterate:ue.ITERATE},lb={eq:ue.EQUALS,ne:ue.NOT_EQUALS,lt:ue.LESS_THAN,le:ue.LESS_THAN_OR_EQUALS,gt:ue.GREATER_THAN,ge:ue.GREATER_THAN_OR_EQUALS,sa:ue.STARTS_AFTER,eb:ue.ENDS_BEFORE,ap:ue.APPROXIMATELY,sw:ue.STARTS_WITH};function IA(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()),cB(i,s)}function cB(e,t){const n={resourceType:e};for(const[r,i]of t)uB(n,r,i);return n}function uB(e,t,n){var c,u;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=Lu(e.filters,{code:t,operator:ue.EQUALS,value:n});return}switch(r){case"_sort":dB(e,n);break;case"_cursor":e.cursor=n;break;case"_count":e.count=parseInt(n,10);break;case"_offset":e.offset=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 f=pE(n);i==="iterate"&&(f.modifier=ue.ITERATE),e.include=Lu(e.include,f);break}case"_revinclude":{const f=pE(n);i==="iterate"&&(f.modifier=ue.ITERATE),e.revInclude=Lu(e.revInclude,f);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 f=(u=(c=la.types[e.resourceType])==null?void 0:c.searchParams)==null?void 0:u[r];f?e.filters=Lu(e.filters,hB(f,i,n)):e.filters=Lu(e.filters,pB(r,i,n))}}}}function dB(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 fB=[ue.MISSING,ue.PRESENT];function hB(e,t,n){if(fB.includes(t))return{code:e.code,operator:t,value:n};switch(e.type){case"number":case"date":case"quantity":{const{operator:r,value:i}=mB(n);if(!mE(e,i))throw new dt(ra(`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(!mE(e,n))throw new dt(ra(`Invalid format for ${e.type} search parameter: ${n}`));return{code:e.code,operator:gB(t),value:n};default:throw new Error("Unrecognized search parameter type: "+e.type)}}function pB(e,t,n){var i;let r=ue.EQUALS;if(t)r=t;else if(n.length>=2){const s=n.substring(0,2);s in lb&&(n.length===2||(i=n.at(2))!=null&&i.match(/\d/))&&(r=s,n=n.substring(s.length))}return{code:e,operator:r,value:n}}function mB(e){const t=e.substring(0,2),n=lb[t];return n?{operator:n,value:e.substring(2)}:{operator:ue.EQUALS,value:e}}function gB(e){return MA[e]??ue.EQUALS}function pE(e){const t=e.split(":");if(t.includes("*"))throw new dt(ra("'*' is not supported as a value for search inclusion parameters"));if(t.length===1)throw new dt(ra(`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 dt(ra(`Invalid include value '${e}'`))}function mE(e,t){switch(e.type){case"date":return Lh(t);default:return!0}}function Uo(e){const t=[];return e.fields&&t.push("_fields="+e.fields.join(",")),e.filters&&e.filters.forEach(n=>t.push(vB(n))),e.sortRules&&e.sortRules.length>0&&t.push(yB(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(",")),e.include&&e.include.forEach(n=>t.push(gE("_include",n))),e.revInclude&&e.revInclude.forEach(n=>t.push(gE("_revinclude",n))),t.length===0?"":(ad(t),"?"+t.join("&"))}function vB(e){const t=e.operator in MA?":"+e.operator:"",n=e.operator!==ue.EQUALS&&e.operator in lb?e.operator:"";return`${e.code}${t}=${n}${encodeURIComponent(e.value)}`}function yB(e){return"_sort="+e.map(t=>t.descending?"-"+t.code:t.code).join(",")}function gE(e,t){return e+(t.modifier?":"+t.modifier:"")+"="+t.resourceType+":"+t.searchParam+(t.targetType?":"+t.targetType:"")}function cb(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 xB(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters){for(const n of t.filters)if(!bB(e,t,n))return!1}return!0}function bB(e,t,n){var i,s;const r=(s=(i=la.types[t.resourceType])==null?void 0:i.searchParams)==null?void 0:s[n.code];if(!r)return!1;if(n.operator===ue.MISSING||n.operator===ue.PRESENT)return SB(e,n,r);switch(r.type){case"reference":return wB(e,n,r);case"string":case"uri":return LA(e,n,r);case"token":return jB(e,n,r);case"date":return RB(e,n,r);default:return!1}}function SB(e,t,n){const i=Oc(n.expression,e).length>0;return(t.operator===ue.MISSING&&t.value==="false"||t.operator===ue.PRESENT&&t.value==="true")===i}function wB(e,t,n){const r=Oc(n.expression,e),i=Kp(t.operator);if(t.value===""&&r.length===0)return t.operator===ue.EQUALS;const s=r.map(c=>typeof c=="string"?c:c.reference);for(const c of cb(t.value)){let u=s.includes(c);if(!u&&t.code==="_compartment"&&(u=s.some(f=>f==null?void 0:f.endsWith("/"+c))),u)return!i}return i}function jB(e,t,n){return Mc(e.resourceType,n).type===Jn.BOOLEAN?CB(e,t,n):LA(e,t,n,!0)}function CB(e,t,n){const r=Oc(n.expression,e),i=t.value==="true",s=r.includes(i);return Kp(t.operator)?!s:s}function LA(e,t,n,r){var p,m,g,y;const s=(y=(g=(m=(p=Mc(e.resourceType,n).elementDefinitions)==null?void 0:p[0])==null?void 0:m.type)==null?void 0:g[0])==null?void 0:y.code,c=Oc(n.expression,e),u=cb(t.value),f=Kp(t.operator);for(const b of c)for(const S of u){let j;if(s===oe.Identifier?j=EB(b,t.operator,S):s===oe.CodeableConcept?j=TB(b,t.operator,S):j=Iy(b,t.operator,S,r),j)return!f}return f}function Iy(e,t,n,r){if(r&&n.includes("|")){const[s,c]=n.split("|");return Iy(e,t,s,!1)&&(!c||Iy(e,t,c,!1))}let i="";return e&&(typeof e=="string"?i=e:typeof e=="object"&&(i=JSON.stringify(e))),i.toLowerCase().includes(n.toLowerCase())}function EB(e,t,n){var r,i,s,c;if(n.includes("|")){const[u,f]=n.split("|").map(p=>p.toLowerCase());return!u&&!f?!1:u?((i=e.system)==null?void 0:i.toLowerCase())===u&&(!f||((s=e.value)==null?void 0:s.toLowerCase())===f):!e.system&&((r=e.value)==null?void 0:r.toLowerCase())===f}return((c=e.value)==null?void 0:c.toLowerCase())===n.toLowerCase()}function TB(e,t,n){var r,i,s,c;if(n.includes("|")){const[u,f]=n.split("|").map(p=>p.toLowerCase());return!u&&!f?!1:u?((i=e.coding)==null?void 0:i.some(p=>{var m,g;return((m=p.system)==null?void 0:m.toLowerCase())===u&&(!f||((g=p.code)==null?void 0:g.toLowerCase())===f)}))??!1:((r=e.coding)==null?void 0:r.some(p=>{var m;return!p.system&&((m=p.code)==null?void 0:m.toLowerCase())===f}))??!1}return((s=e.text)==null?void 0:s.toLowerCase())===n.toLowerCase()||(((c=e.coding)==null?void 0:c.some(u=>{var f;return((f=u.code)==null?void 0:f.toLowerCase())===n.toLowerCase()}))??!1)}function RB(e,t,n){const r=Oc(n.expression,e),i=cb(t.value),s=Kp(t.operator);for(const c of r)for(const u of i)if(DB(Bh(c),t.operator,Bh(u)))return!s;return s}function DB(e,t,n){if(!e)return!1;switch(t){case ue.STARTS_AFTER:case ue.GREATER_THAN:return e>n;case ue.GREATER_THAN_OR_EQUALS:return e>=n;case ue.ENDS_BEFORE:case ue.LESS_THAN:return e<n;case ue.LESS_THAN_OR_EQUALS:return e<=n;case ue.EQUALS:case ue.NOT_EQUALS:return e===n;default:return!1}}function Bh(e){if(aU(e))try{return new Date(e).toISOString()}catch(t){console.debug("Failed to parse date",e,t)}else if(xA(e)){if("start"in e)return Bh(e.start);if("end"in e)return Bh(e.end)}}function Kp(e){return e===ue.NOT_EQUALS||e===ue.NOT}const AB={resourceType:"*"},_B=["DomainConfiguration","JsonWebKey","Login"],kB=["PasswordChangeRequest","UserSecurityRequest","Project","ProjectMembership","User"],Ns={READ:"read",VREAD:"vread",UPDATE:"update",HISTORY:"history",SEARCH:"search"},PB=[Ns.READ,Ns.VREAD,Ns.HISTORY,Ns.SEARCH];function NB(e,t){return _B.includes(t)?!1:OB(e,Ns.UPDATE,t)}function OB(e,t,n){var r;return!!((r=e.resource)!=null&&r.some(i=>$A(i,n,t)))}function zA(e,t,n){var r;return n?(r=n.resource)==null?void 0:r.find(i=>MB(e,t,i)):AB}function MB(e,t,n){var i,s;const r=e.resourceType;return!(!$A(n,r,t)||n.compartment&&!((s=(i=e.meta)==null?void 0:i.compartment)!=null&&s.some(c=>{var u;return c.reference===((u=n.compartment)==null?void 0:u.reference)}))||n.criteria&&!xB(e,IA(n.criteria)))}function $A(e,t,n){return e.resourceType!==t&&(e.resourceType!=="*"||kB.includes(t))?!1:e.interaction?e.interaction.includes(n):!e.readonly||PB.includes(n)}function IB(e){if(typeof window<"u"){const t=window.atob(e),n=Uint8Array.from(t,r=>r.charCodeAt(0));return new window.TextDecoder().decode(n)}if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf-8");throw new Error("Unable to decode base64")}function vE(e){if(typeof window<"u"){const t=new window.TextEncoder().encode(e),n=String.fromCharCode.apply(null,t);return window.btoa(n)}if(typeof Buffer<"u")return Buffer.from(e,"utf8").toString("base64");throw new Error("Unable to encode base64")}function LB(e){e=e.padEnd(e.length+(4-e.length%4)%4,"=");const t=e.replace(/-/g,"+").replace(/_/g,"/");return IB(t)}function yE(){const e=new Uint32Array(28);return crypto.getRandomValues(e),sU(e.buffer)}async function zB(e){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))}function UA(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function BA(e){var i;const t={};e=Qr(e);for(const s of e.entry||[]){const c=s.resource;if(!c)continue;c.meta!==void 0&&(delete c.meta.author,delete c.meta.compartment,delete c.meta.lastUpdated,delete c.meta.project,delete c.meta.versionId,Object.keys(c.meta).length===0&&delete c.meta);const u=c==null?void 0:c.id;u&&(t[u]=UA(),s.fullUrl="urn:uuid:"+t[u],(i=s.resource)==null||delete i.id)}const n=e.entry,r=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:n==null?void 0:n.map(s=>{var c;return{fullUrl:s.fullUrl,request:{method:"POST",url:(c=s.resource)==null?void 0:c.resourceType},resource:s.resource}})},(s,c)=>$B(s,c,t),2);return UB(JSON.parse(r))}function $B(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 UB(e){const t=VB(e),{sorted:n,cycles:r}=BB(t),i={};for(const c of e.entry??[])c.fullUrl&&(i[c.fullUrl]=c);const s=n.map(c=>i[c]);for(const c of r)for(const u of c){const f=i[u],p={...f,request:{...f.request,method:"PUT"}};s.push(p)}return{...e,entry:s}}const Kl={NotVisited:"NotVisited",Visiting:"Visiting",Visited:"Visited"};function BB(e){const t=[],n={},r=[];for(const s of Object.keys(e))n[s]=Kl.NotVisited;function i(s,c){if(n[s]===Kl.Visited)return!0;if(n[s]===Kl.Visiting){const f=c.lastIndexOf(s);return f!==-1&&r.push(c.slice(f)),!0}n[s]=Kl.Visiting,c.push(s);let u=!1;for(const f of e[s])i(f,c)||(u=!0);return n[s]=Kl.Visited,c.pop(),t.unshift(s),!u}for(const s in e)n[s]===Kl.NotVisited&&i(s,[]);return{sorted:t,cycles:r}}function VA(e,t){for(const n in e)if(e[n]&&typeof e[n]=="object"){const r=e[n];if(Ko(r)){const i=r.reference;i.startsWith("urn:uuid:")&&t(i)}else VA(r,t)}}function VB(e){const t={};for(const n of e.entry||[])n.fullUrl&&(t[n.fullUrl]=[]);for(const n of e.entry||[]){const r=n.fullUrl;n.resource&&VA(n.resource,i=>{t[i]&&t[i].push(r)})}return t}const hn={FHIR_JSON:"application/fhir+json",FORM_URL_ENCODED:"application/x-www-form-urlencoded",HL7_V2:"x-application/hl7-v2+er7",JSON:"application/json",JSON_PATCH:"application/json-patch+json",TEXT:"text/plain",PING:"x-application/ping",XML:"text/xml",CDA_XML:"application/cda+xml"};class FB{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];if(n)for(const r of n)r.call(this,t);return!t.defaultPrevented}removeAllListeners(){this.listeners={}}}class Xp{constructor(){this.emitter=new FB}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()}}const Ly={"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"},HB=["Patient","Encounter","ImagingStudy","DiagnosticReport","OperationOutcome","Bundle"],ub=["DiagnosticReport-update"];function qB(e){return ub.includes(e)}function GB(e){if(ub.includes(e))throw new dt(yn(`'context.version' is required for '${e}'.`))}const QB={"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 WB(e){return HB.includes(e)}function FA(e){return!!e.endpoint}function xE(e){if(!db(e))throw new dt(yn("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 FA(e)&&(s.endpoint=e.endpoint),new URLSearchParams(s).toString()}function db(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(!Ly[s])return!1;return!(FA(e)&&!(typeof e.endpoint=="string"&&e.endpoint.startsWith("ws")))}function YB(e,t,n,r){if(typeof t!="object")throw new dt(yn(`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 dt(yn(`context[${n}] is invalid. Resource must contain a valid string ID.`));if(!t.resourceType)throw new dt(yn(`context[${n}] is invalid. Resource must contain a resource type. No resource type found.`));const i=r.resourceType;if(i!=="*"){if(!WB(t.resourceType))throw new dt(yn(`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 dt(yn(`context[${n}] is invalid. context[${n}] for the '${e}' event should contain resource of type ${i}.`))}}function KB(e,t,n,r,i){if(i.set(t.key,(i.get(t.key)??0)+1),r.reference){if(!Ko(t.reference))throw new dt(yn(`context[${n}] is invalid. Expected key '${t.key}' to be a reference.`))}else YB(e,t.resource,n,r)}function XB(e,t){const n=new Map,r=QB[e];for(let i=0;i<t.length;i++){const s=t[i].key;if(!r[s])throw new dt(yn(`Key '${s}' not found for event '${e}'. Make sure to add only valid keys.`));KB(e,t[i],i,r[s],n)}for(const[i,s]of Object.entries(r)){if(!(s.optional||n.has(i)))throw new dt(yn(`Missing required key '${i}' on context for '${e}' event.`));if(!s.manyAllowed&&(n.get(i)??0)>1)throw new dt(yn(`${n.get(i)} context entries with key '${i}' found for the '${e}' event when schema only allows for 1.`))}}function bE(e,t,n,r){if(!(e&&typeof e=="string"))throw new dt(yn("Must provide a topic."));if(!Ly[t])throw new dt(yn(`Must provide a valid FHIRcast event name. Supported events: ${Object.keys(Ly).join(", ")}`));if(typeof n!="object")throw new dt(yn("context must be a context object or array of context objects."));if(ub.includes(t)&&!r)throw new dt(yn(`The '${t}' event must contain a 'context.versionId'.`));const i=Array.isArray(n)?n:[n];return XB(t,i),{timestamp:new Date().toISOString(),id:UA(),event:{"hub.topic":e,"hub.event":t,context:i,...r?{"context.versionId":r}:{}}}}class ZB extends Xp{constructor(t){if(super(),this.subRequest=t,!t.endpoint)throw new dt(yn("Subscription request should contain an endpoint."));if(!db(t))throw new dt(yn("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==null?void 0:i.id,timestamp:new Date().toISOString()})))}),n.addEventListener("close",()=>{this.dispatchEvent({type:"disconnect"})})}),this.websocket=n}disconnect(){this.websocket.close()}}function JB(e){return JSON.parse(LB(e))}function eV(e){return e.split(".").length===3}function fb(e){const[t,n,r]=e.split(".");return JB(n)}function tV(e){try{return typeof fb(e).login_id=="string"}catch{return!1}}function nV(e){try{const n=fb(e).exp;return typeof n=="number"?n*1e3:void 0}catch{return}}class rV{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,hn.TEXT)}async delete(t){await this.medplum.delete(`keyvalue/v1/${t}`)}}var HA;HA=Symbol.toStringTag;class Ai{constructor(t){this[HA]="ReadablePromise",this.status="pending",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 iV{constructor(t){this.storage=t??(typeof localStorage<"u"?localStorage:new aV)}clear(){this.storage.clear()}getString(t){return this.storage.getItem(t)??void 0}setString(t,n){n?this.storage.setItem(t,n):this.storage.removeItem(t)}getObject(t){const n=this.getString(t);return n?JSON.parse(n):void 0}setObject(t,n){this.setString(t,n?Ii(n):void 0)}}class aV{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]}}/*!
78
+ `?(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 GU(e){return!!(e&&(e.id==="String"||e.id==="Symbol"&&HU.includes(e.value)))}const QU=["true","false"],WU=["!=","!~","<=",">=","{}","->"];function YU(e){return new qU(e,QU,WU).tokenize()}const Xt={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},KU={parse(e){var n;const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+((n=e.peek())==null?void 0:n.value)+"`");return t}},XU={parse(e,t){const n=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new ob(t,n)},precedence:Xt.Indexer},ZU={parse(e,t){if(!(t instanceof zh))throw new Error("Unexpected parentheses");const n=[];for(;!e.match(")");)n.push(e.consumeAndParse()),e.match(",");return new ab(t.name,n)},precedence:Xt.FunctionCall};function JU(e){const t=e.split(" "),n=parseFloat(t[0]);let r=t[1];return r!=null&&r.startsWith("'")&&r.endsWith("'")?r=r.substring(1,r.length-1):r="{"+r+"}",{value:n,unit:r}}function eB(){return new c8().registerPrefix("String",{parse:(e,t)=>new Yl({type:oe.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new Yl({type:oe.dateTime,value:xh(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new Yl({type:oe.Quantity,value:JU(t.value)})}).registerPrefix("Number",{parse:(e,t)=>new Yl({type:t.value.includes(".")?oe.decimal:oe.integer,value:parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new Yl({type:oe.boolean,value:!0})}).registerPrefix("false",{parse:()=>new Yl({type:oe.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new zh(t.value)}).registerPrefix("{}",{parse:()=>new kU}).registerPrefix("(",KU).registerInfix("[",XU).registerInfix("(",ZU).prefix("+",Xt.UnaryAdd,(e,t)=>new PU("+",t,n=>n)).prefix("-",Xt.UnarySubtract,(e,t)=>new Di("-",t,t,(n,r)=>-r)).infixLeft(".",Xt.Dot,(e,t,n)=>new nb(e,n)).infixLeft("/",Xt.Divide,(e,t,n)=>new Di("/",e,n,(r,i)=>r/i)).infixLeft("*",Xt.Multiply,(e,t,n)=>new Di("*",e,n,(r,i)=>r*i)).infixLeft("+",Xt.Add,(e,t,n)=>new Di("+",e,n,(r,i)=>r+i)).infixLeft("-",Xt.Subtract,(e,t,n)=>new Di("-",e,n,(r,i)=>r-i)).infixLeft("|",Xt.Union,(e,t,n)=>new rb(e,n)).infixLeft("=",Xt.Equals,(e,t,n)=>new IU(e,n)).infixLeft("!=",Xt.NotEquals,(e,t,n)=>new LU(e,n)).infixLeft("~",Xt.Equivalent,(e,t,n)=>new zU(e,n)).infixLeft("!~",Xt.NotEquivalent,(e,t,n)=>new $U(e,n)).infixLeft("<",Xt.LessThan,(e,t,n)=>new Di("<",e,n,(r,i)=>r<i)).infixLeft("<=",Xt.LessThanOrEquals,(e,t,n)=>new Di("<=",e,n,(r,i)=>r<=i)).infixLeft(">",Xt.GreaterThan,(e,t,n)=>new Di(">",e,n,(r,i)=>r>i)).infixLeft(">=",Xt.GreaterThanOrEquals,(e,t,n)=>new Di(">=",e,n,(r,i)=>r>=i)).infixLeft("&",Xt.Ampersand,(e,t,n)=>new NU(e,n)).infixLeft("and",Xt.And,(e,t,n)=>new UU(e,n)).infixLeft("as",Xt.As,(e,t,n)=>new $h(e,n)).infixLeft("contains",Xt.Contains,(e,t,n)=>new OU(e,n)).infixLeft("div",Xt.Divide,(e,t,n)=>new Di("div",e,n,(r,i)=>r/i|0)).infixLeft("in",Xt.In,(e,t,n)=>new MU(e,n)).infixLeft("is",Xt.Is,(e,t,n)=>new ib(e,n)).infixLeft("mod",Xt.Modulo,(e,t,n)=>new Di("mod",e,n,(r,i)=>r%i)).infixLeft("or",Xt.Or,(e,t,n)=>new BU(e,n)).infixLeft("xor",Xt.Xor,(e,t,n)=>new VU(e,n)).infixLeft("implies",Xt.Implies,(e,t,n)=>new FU(e,n))}const tB=eB();function sb(e){return new NA(e,tB.construct(YU(e)).consumeAndParse())}function Oc(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 Fs(e,n).map(r=>r.value)}function Fs(e,t,n={},r=void 0){let i;if(typeof e=="string"){const s=r==null?void 0:r.get(e);i=s??sb(e),r&&!s&&r.set(e,i)}else i=e;return i.eval({variables:n},t).map(s=>{var c;return{type:s.type,value:(c=s.value)==null?void 0:c.valueOf()}})}const Jn={BOOLEAN:"BOOLEAN",NUMBER:"NUMBER",QUANTITY:"QUANTITY",TEXT:"TEXT",REFERENCE:"REFERENCE",CANONICAL:"CANONICAL",DATE:"DATE",DATETIME:"DATETIME"};function Mc(e,t){var r,i;let n=(i=(r=la.types[e])==null?void 0:r.searchParamsDetails)==null?void 0:i[t.code];return n||(n=rB(e,t)),n}function nB(e,t,n){let r=la.types[e];r||(r={},la.types[e]=r),r.searchParamsDetails||(r.searchParamsDetails={}),r.searchParamsDetails[t]=n}function rB(e,t){const n=t.code,r=sB(e,t.expression),i={elementDefinitions:[],propertyTypes:new Set,array:!1};for(const c of r){const u=bh(c),f=dU(()=>u.join("."));u.length===1&&u[0]instanceof Nr?i.propertyTypes.add("boolean"):t.code.endsWith(":identifier")?i.propertyTypes.add("Identifier"):f().endsWith("extension.value.code")||f().endsWith("extension.value.coding.code")?(i.array=!0,i.propertyTypes.add("code")):OA(i,u,e,1),f().endsWith("extension.valueDateTime")&&(i.array=!1)}const s={type:oB(t,i.propertyTypes),elementDefinitions:i.elementDefinitions,parsedExpression:lB(e,t.expression),array:i.array};return nB(e,n,s),s}function OA(e,t,n,r){const i=t[r];if(i instanceof $h){e.propertyTypes.add(i.right.toString());return}if(i instanceof ab){iB(e,i);return}const s=i.toString(),c=Yo(n,s);if(!c)throw new Error(`Element definition not found for ${n} ${s}`);let u=!1,f=r+1;f<t.length&&t[f]instanceof ob&&(u=!0,f++);const p=t[f];if(c.isArray&&!u&&(e.array=!0),f===t.length-1&&p instanceof $h){e.elementDefinitions.push(c),e.propertyTypes.add(p.right.toString());return}if(f>=t.length){e.elementDefinitions.push(c);for(const m of c.type)e.propertyTypes.add(m.code);return}for(const m of c.type){let g=m.code;aB(g)&&(g=c.type[0].code),OA(e,t,g,f)}}function iB(e,t){if(t.name==="as"){e.propertyTypes.add(t.args[0].toString());return}if(t.name==="ofType"){e.propertyTypes.add(t.args[0].toString());return}if(t.name==="resolve"){e.propertyTypes.add("string");return}if(t.name==="where"&&t.args[0]instanceof ib){e.propertyTypes.add(t.args[0].right.toString());return}throw new Error(`Unhandled FHIRPath function: ${t.name}`)}function aB(e){return e==="Element"||e==="BackboneElement"}function oB(e,t){switch(e.type){case"date":return t.size===1&&t.has(oe.date)?Jn.DATE:Jn.DATETIME;case"number":return Jn.NUMBER;case"quantity":return Jn.QUANTITY;case"reference":return t.has(oe.canonical)?Jn.CANONICAL:Jn.REFERENCE;case"token":return t.size===1&&t.has(oe.boolean)?Jn.BOOLEAN:Jn.TEXT;default:return Jn.TEXT}}function sB(e,t){const n=[],r=sb(t);return Uh(e,r.child,n),n}function lB(e,t){const n=[],r=sb(t);if(Uh(e,r.child,n),n.length===0)return r;let i=n[0];for(let s=1;s<n.length;s++)i=new rb(i,n[s]);return new NA("<original-not-available>",i)}function Uh(e,t,n){t instanceof rb?(Uh(e,t.left,n),Uh(e,t.right,n)):t.toString().includes(e+".")&&n.push(t)}function bh(e){if(e instanceof $h||e instanceof ob)return[bh(e.left),e].flat();if(e instanceof Nr)return[e];if(e instanceof nb)return[bh(e.left),bh(e.right)].flat();if(e instanceof ab){if(e.name==="where"&&!(e.args[0]instanceof ib))return[];if(e.name==="last")return[]}return[e]}const Yp=20,ue={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"},MA={contains:ue.CONTAINS,exact:ue.EXACT,above:ue.ABOVE,below:ue.BELOW,text:ue.TEXT,not:ue.NOT,in:ue.IN,"not-in":ue.NOT_IN,"of-type":ue.OF_TYPE,missing:ue.MISSING,identifier:ue.IDENTIFIER,iterate:ue.ITERATE},lb={eq:ue.EQUALS,ne:ue.NOT_EQUALS,lt:ue.LESS_THAN,le:ue.LESS_THAN_OR_EQUALS,gt:ue.GREATER_THAN,ge:ue.GREATER_THAN_OR_EQUALS,sa:ue.STARTS_AFTER,eb:ue.ENDS_BEFORE,ap:ue.APPROXIMATELY,sw:ue.STARTS_WITH};function IA(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()),cB(i,s)}function cB(e,t){const n={resourceType:e};for(const[r,i]of t)uB(n,r,i);return n}function uB(e,t,n){var c,u;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=Lu(e.filters,{code:t,operator:ue.EQUALS,value:n});return}switch(r){case"_sort":dB(e,n);break;case"_cursor":e.cursor=n;break;case"_count":e.count=parseInt(n,10);break;case"_offset":e.offset=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 f=pE(n);i==="iterate"&&(f.modifier=ue.ITERATE),e.include=Lu(e.include,f);break}case"_revinclude":{const f=pE(n);i==="iterate"&&(f.modifier=ue.ITERATE),e.revInclude=Lu(e.revInclude,f);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 f=(u=(c=la.types[e.resourceType])==null?void 0:c.searchParams)==null?void 0:u[r];f?e.filters=Lu(e.filters,hB(f,i,n)):e.filters=Lu(e.filters,pB(r,i,n))}}}}function dB(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 fB=[ue.MISSING,ue.PRESENT];function hB(e,t,n){if(fB.includes(t))return{code:e.code,operator:t,value:n};switch(e.type){case"number":case"date":case"quantity":{const{operator:r,value:i}=mB(n);if(!mE(e,i))throw new dt(ra(`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(!mE(e,n))throw new dt(ra(`Invalid format for ${e.type} search parameter: ${n}`));return{code:e.code,operator:gB(t),value:n};default:throw new Error("Unrecognized search parameter type: "+e.type)}}function pB(e,t,n){var i;let r=ue.EQUALS;if(t)r=t;else if(n.length>=2){const s=n.substring(0,2);s in lb&&(n.length===2||(i=n.at(2))!=null&&i.match(/\d/))&&(r=s,n=n.substring(s.length))}return{code:e,operator:r,value:n}}function mB(e){const t=e.substring(0,2),n=lb[t];return n?{operator:n,value:e.substring(2)}:{operator:ue.EQUALS,value:e}}function gB(e){return MA[e]??ue.EQUALS}function pE(e){const t=e.split(":");if(t.includes("*"))throw new dt(ra("'*' is not supported as a value for search inclusion parameters"));if(t.length===1)throw new dt(ra(`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 dt(ra(`Invalid include value '${e}'`))}function mE(e,t){switch(e.type){case"date":return Lh(t);default:return!0}}function Uo(e){const t=[];return e.fields&&t.push("_fields="+e.fields.join(",")),e.filters&&e.filters.forEach(n=>t.push(vB(n))),e.sortRules&&e.sortRules.length>0&&t.push(yB(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(",")),e.include&&e.include.forEach(n=>t.push(gE("_include",n))),e.revInclude&&e.revInclude.forEach(n=>t.push(gE("_revinclude",n))),t.length===0?"":(ad(t),"?"+t.join("&"))}function vB(e){const t=e.operator in MA?":"+e.operator:"",n=e.operator!==ue.EQUALS&&e.operator in lb?e.operator:"";return`${e.code}${t}=${n}${encodeURIComponent(e.value)}`}function yB(e){return"_sort="+e.map(t=>t.descending?"-"+t.code:t.code).join(",")}function gE(e,t){return e+(t.modifier?":"+t.modifier:"")+"="+t.resourceType+":"+t.searchParam+(t.targetType?":"+t.targetType:"")}function cb(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 xB(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters){for(const n of t.filters)if(!bB(e,t,n))return!1}return!0}function bB(e,t,n){var i,s;const r=(s=(i=la.types[t.resourceType])==null?void 0:i.searchParams)==null?void 0:s[n.code];if(!r)return!1;if(n.operator===ue.MISSING||n.operator===ue.PRESENT)return SB(e,n,r);switch(r.type){case"reference":return wB(e,n,r);case"string":case"uri":return LA(e,n,r);case"token":return jB(e,n,r);case"date":return RB(e,n,r);default:return!1}}function SB(e,t,n){const i=Oc(n.expression,e).length>0;return(t.operator===ue.MISSING&&t.value==="false"||t.operator===ue.PRESENT&&t.value==="true")===i}function wB(e,t,n){const r=Oc(n.expression,e),i=Kp(t.operator);if(t.value===""&&r.length===0)return t.operator===ue.EQUALS;const s=r.map(c=>typeof c=="string"?c:c.reference);for(const c of cb(t.value)){let u=s.includes(c);if(!u&&t.code==="_compartment"&&(u=s.some(f=>f==null?void 0:f.endsWith("/"+c))),u)return!i}return i}function jB(e,t,n){return Mc(e.resourceType,n).type===Jn.BOOLEAN?CB(e,t,n):LA(e,t,n,!0)}function CB(e,t,n){const r=Oc(n.expression,e),i=t.value==="true",s=r.includes(i);return Kp(t.operator)?!s:s}function LA(e,t,n,r){var p,m,g,y;const s=(y=(g=(m=(p=Mc(e.resourceType,n).elementDefinitions)==null?void 0:p[0])==null?void 0:m.type)==null?void 0:g[0])==null?void 0:y.code,c=Oc(n.expression,e),u=cb(t.value),f=Kp(t.operator);for(const b of c)for(const S of u){let j;if(s===oe.Identifier?j=EB(b,t.operator,S):s===oe.CodeableConcept?j=TB(b,t.operator,S):j=Iy(b,S,r),j)return!f}return f}function Iy(e,t,n){if(t==="")return!1;if(n&&typeof e=="string"&&e.includes("|")){const[i,s]=e.split("|"),c=Iy(i,t,!1),u=s?Iy(s,t,!1):!1;return c||u}let r="";return e&&(typeof e=="string"?r=e:typeof e=="object"&&(r=JSON.stringify(e))),r.toLowerCase().includes(t.toLowerCase())}function EB(e,t,n){var r,i,s,c;if(n.includes("|")){const[u,f]=n.split("|").map(p=>p.toLowerCase());return!u&&!f?!1:u?((i=e.system)==null?void 0:i.toLowerCase())===u&&(!f||((s=e.value)==null?void 0:s.toLowerCase())===f):!e.system&&((r=e.value)==null?void 0:r.toLowerCase())===f}return((c=e.value)==null?void 0:c.toLowerCase())===n.toLowerCase()}function TB(e,t,n){var r,i,s,c;if(n.includes("|")){const[u,f]=n.split("|").map(p=>p.toLowerCase());return!u&&!f?!1:u?((i=e.coding)==null?void 0:i.some(p=>{var m,g;return((m=p.system)==null?void 0:m.toLowerCase())===u&&(!f||((g=p.code)==null?void 0:g.toLowerCase())===f)}))??!1:((r=e.coding)==null?void 0:r.some(p=>{var m;return!p.system&&((m=p.code)==null?void 0:m.toLowerCase())===f}))??!1}return((s=e.text)==null?void 0:s.toLowerCase())===n.toLowerCase()||(((c=e.coding)==null?void 0:c.some(u=>{var f;return((f=u.code)==null?void 0:f.toLowerCase())===n.toLowerCase()}))??!1)}function RB(e,t,n){const r=Oc(n.expression,e),i=cb(t.value),s=Kp(t.operator);for(const c of r)for(const u of i)if(DB(Bh(c),t.operator,Bh(u)))return!s;return s}function DB(e,t,n){if(!e)return!1;switch(t){case ue.STARTS_AFTER:case ue.GREATER_THAN:return e>n;case ue.GREATER_THAN_OR_EQUALS:return e>=n;case ue.ENDS_BEFORE:case ue.LESS_THAN:return e<n;case ue.LESS_THAN_OR_EQUALS:return e<=n;case ue.EQUALS:case ue.NOT_EQUALS:return e===n;default:return!1}}function Bh(e){if(aU(e))try{return new Date(e).toISOString()}catch(t){console.debug("Failed to parse date",e,t)}else if(xA(e)){if("start"in e)return Bh(e.start);if("end"in e)return Bh(e.end)}}function Kp(e){return e===ue.NOT_EQUALS||e===ue.NOT}const AB={resourceType:"*"},_B=["DomainConfiguration","JsonWebKey","Login"],kB=["PasswordChangeRequest","UserSecurityRequest","Project","ProjectMembership","User"],Ns={READ:"read",VREAD:"vread",UPDATE:"update",HISTORY:"history",SEARCH:"search"},PB=[Ns.READ,Ns.VREAD,Ns.HISTORY,Ns.SEARCH];function NB(e,t){return _B.includes(t)?!1:OB(e,Ns.UPDATE,t)}function OB(e,t,n){var r;return!!((r=e.resource)!=null&&r.some(i=>$A(i,n,t)))}function zA(e,t,n){var r;return n?(r=n.resource)==null?void 0:r.find(i=>MB(e,t,i)):AB}function MB(e,t,n){var i,s;const r=e.resourceType;return $A(n,r,t)?r==="Binary"?!0:!(n.compartment&&!((s=(i=e.meta)==null?void 0:i.compartment)!=null&&s.some(c=>{var u;return c.reference===((u=n.compartment)==null?void 0:u.reference)}))||n.criteria&&!xB(e,IA(n.criteria))):!1}function $A(e,t,n){return e.resourceType!==t&&(e.resourceType!=="*"||kB.includes(t))?!1:e.interaction?e.interaction.includes(n):!e.readonly||PB.includes(n)}function IB(e){if(typeof window<"u"){const t=window.atob(e),n=Uint8Array.from(t,r=>r.charCodeAt(0));return new window.TextDecoder().decode(n)}if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf-8");throw new Error("Unable to decode base64")}function vE(e){if(typeof window<"u"){const t=new window.TextEncoder().encode(e),n=String.fromCharCode.apply(null,t);return window.btoa(n)}if(typeof Buffer<"u")return Buffer.from(e,"utf8").toString("base64");throw new Error("Unable to encode base64")}function LB(e){e=e.padEnd(e.length+(4-e.length%4)%4,"=");const t=e.replace(/-/g,"+").replace(/_/g,"/");return IB(t)}function yE(){const e=new Uint32Array(28);return crypto.getRandomValues(e),sU(e.buffer)}async function zB(e){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))}function UA(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function BA(e){var i;const t={};e=Qr(e);for(const s of e.entry||[]){const c=s.resource;if(!c)continue;c.meta!==void 0&&(delete c.meta.author,delete c.meta.compartment,delete c.meta.lastUpdated,delete c.meta.project,delete c.meta.versionId,Object.keys(c.meta).length===0&&delete c.meta);const u=c==null?void 0:c.id;u&&(t[u]=UA(),s.fullUrl="urn:uuid:"+t[u],(i=s.resource)==null||delete i.id)}const n=e.entry,r=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:n==null?void 0:n.map(s=>{var c;return{fullUrl:s.fullUrl,request:{method:"POST",url:(c=s.resource)==null?void 0:c.resourceType},resource:s.resource}})},(s,c)=>$B(s,c,t),2);return UB(JSON.parse(r))}function $B(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 UB(e){const t=VB(e),{sorted:n,cycles:r}=BB(t),i={};for(const c of e.entry??[])c.fullUrl&&(i[c.fullUrl]=c);const s=n.map(c=>i[c]);for(const c of r)for(const u of c){const f=i[u],p={...f,request:{...f.request,method:"PUT"}};s.push(p)}return{...e,entry:s}}const Kl={NotVisited:"NotVisited",Visiting:"Visiting",Visited:"Visited"};function BB(e){const t=[],n={},r=[];for(const s of Object.keys(e))n[s]=Kl.NotVisited;function i(s,c){if(n[s]===Kl.Visited)return!0;if(n[s]===Kl.Visiting){const f=c.lastIndexOf(s);return f!==-1&&r.push(c.slice(f)),!0}n[s]=Kl.Visiting,c.push(s);let u=!1;for(const f of e[s])i(f,c)||(u=!0);return n[s]=Kl.Visited,c.pop(),t.unshift(s),!u}for(const s in e)n[s]===Kl.NotVisited&&i(s,[]);return{sorted:t,cycles:r}}function VA(e,t){for(const n in e)if(e[n]&&typeof e[n]=="object"){const r=e[n];if(Ko(r)){const i=r.reference;i.startsWith("urn:uuid:")&&t(i)}else VA(r,t)}}function VB(e){const t={};for(const n of e.entry||[])n.fullUrl&&(t[n.fullUrl]=[]);for(const n of e.entry||[]){const r=n.fullUrl;n.resource&&VA(n.resource,i=>{t[i]&&t[i].push(r)})}return t}const hn={FHIR_JSON:"application/fhir+json",FORM_URL_ENCODED:"application/x-www-form-urlencoded",HL7_V2:"x-application/hl7-v2+er7",JSON:"application/json",JSON_PATCH:"application/json-patch+json",TEXT:"text/plain",PING:"x-application/ping",XML:"text/xml",CDA_XML:"application/cda+xml"};class FB{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];if(n)for(const r of n)r.call(this,t);return!t.defaultPrevented}removeAllListeners(){this.listeners={}}}class Xp{constructor(){this.emitter=new FB}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()}}const Ly={"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"},HB=["Patient","Encounter","ImagingStudy","DiagnosticReport","OperationOutcome","Bundle"],ub=["DiagnosticReport-update"];function qB(e){return ub.includes(e)}function GB(e){if(ub.includes(e))throw new dt(yn(`'context.version' is required for '${e}'.`))}const QB={"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 WB(e){return HB.includes(e)}function FA(e){return!!e.endpoint}function xE(e){if(!db(e))throw new dt(yn("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 FA(e)&&(s.endpoint=e.endpoint),new URLSearchParams(s).toString()}function db(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(!Ly[s])return!1;return!(FA(e)&&!(typeof e.endpoint=="string"&&e.endpoint.startsWith("ws")))}function YB(e,t,n,r){if(typeof t!="object")throw new dt(yn(`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 dt(yn(`context[${n}] is invalid. Resource must contain a valid string ID.`));if(!t.resourceType)throw new dt(yn(`context[${n}] is invalid. Resource must contain a resource type. No resource type found.`));const i=r.resourceType;if(i!=="*"){if(!WB(t.resourceType))throw new dt(yn(`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 dt(yn(`context[${n}] is invalid. context[${n}] for the '${e}' event should contain resource of type ${i}.`))}}function KB(e,t,n,r,i){if(i.set(t.key,(i.get(t.key)??0)+1),r.reference){if(!Ko(t.reference))throw new dt(yn(`context[${n}] is invalid. Expected key '${t.key}' to be a reference.`))}else YB(e,t.resource,n,r)}function XB(e,t){const n=new Map,r=QB[e];for(let i=0;i<t.length;i++){const s=t[i].key;if(!r[s])throw new dt(yn(`Key '${s}' not found for event '${e}'. Make sure to add only valid keys.`));KB(e,t[i],i,r[s],n)}for(const[i,s]of Object.entries(r)){if(!(s.optional||n.has(i)))throw new dt(yn(`Missing required key '${i}' on context for '${e}' event.`));if(!s.manyAllowed&&(n.get(i)??0)>1)throw new dt(yn(`${n.get(i)} context entries with key '${i}' found for the '${e}' event when schema only allows for 1.`))}}function bE(e,t,n,r){if(!(e&&typeof e=="string"))throw new dt(yn("Must provide a topic."));if(!Ly[t])throw new dt(yn(`Must provide a valid FHIRcast event name. Supported events: ${Object.keys(Ly).join(", ")}`));if(typeof n!="object")throw new dt(yn("context must be a context object or array of context objects."));if(ub.includes(t)&&!r)throw new dt(yn(`The '${t}' event must contain a 'context.versionId'.`));const i=Array.isArray(n)?n:[n];return XB(t,i),{timestamp:new Date().toISOString(),id:UA(),event:{"hub.topic":e,"hub.event":t,context:i,...r?{"context.versionId":r}:{}}}}class ZB extends Xp{constructor(t){if(super(),this.subRequest=t,!t.endpoint)throw new dt(yn("Subscription request should contain an endpoint."));if(!db(t))throw new dt(yn("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==null?void 0:i.id,timestamp:new Date().toISOString()})))}),n.addEventListener("close",()=>{this.dispatchEvent({type:"disconnect"})})}),this.websocket=n}disconnect(){this.websocket.close()}}function JB(e){return JSON.parse(LB(e))}function eV(e){return e.split(".").length===3}function fb(e){const[t,n,r]=e.split(".");return JB(n)}function tV(e){try{return typeof fb(e).login_id=="string"}catch{return!1}}function nV(e){try{const n=fb(e).exp;return typeof n=="number"?n*1e3:void 0}catch{return}}class rV{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,hn.TEXT)}async delete(t){await this.medplum.delete(`keyvalue/v1/${t}`)}}var HA;HA=Symbol.toStringTag;class Ai{constructor(t){this[HA]="ReadablePromise",this.status="pending",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 iV{constructor(t){this.storage=t??(typeof localStorage<"u"?localStorage:new aV)}clear(){this.storage.clear()}getString(t){return this.storage.getItem(t)??void 0}setString(t,n){n?this.storage.setItem(t,n):this.storage.removeItem(t)}getObject(t){const n=this.getString(t);return n?JSON.parse(n):void 0}setObject(t,n){this.setString(t,n?Ii(n):void 0)}}class aV{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]}}/*!
79
79
  * Reconnecting WebSocket
80
80
  * by Pedro Ladaria <pedro.ladaria@gmail.com>
81
81
  * https://github.com/pladaria/reconnecting-websocket
@@ -83,7 +83,7 @@ function p3(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
83
83
  *
84
84
  * Copy of "partysocket" from Partykit team, a fork of the original "Reconnecting WebSocket"
85
85
  * https://github.com/partykit/partykit/blob/main/packages/partysocket
86
- */const ac={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let SE=!1;function oV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");ac.Event=globalThis.Event,ac.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},ac.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function sV(e,t){if(!e)throw new Error(t)}function ah(e){return new e.constructor(e.type,e)}const bs={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let wE=!1;class Mo extends Xp{constructor(t,n,r={}){SE||(oV(),SE=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._closeCalled=!1,this._messageQueue=[],this._debugLogger=console.log.bind(console),this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=i=>{this._debug("open event");const{minUptime:s=bs.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),sV(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(c=>{var u;return(u=this._ws)==null?void 0:u.send(c)}),this._messageQueue=[],this.onopen&&this.onopen(i),this.dispatchEvent(ah(i))},this._handleMessage=i=>{this._debug("message event"),this.onmessage&&this.onmessage(i),this.dispatchEvent(ah(i))},this._handleError=i=>{this._debug("error event",i.message),this._disconnect(void 0,i.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(i),this._debug("exec error listeners"),this.dispatchEvent(ah(i)),this._connect()},this._handleClose=i=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(i),this.dispatchEvent(ah(i))},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 Mo.CONNECTING}get OPEN(){return Mo.OPEN}get CLOSING(){return Mo.CLOSING}get CLOSED(){return Mo.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(){var n;return this._messageQueue.reduce((r,i)=>(typeof i=="string"?r+=i.length:i instanceof Blob?r+=i.size:r+=i.byteLength,r),0)+(((n=this._ws)==null?void 0:n.bufferedAmount)??0)}get extensions(){var t;return((t=this._ws)==null?void 0:t.extensions)??""}get protocol(){var t;return((t=this._ws)==null?void 0:t.protocol)??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?Mo.CLOSED:Mo.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}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&&this._ws.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{const{maxEnqueuedMessages:n=bs.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=bs.reconnectionDelayGrowFactor,minReconnectionDelay:n=bs.minReconnectionDelay,maxReconnectionDelay:r=bs.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=bs.maxRetries,connectionTimeout:n=bs.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"&&!wE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),wE=!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 ac.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new ac.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new ac.CloseEvent(t,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_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 lV=5e3;class zy extends Xp{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 cV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new zy(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class uV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof GA))throw new dt(yn("First arg of constructor should be a `MedplumClient`"));let i;try{i=new URL(n).toString()}catch{throw new dt(yn("Not a valid URL"))}const s=r!=null&&r.ReconnectingWebSocket?new r.ReconnectingWebSocket(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger}):new Mo(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new zy,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??lV,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,i,s,c,u,f;try{const p=JSON.parse(n.data);if(p.type==="pong"){this.waitingForPong=!1;return}const m=p,g=(i=(r=m==null?void 0:m.entry)==null?void 0:r[0])==null?void 0:i.resource;if(g.type==="heartbeat"){(s=this.masterSubEmitter)==null||s.dispatchEvent({type:"heartbeat",payload:m});return}if(g.type==="handshake"){const b=Bs(g.subscription),S={type:"connect",payload:{subscriptionId:b}};(c=this.masterSubEmitter)==null||c.dispatchEvent(S);const j=this.criteriaEntriesBySubscriptionId.get(b);if(!j){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}j.connecting=!1,j.emitter.dispatchEvent({...S});return}(u=this.masterSubEmitter)==null||u.dispatchEvent({type:"message",payload:m});const y=this.criteriaEntriesBySubscriptionId.get(Bs(g.subscription));if(!y){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}y.emitter.dispatchEvent({type:"message",payload:m})}catch(p){console.error(p);const m={type:"error",payload:p};(f=this.masterSubEmitter)==null||f.dispatchEvent(m);for(const g of this.getAllCriteriaEmitters())g.dispatchEvent({...m})}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new dt(S8(new Error("WebSocket error")))};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.dispatchEvent({...n})}),t.addEventListener("close",()=>{var r,i;const n={type:"close"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const s of this.getAllCriteriaEmitters())s.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),(i=this.masterSubEmitter)==null||i.removeAllListeners())}),t.addEventListener("open",()=>{var r;const n={type:"open"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.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.medplum.addEventListener("change",()=>{var r;const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&((r=this.currentProfile)==null?void 0:r.id)!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){var i;const r={type:"error",payload:n};(i=this.masterSubEmitter)==null||i.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){var r;const{subscriptionId:n}=t;if(n){const i={type:"disconnect",payload:{subscriptionId:n}};(r=this.masterSubEmitter)==null||r.dispatchEvent(i),t.emitter.dispatchEvent({...i})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){var c,u;let n=t==null?void 0:t.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${zt(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=(c=r==null?void 0:r.find(f=>f.name==="token"))==null?void 0:c.valueString,s=(u=r==null?void 0:r.find(f=>f.name==="websocket-url"))==null?void 0:u.valueUrl;if(!i)throw new dt(yn("Failed to get token"));if(!s)throw new dt(yn("Failed to get URL from $get-ws-binding-token"));return[n,i]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const i of r.criteriaWithProps)if(sa(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){var u;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(f=>{const p=f.subscriptionProps;return!sa(r,p)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),(u=this.masterSubEmitter)==null||u._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){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(Ye(n)),this.emitError(t,n),this.removeCriteriaEntry(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)}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 cV(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 zy(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const qA="4.3.0-2385e056c",dV=hn.FHIR_JSON+", */*; q=0.1",fV="https://api.medplum.com/",hV=1e3,pV=6e4,mV=0,gV=3e5,vV="Binary/",jE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Xl={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"},yV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},xV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class GA extends Xp{constructor(t){if(super(),this.initComplete=!0,t!=null&&t.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=(t==null?void 0:t.fetch)??bV(),this.storage=(t==null?void 0:t.storage)??new iV,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=eb((t==null?void 0:t.baseUrl)??fV),this.fhirBaseUrl=Xi(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Xi(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Xi(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Xi(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=Xi(this.baseUrl,(t==null?void 0:t.fhircastHubUrl)??"fhircast/STU3"),this.clientId=(t==null?void 0:t.clientId)??"",this.clientSecret=(t==null?void 0:t.clientSecret)??"",this.credentialsInHeader=(t==null?void 0:t.authCredentialsMethod)==="header",this.defaultHeaders=(t==null?void 0:t.defaultHeaders)??{},this.onUnauthenticated=t==null?void 0:t.onUnauthenticated,this.refreshGracePeriod=(t==null?void 0:t.refreshGracePeriod)??gV,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?mV:pV),this.cacheTime>0?this.requestCache=new aA((t==null?void 0:t.resourceCacheSize)??hV):this.requestCache=void 0,t!=null&&t.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t!=null&&t.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t!=null&&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!=null&&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}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}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),typeof window<"u"&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){var t;this.storage.setString("activeLogin",void 0),(t=this.requestCache)==null||t.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){var n;t=t.toString(),(n=this.requestCache)==null||n.delete(t)}invalidateAll(){var t;(t=this.requestCache)==null||t.clear()}invalidateSearches(t){const n=Xi(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(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 Ai(i);return this.setCacheEntry(t,s),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,hn.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(window.location.search).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,i,s=!0){let c=i;s&&(c=await this.ensureCodeChallenge(i)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,c,s))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:Xl.TokenExchange,subject_token_type:yV.AccessToken,client_id:n,subject_token:t})}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(Xi(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=pU(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),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 Ai(this.search(t,i.searchParams,r).then(f=>{var p,m;return(m=(p=f.entry)==null?void 0:p[0])==null?void 0:m.resource}));return this.setCacheEntry(s,u),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 Ai(this.search(t,n,r).then(TE));return this.setCacheEntry(s,u),u}async*searchResourcePages(t,n,r){var s,c;let i=this.fhirSearchUrl(t,n);for(;i;){const u=new URL(i).searchParams;u.has("_count")||u.set("_count","1000");const f=await this.search(t,u,r),p=(s=f.link)==null?void 0:s.find(m=>m.relation==="next");if(!((c=f.entry)!=null&&c.length)&&!p)break;yield TE(f),i=p!=null&&p.url?new URL(p.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){var i,s;const r=(s=(i=this.requestCache)==null?void 0:i.get(this.fhirUrl(t,n).toString()))==null?void 0:s.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return jE;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 Ai(Promise.reject(new Error("Missing reference")));if(r==="system")return new Ai(Promise.resolve(jE));const[i,s]=r.split("/");return!i||!s?new Ai(Promise.reject(new Error("Invalid reference"))):this.readResource(i,s,n)}requestSchema(t){if(fA(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const i=new Ai((async()=>{const s=`{
86
+ */const ac={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let SE=!1;function oV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");ac.Event=globalThis.Event,ac.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},ac.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function sV(e,t){if(!e)throw new Error(t)}function ah(e){return new e.constructor(e.type,e)}const bs={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let wE=!1;class Mo extends Xp{constructor(t,n,r={}){SE||(oV(),SE=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._closeCalled=!1,this._messageQueue=[],this._debugLogger=console.log.bind(console),this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=i=>{this._debug("open event");const{minUptime:s=bs.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),sV(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(c=>{var u;return(u=this._ws)==null?void 0:u.send(c)}),this._messageQueue=[],this.onopen&&this.onopen(i),this.dispatchEvent(ah(i))},this._handleMessage=i=>{this._debug("message event"),this.onmessage&&this.onmessage(i),this.dispatchEvent(ah(i))},this._handleError=i=>{this._debug("error event",i.message),this._disconnect(void 0,i.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(i),this._debug("exec error listeners"),this.dispatchEvent(ah(i)),this._connect()},this._handleClose=i=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(i),this.dispatchEvent(ah(i))},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 Mo.CONNECTING}get OPEN(){return Mo.OPEN}get CLOSING(){return Mo.CLOSING}get CLOSED(){return Mo.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(){var n;return this._messageQueue.reduce((r,i)=>(typeof i=="string"?r+=i.length:i instanceof Blob?r+=i.size:r+=i.byteLength,r),0)+(((n=this._ws)==null?void 0:n.bufferedAmount)??0)}get extensions(){var t;return((t=this._ws)==null?void 0:t.extensions)??""}get protocol(){var t;return((t=this._ws)==null?void 0:t.protocol)??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?Mo.CLOSED:Mo.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}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&&this._ws.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{const{maxEnqueuedMessages:n=bs.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=bs.reconnectionDelayGrowFactor,minReconnectionDelay:n=bs.minReconnectionDelay,maxReconnectionDelay:r=bs.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=bs.maxRetries,connectionTimeout:n=bs.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"&&!wE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),wE=!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 ac.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new ac.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new ac.CloseEvent(t,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_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 lV=5e3;class zy extends Xp{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 cV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new zy(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class uV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof GA))throw new dt(yn("First arg of constructor should be a `MedplumClient`"));let i;try{i=new URL(n).toString()}catch{throw new dt(yn("Not a valid URL"))}const s=r!=null&&r.ReconnectingWebSocket?new r.ReconnectingWebSocket(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger}):new Mo(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new zy,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??lV,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,i,s,c,u,f;try{const p=JSON.parse(n.data);if(p.type==="pong"){this.waitingForPong=!1;return}const m=p,g=(i=(r=m==null?void 0:m.entry)==null?void 0:r[0])==null?void 0:i.resource;if(g.type==="heartbeat"){(s=this.masterSubEmitter)==null||s.dispatchEvent({type:"heartbeat",payload:m});return}if(g.type==="handshake"){const b=Bs(g.subscription),S={type:"connect",payload:{subscriptionId:b}};(c=this.masterSubEmitter)==null||c.dispatchEvent(S);const j=this.criteriaEntriesBySubscriptionId.get(b);if(!j){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}j.connecting=!1,j.emitter.dispatchEvent({...S});return}(u=this.masterSubEmitter)==null||u.dispatchEvent({type:"message",payload:m});const y=this.criteriaEntriesBySubscriptionId.get(Bs(g.subscription));if(!y){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}y.emitter.dispatchEvent({type:"message",payload:m})}catch(p){console.error(p);const m={type:"error",payload:p};(f=this.masterSubEmitter)==null||f.dispatchEvent(m);for(const g of this.getAllCriteriaEmitters())g.dispatchEvent({...m})}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new dt(S8(new Error("WebSocket error")))};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.dispatchEvent({...n})}),t.addEventListener("close",()=>{var r,i;const n={type:"close"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const s of this.getAllCriteriaEmitters())s.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),(i=this.masterSubEmitter)==null||i.removeAllListeners())}),t.addEventListener("open",()=>{var r;const n={type:"open"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.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.medplum.addEventListener("change",()=>{var r;const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&((r=this.currentProfile)==null?void 0:r.id)!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){var i;const r={type:"error",payload:n};(i=this.masterSubEmitter)==null||i.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){var r;const{subscriptionId:n}=t;if(n){const i={type:"disconnect",payload:{subscriptionId:n}};(r=this.masterSubEmitter)==null||r.dispatchEvent(i),t.emitter.dispatchEvent({...i})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){var c,u;let n=t==null?void 0:t.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${zt(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=(c=r==null?void 0:r.find(f=>f.name==="token"))==null?void 0:c.valueString,s=(u=r==null?void 0:r.find(f=>f.name==="websocket-url"))==null?void 0:u.valueUrl;if(!i)throw new dt(yn("Failed to get token"));if(!s)throw new dt(yn("Failed to get URL from $get-ws-binding-token"));return[n,i]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const i of r.criteriaWithProps)if(sa(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){var u;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(f=>{const p=f.subscriptionProps;return!sa(r,p)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),(u=this.masterSubEmitter)==null||u._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){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(Ye(n)),this.emitError(t,n),this.removeCriteriaEntry(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)}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 cV(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 zy(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const qA="4.3.2-31f7dcd0a",dV=hn.FHIR_JSON+", */*; q=0.1",fV="https://api.medplum.com/",hV=1e3,pV=6e4,mV=0,gV=3e5,vV="Binary/",jE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Xl={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"},yV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},xV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class GA extends Xp{constructor(t){if(super(),this.initComplete=!0,t!=null&&t.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=(t==null?void 0:t.fetch)??bV(),this.storage=(t==null?void 0:t.storage)??new iV,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=eb((t==null?void 0:t.baseUrl)??fV),this.fhirBaseUrl=Xi(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Xi(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Xi(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Xi(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=Xi(this.baseUrl,(t==null?void 0:t.fhircastHubUrl)??"fhircast/STU3"),this.clientId=(t==null?void 0:t.clientId)??"",this.clientSecret=(t==null?void 0:t.clientSecret)??"",this.credentialsInHeader=(t==null?void 0:t.authCredentialsMethod)==="header",this.defaultHeaders=(t==null?void 0:t.defaultHeaders)??{},this.onUnauthenticated=t==null?void 0:t.onUnauthenticated,this.refreshGracePeriod=(t==null?void 0:t.refreshGracePeriod)??gV,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?mV:pV),this.cacheTime>0?this.requestCache=new aA((t==null?void 0:t.resourceCacheSize)??hV):this.requestCache=void 0,t!=null&&t.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t!=null&&t.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t!=null&&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!=null&&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}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}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),typeof window<"u"&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){var t;this.storage.setString("activeLogin",void 0),(t=this.requestCache)==null||t.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){var n;t=t.toString(),(n=this.requestCache)==null||n.delete(t)}invalidateAll(){var t;(t=this.requestCache)==null||t.clear()}invalidateSearches(t){const n=Xi(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(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 Ai(i);return this.setCacheEntry(t,s),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,hn.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(window.location.search).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,i,s=!0){let c=i;s&&(c=await this.ensureCodeChallenge(i)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,c,s))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:Xl.TokenExchange,subject_token_type:yV.AccessToken,client_id:n,subject_token:t})}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(Xi(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=pU(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),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 Ai(this.search(t,i.searchParams,r).then(f=>{var p,m;return(m=(p=f.entry)==null?void 0:p[0])==null?void 0:m.resource}));return this.setCacheEntry(s,u),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 Ai(this.search(t,n,r).then(TE));return this.setCacheEntry(s,u),u}async*searchResourcePages(t,n,r){var s,c;let i=this.fhirSearchUrl(t,n);for(;i;){const u=new URL(i).searchParams;u.has("_count")||u.set("_count","1000");const f=await this.search(t,u,r),p=(s=f.link)==null?void 0:s.find(m=>m.relation==="next");if(!((c=f.entry)!=null&&c.length)&&!p)break;yield TE(f),i=p!=null&&p.url?new URL(p.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){var i,s;const r=(s=(i=this.requestCache)==null?void 0:i.get(this.fhirUrl(t,n).toString()))==null?void 0:s.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return jE;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 Ai(Promise.reject(new Error("Missing reference")));if(r==="system")return new Ai(Promise.resolve(jE));const[i,s]=r.split("/");return!i||!s?new Ai(Promise.reject(new Error("Invalid reference"))):this.readResource(i,s,n)}requestSchema(t){if(fA(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const i=new Ai((async()=>{const s=`{
87
87
  StructureDefinitionList(_filter: "name eq ${t}") {
88
88
  resourceType,
89
89
  name,
@@ -583,4 +583,4 @@ Please change the parent <Route path="${D}"> to <Route path="${D==="/"?"*":`${D}
583
583
  }
584
584
  ]
585
585
  }`,see="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 lee(){const e=_e(),{id:t}=qt(),[n,r]=v.useState(),[i,s]=v.useState(),[c,u]=v.useState(oee),[f,p]=v.useState(see),[m,g]=v.useState(hn.FHIR_JSON),y=v.useRef(null),b=v.useRef(null),[S,j]=v.useState(!1);v.useEffect(()=>{e.readResource("Bot",t).then(async k=>{r(k),s(await cee(e,k))}).catch(k=>Oe({color:"red",message:Ye(k),autoClose:!1}))},[e,t]);const C=v.useCallback(async()=>Yu(y.current,{command:"getValue"}),[]),T=v.useCallback(async()=>Yu(y.current,{command:"getOutput"}),[]),D=v.useCallback(async()=>m===hn.FHIR_JSON?JSON.parse(c):f,[m,c,f]),E=v.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),j(!0);try{const M=await C(),I=await T(),$=await e.createAttachment({data:M,filename:"index.ts",contentType:"text/typescript"}),V=await e.createAttachment({data:I,filename:"index.js",contentType:"text/typescript"}),Y=[{op:"add",path:"/sourceCode",value:$},{op:"add",path:"/executableCode",value:V}];await e.patchResource("Bot",t,Y),Oe({color:"green",message:"Saved"})}catch(M){Oe({color:"red",message:Ye(M),autoClose:!1})}finally{j(!1)}},[e,t,C,T]),R=v.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),j(!0);try{await e.post(e.fhirUrl("Bot",t,"$deploy")),Oe({color:"green",message:"Deployed"})}catch(M){Oe({color:"red",message:Ye(M),autoClose:!1})}finally{j(!1)}},[e,t]),A=v.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),j(!0);try{const M=await D(),I=await e.post(e.fhirUrl("Bot",t,"$execute"),M,m);await Yu(b.current,{command:"setValue",value:I}),Oe({color:"green",message:"Success"})}catch(M){Oe({color:"red",message:Ye(M),autoClose:!1})}finally{j(!1)}},[e,t,D,m]);return!n||i===void 0?null:o.jsxs(or,{m:0,gutter:0,style:{overflow:"hidden"},children:[o.jsx(or.Col,{span:8,children:o.jsxs(mr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[o.jsx(aee,{iframeRef:y,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:i,minHeight:"528px"}),o.jsxs(je,{justify:"flex-end",gap:"xs",children:[o.jsx(Ne,{type:"button",onClick:E,loading:S,leftSection:o.jsx(dF,{size:"1rem"}),children:"Save"}),o.jsx(Ne,{type:"button",onClick:R,loading:S,leftSection:o.jsx(mb,{size:"1rem"}),children:"Deploy"}),o.jsx(Ne,{type:"button",onClick:A,loading:S,leftSection:o.jsx(TF,{size:"1rem"}),children:"Execute"})]})]})}),o.jsxs(or.Col,{span:4,children:[o.jsxs(mr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[o.jsx(ln,{data:[{label:"FHIR",value:hn.FHIR_JSON},{label:"HL7",value:hn.HL7_V2}],onChange:k=>g(k.currentTarget.value)}),m===hn.FHIR_JSON?o.jsx(Dc,{value:c,onChange:k=>u(k),autosize:!0,minRows:15}):o.jsx("textarea",{className:ree.hl7Input,value:f,onChange:k=>p(k.currentTarget.value),rows:15})]}),o.jsx(mr,{m:2,p:"xs",shadow:"md",children:o.jsx(iee,{iframeRef:b,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function cee(e,t){var n,r,i;if((n=t.sourceCode)!=null&&n.url){const s=(i=(r=t.sourceCode.url)==null?void 0:r.split("/"))==null?void 0:i.find(wA);return(await e.download(e.fhirUrl("Binary",s))).text()}return t.code??""}function sl(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function uee(){const e=_e(),{resourceType:t,id:n}=qt(),r={reference:t+"/"+n},i=v.useCallback(s=>{e.updateResource(sl(s)).then(()=>{Oe({color:"green",message:"Success"})}).catch(c=>{Oe({color:"red",message:Ye(c),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return o.jsx(ot,{children:o.jsx(oW,{value:r,onSubmit:i})});case"Questionnaire":return o.jsx(ot,{children:o.jsx(QW,{questionnaire:r,onSubmit:i})});default:return null}}function dee(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t}),r=wn();return n?o.jsx(ot,{children:o.jsx(yY,{value:n,onStart:(i,s)=>{var c;return(c=r(`/forms/${Bs(s)}`))==null?void 0:c.catch(console.error)},onEdit:(i,s,c)=>{var u;return(u=r(`/${c.reference}}`))==null?void 0:u.catch(console.error)}})}):null}function fee(){const e=_e(),{resourceType:t,id:n}=qt(),r=wn();return o.jsxs(ot,{children:[o.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),o.jsx(Ne,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>{var i;return(i=r(`/${t}`))==null?void 0:i.catch(console.error)}).catch(i=>Oe({color:"red",message:Ye(i),autoClose:!1}))},children:"Delete"})]})}const hee="_selectProfileBtn_tbaz6_1",pee="_chevron_tbaz6_13",JT={selectProfileBtn:hee,chevron:pee};function mee(){var f,p;const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t}),[r,i]=v.useState(),s=yd({onDropdownClose:()=>s.resetSelectedOption()}),c=v.useMemo(()=>{var m;if(Tn((m=n==null?void 0:n.meta)==null?void 0:m.profile))return[o.jsx(ct.Option,{value:"",children:"None"},""),...n.meta.profile.map(g=>o.jsx(ct.Option,{value:g,children:g},g))]},[(f=n==null?void 0:n.meta)==null?void 0:f.profile]);if(v.useEffect(()=>{var m,g;((g=(m=n==null?void 0:n.meta)==null?void 0:m.profile)==null?void 0:g.length)===1&&i(n.meta.profile[0])},[(p=n==null?void 0:n.meta)==null?void 0:p.profile]),!n)return null;let u;return Tn(c)&&(u=o.jsx(je,{justify:"flex-end",children:o.jsxs(Ge,{align:"flex-end",gap:"xs",children:[o.jsxs(ct,{store:s,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:m=>{i(m),s.closeDropdown()},children:[o.jsx(ct.Target,{children:o.jsx(tr,{onClick:()=>s.toggleDropdown(),children:o.jsxs(d0,{fw:"bold",fs:"sm",className:JT.selectProfileBtn,children:[o.jsx("span",{children:"Pick profile"}),o.jsx(pb,{stroke:1.5,className:JT.chevron})]})})}),o.jsx(ct.Dropdown,{w:"max-content",children:o.jsx(ct.Options,{children:c})})]}),o.jsx(ce,{children:r?o.jsxs(o.Fragment,{children:[o.jsx(Ae,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),o.jsx(Ae,{span:!0,size:"sm",children:r||"Nothing selected"})]}):o.jsx(Ae,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),o.jsx(ot,{children:o.jsxs(Ge,{gap:"xl",children:[u,o.jsx(Pb,{value:n,profileUrl:r})]})})}function gee(){const e=_e(),{resourceType:t,id:n}=qt(),[r,i]=v.useState(),[s,c]=v.useState(),u=wn(),[f,p]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(b=>{i(Qr(b)),c(Qr(b))}).catch(b=>{p(Zt(b)),Oe({color:"red",message:Ye(b),autoClose:!1})})},[e,t,n]);const m=v.useCallback(b=>{p(void 0),e.updateResource(sl(b)).then(()=>{var S;(S=u(`/${t}/${n}/details`))==null||S.catch(console.error),Oe({id:"succes",color:"green",message:"Success"})}).catch(S=>{p(Zt(S)),Oe({color:"red",message:Ye(S),autoClose:!1})})},[e,t,n,u]),g=v.useCallback(b=>{p(void 0);const S=$_.createPatch(r,b);e.patchResource(t,n,S).then(()=>{var j;(j=u(`/${t}/${n}/details`))==null||j.catch(console.error),Oe({id:"succes",color:"green",message:"Success"})}).catch(j=>{p(Zt(j)),Oe({color:"red",message:Ye(j),autoClose:!1})})},[e,t,n,r,u]),y=v.useCallback(()=>{var b;return(b=u(`/${t}/${n}/delete`))==null?void 0:b.catch(console.error)},[u,t,n]);return s?o.jsx(ot,{children:o.jsx(Yh,{defaultValue:s,onSubmit:m,onPatch:g,onDelete:y,outcome:f})}):null}function vee(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t});return n?o.jsx(ot,{maw:700,children:n.resourceType==="Patient"?o.jsx(eW,{patient:n}):o.jsx(Ya,{icon:o.jsx(rl,{size:16}),title:"Unsupported export type",color:"red",children:"This page is only supported for Patient resources"})}):null}function i4({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,i=_e(),[s,c]=v.useState();return v.useEffect(()=>{i.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(u=>{c(u.filter(Sq))}).catch(console.error)},[i,n,r]),o.jsx(Et,{value:t==null?void 0:t.url,onChange:u=>{const f=s==null?void 0:s.find(p=>p.url===u);f&&n(f)},children:o.jsx(Et.List,{children:s==null?void 0:s.map(u=>{var m,g;const f=(g=(m=e.meta)==null?void 0:m.profile)==null?void 0:g.includes(u.url),p=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 o.jsx(Et.Tab,{value:u.url,title:p,rightSection:f&&o.jsx(q0,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:o.jsx(zF,{size:"90%"})}),children:u.title||u.name},u.url)})})})}function a4(e,t){const n=_e(),r=wn();return{defaultValue:{resourceType:e},handleSubmit:c=>{t&&t(void 0),n.createResource(c).then(u=>r("/"+u.resourceType+"/"+u.id)).catch(u=>{t&&t(Zt(u)),Oe({color:"red",message:Ye(u),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function hy(){const{resourceType:e}=qt(),t=Mr(),[n,r]=v.useState(),{defaultValue:i,handleSubmit:s}=a4(e,r),[c,u]=v.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),p=v.useCallback(m=>{const g=sl(m);c&&RA(g,c.url),s(g)},[c,s]);return f?o.jsx(ot,{children:o.jsxs(Ge,{children:[o.jsx(i4,{resource:i,currentProfile:c,onChange:u}),c?o.jsx(Yh,{defaultValue:i,onSubmit:p,outcome:n,profileUrl:c.url},c.url):o.jsx(Ae,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):o.jsx(ot,{children:o.jsx(Yh,{defaultValue:i,onSubmit:s,outcome:n})})}function yee(){const e=_e(),{resourceType:t,id:n}=qt(),r=e.readHistory(t,n).read();return o.jsx(ot,{children:o.jsx(FY,{history:r})})}function xee(){const{resourceType:e}=qt(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:i}=a4(e,n),s=v.useCallback(c=>{i(JSON.parse(c["new-resource"]))},[i]);return o.jsxs(ot,{children:[t&&o.jsx(Kr,{outcome:t}),o.jsxs(pt,{onSubmit:s,children:[o.jsx(Dc,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:Ii(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),o.jsx(je,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:o.jsx(Ne,{type:"submit",children:"OK"})})]})]})}function bee(){const e=_e(),{resourceType:t,id:n}=qt(),r=Qt({reference:t+"/"+n}),i=wn(),[s,c]=v.useState(),u=v.useCallback(f=>{e.updateResource(sl(JSON.parse(f.resource))).then(()=>{var p;c(void 0),(p=i(`/${t}/${n}/details`))==null||p.catch(console.error),Oe({color:"green",message:"Success"})}).catch(p=>{Oe({color:"red",message:Ye(p),autoClose:!1})})},[e,t,n,i]);return r?o.jsxs(ot,{children:[s&&o.jsx(Kr,{outcome:s}),o.jsxs(pt,{onSubmit:u,children:[o.jsx(Dc,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:Ii(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),o.jsx(je,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:o.jsx(Ne,{type:"submit",children:"OK"})})]})]}):null}function See(){const{resourceType:e,id:t}=qt();return Qt({reference:e+"/"+t})?o.jsxs(ot,{children:[o.jsxs(Ya,{icon:o.jsx(rl,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",o.jsx("br",{}),o.jsx(Nt,{href:`/forms/${t}`,children:`/forms/${t}`})]}),o.jsx(dk,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function wee(){const e=_e(),{resourceType:t,id:n}=qt(),[r,i]=v.useState(),[s,c]=v.useState();return v.useEffect(()=>{e.readResource(t,n).then(u=>i(Qr(u))).catch(u=>{Oe({color:"red",message:Ye(u)})})},[e,t,n]),r?o.jsxs(ot,{children:[o.jsxs(Le,{order:2,children:["Available ",t," profiles"]}),o.jsx(Ge,{children:o.jsxs(o.Fragment,{children:[o.jsx(i4,{resource:r,currentProfile:s,onChange:c}),s?o.jsx(jee,{profile:s,resource:r,onResourceUpdated:u=>i(u)},s.url):o.jsx(Ae,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const jee=({profile:e,resource:t,onResourceUpdated:n})=>{const r=_e(),[i,s]=v.useState(),[c,u]=v.useState(()=>{var p,m;return(m=(p=t.meta)==null?void 0:p.profile)==null?void 0:m.includes(e.url)}),f=v.useCallback(p=>{s(void 0);const m=sl(p);c?RA(m,e.url):mU(m,e.url),r.updateResource(m).then(g=>{n(g),Oe({color:"green",message:"Success"})}).catch(g=>{s(Zt(g)),Oe({color:"red",message:Ye(g),autoClose:!1})})},[r,e.url,n,c]);return o.jsxs(Ge,{children:[o.jsx(jd,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:p=>u(p.currentTarget.checked),"data-testid":"profile-toggle"}),c?o.jsx(Yh,{profileUrl:e.url,defaultValue:t,onSubmit:f,outcome:i}):o.jsx("form",{noValidate:!0,onSubmit:p=>{p.preventDefault(),f(t)},children:o.jsx(je,{justify:"flex-end",mt:"xl",children:o.jsx(Ne,{type:"submit",children:"OK"})})})]})},o4={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},Cee=Object.keys(o4);function Eee(){const e=_e(),{id:t}=qt(),n=Qt({reference:`Questionnaire/${t}`}),[r,i]=v.useState(),[s,c]=v.useState("create"),[u,f]=v.useState(0),p=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>Tee(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},${zt(n)}`:zt(n)}`,channel:{type:"rest-hook",endpoint:zt(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"),Oe({color:"green",message:"Success"})}).catch(g=>Oe({color:"red",message:Ye(g),autoClose:!1}))}return o.jsxs(ot,{children:[o.jsx(Le,{children:"Bots"}),o.jsxs(Ge,{children:[p.length===0&&o.jsx("p",{children:"No bots found."}),p.map(g=>{var y;return o.jsxs("div",{children:[o.jsx("h3",{children:o.jsx(Lc,{value:{reference:(y=g.channel)==null?void 0:y.endpoint},link:!0})}),o.jsxs("p",{children:["Criteria: ",g.criteria]})]},g.id)})]}),o.jsx(Cn,{}),o.jsxs(Ge,{mt:10,children:[o.jsx(pd,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),o.jsxs(je,{children:[o.jsx(il,{name:"bot",resourceType:"Bot",onChange:g=>i(g)}),o.jsx(Ne,{onClick:m,children:"Connect"})]}),o.jsx(je,{children:o.jsx(ln,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:Cee,onChange:g=>c(o4[g.target.value])})})]}),o.jsx("div",{style:{display:"none"},children:u})]})}function Tee(e,t){var i;if(!t)return!1;const n=e.criteria||"",r=((i=e.channel)==null?void 0:i.endpoint)||"";return n.startsWith("QuestionnaireResponse?")&&r.startsWith("Bot/")&&(n.includes(zt(t))||(t.url?n.includes(t.url):!1))}function Ree(){const{id:e}=qt(),t=wn(),r=_e().readReference({reference:`Questionnaire/${e}`}).read(),[i,s]=v.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:ue.EQUALS,value:r.url?`${r.url},Questionnaire/${e}`:`Questionnaire/${e}`}],fields:["id","_lastUpdated"]});return o.jsx(ot,{children:o.jsx(zc,{search:i,onClick:c=>{var u;return(u=t(`/${c.resource.resourceType}/${c.resource.id}`))==null?void 0:u.catch(console.error)},onChange:c=>s(c.definition),hideFilters:!0,hideToolbar:!0})})}function Dee(){const e=_e(),{resourceType:t,id:n}=qt(),r=Qt({reference:t+"/"+n}),i=v.useCallback(s=>{e.updateResource(sl(s)).then(()=>{Oe({color:"green",message:"Success"})}).catch(c=>{Oe({color:"red",message:Ye(c),autoClose:!1})})},[e]);return r?o.jsx(ot,{children:o.jsx(uY,{onSubmit:i,definition:r})}):null}function Aee(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t});return n?o.jsx(ot,{children:e==="MeasureReport"?o.jsx(ZQ,{measureReport:n}):o.jsx(kb,{value:n})}):null}const _ee="_container_1ue98_1",kee="_entry_1ue98_14",Pee="_active_1ue98_21",py={container:_ee,entry:kee,active:Pee};function Nee(e){const t=_e(),n=Qt(e.value),[r,i]=v.useState();return v.useEffect(()=>{if(!n)return;const s=n1(n);if(!s)return;const c="reference"in s?s.reference:zt(s);t.search("ServiceRequest","subject="+c).then(u=>{const p=(u.entry??[]).map(m=>m.resource);U_(p),p.reverse(),i(p)}).catch(u=>Oe({color:"red",message:Ye(u),autoClose:!1}))},[t,n]),r?o.jsx("div",{"data-testid":"quick-service-requests",className:py.container,children:r.map(s=>{var c,u,f,p,m,g,y;return o.jsxs("div",{className:Ut(py.entry,{[py.active]:s.id===(n==null?void 0:n.id)}),children:[o.jsx("p",{children:o.jsx(mt,{to:s,children:Oee(s)})}),((u=(c=s.category)==null?void 0:c[0])==null?void 0:u.text)&&o.jsx("p",{children:(f=s.category[0])==null?void 0:f.text}),((g=(m=(p=s.code)==null?void 0:p.coding)==null?void 0:m[0])==null?void 0:g.code)&&o.jsx("p",{children:(y=s.code.coding[0])==null?void 0:y.code}),o.jsx("p",{children:Mee(s)})]},s.id)})}):null}function Oee(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function Mee(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const Iee="_container_1l2dh_1",Lee={container:Iee};function zee(e){var i,s,c,u;const t=Qt(e.valueSet);if(!t)return null;const n=[""],r=(u=(c=(s=(i=t.compose)==null?void 0:i.include)==null?void 0:s[0])==null?void 0:c.concept)==null?void 0:u.map(f=>f.code);return r&&n.push(...r),e.defaultValue&&!n.includes(e.defaultValue)&&n.push(e.defaultValue),o.jsx("div",{className:Lee.container,children:o.jsx(ln,{defaultValue:e.defaultValue,onChange:f=>e.onChange(f.currentTarget.value),data:n})})}function $ee(e){var n,r;const t=Qt(e.specimen);return t?o.jsxs(ht,{children:[o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Type"}),o.jsx(ht.Value,{children:"Specimen"})]}),o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Collected"}),o.jsx(ht.Value,{children:gr((n=t.collection)==null?void 0:n.collectedDateTime)})]}),o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Specimen Age"}),o.jsx(ht.Value,{children:Uee(t)})]}),(r=t.collection)!=null&&r.collectedDateTime&&t.receivedTime?o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Specimen Stability"}),o.jsx(ht.Value,{children:Bee(t)})]}):o.jsx(o.Fragment,{})]}):null}function Uee(e){var i;const t=(i=e.collection)==null?void 0:i.collectedDateTime;if(!t)return;const n=new Date(t);return s4(l4(n,new Date))}function Bee(e){var r;if(!((r=e.collection)!=null&&r.collectedDateTime)||!e.receivedTime)return;const t=new Date(e.collection.collectedDateTime),n=new Date(e.receivedTime);return s4(l4(t,n))}function s4(e){return e.toString().padStart(3,"0")+"D"}function l4(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function Vee(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==="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 Fee(){var D,E,R,A,k,M,I;const e=_e(),{resourceType:t,id:n}=qt(),r={reference:t+"/"+n},i=wn(),[s,c]=v.useState(),u=Qt(r,c),f=Vee(t),[p,m]=v.useState(()=>{const $=window.location.pathname.split("/").pop();return $&&f.map(V=>V.toLowerCase()).includes($)?$:f[0].toLowerCase()});async function g(){var Y,Q;const V=(Q=(Y=(await e.readHistory(t,n)).entry)==null?void 0:Y.find(J=>!!J.resource))==null?void 0:Q.resource;V?y(V):Oe({color:"red",message:"No history to restore",autoClose:!1})}function y($){e.updateResource(sl($)).then(()=>{c(void 0),Oe({color:"green",message:"Success"})}).catch(V=>{Oe({color:"red",message:Ye(V),autoClose:!1})})}if(s)return j8(s)?o.jsxs(ot,{children:[o.jsx(Le,{children:"Deleted"}),o.jsx("p",{children:"The resource was deleted."}),o.jsx(Ne,{color:"red",onClick:g,children:"Restore"})]}):o.jsx(Kr,{outcome:s});function b($){var V;$||($=f[0].toLowerCase()),m($),(V=i(`/${t}/${n}/${$}`))==null||V.catch(console.error)}function S($){const V=u,Y=V.orderDetail||[];Y.length===0&&Y.push({}),Y[0].text!==$&&(Y[0].text=$,y({...V,orderDetail:Y}))}const j=u&&n1(u),C=u&&sJ(u),T=(R=(E=(D=e.getUserConfiguration())==null?void 0:D.option)==null?void 0:E.find($=>$.id==="statusValueSet"))==null?void 0:R.valueString;return o.jsxs(o.Fragment,{children:[(u==null?void 0:u.resourceType)==="ServiceRequest"&&T&&o.jsx(zee,{valueSet:{reference:T},defaultValue:(k=(A=u.orderDetail)==null?void 0:A[0])==null?void 0:k.text,onChange:S},zt(u)+"-"+((I=(M=u.orderDetail)==null?void 0:M[0])==null?void 0:I.text)),u&&o.jsx(Nee,{value:u}),u&&o.jsxs(mr,{children:[j&&o.jsx(W_,{patient:j}),C&&o.jsx($ee,{specimen:C}),t!=="Patient"&&o.jsx(Xk,{resource:r}),o.jsx(Yr,{children:o.jsx(Et,{value:p.toLowerCase(),onChange:b,children:o.jsx(Et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:f.map($=>o.jsx(Et.Tab,{value:$.toLowerCase(),children:$},$))})})})]}),o.jsx(Yb,{})]})}function eR(){var T,D,E,R;const e=wn(),{resourceType:t,id:n,versionId:r,tab:i}=qt(),s=_e(),[c,u]=v.useState(!0),[f,p]=v.useState(),[m,g]=v.useState();if(v.useEffect(()=>{g(void 0),u(!0),s.readHistory(t,n).then(A=>p(A)).then(()=>u(!1)).catch(A=>{g(A),u(!1)})},[s,t,n]),c)return o.jsx(gi,{});if(!f)return o.jsxs(ot,{children:[o.jsx(Le,{children:"Resource not found"}),o.jsx(mt,{to:`/${t}`,children:"Return to search page"})]});const y=f.entry??[],b=y.findIndex(A=>{var k,M;return((M=(k=A.resource)==null?void 0:k.meta)==null?void 0:M.versionId)===r});if(b===-1)return o.jsxs(ot,{children:[o.jsx(Le,{children:"Version not found"}),o.jsx(mt,{to:`/${t}/${n}`,children:"Return to resource"})]});const S=y[b].resource,j=b<y.length-1?y[b+1].resource:void 0,C="diff";return o.jsxs(Et,{value:i||C,onChange:A=>{var k;return(k=e(`/${t}/${n}/_history/${r}/${A||C}`))==null?void 0:k.catch(console.error)},children:[o.jsxs(mr,{children:[o.jsx(Ic,{fluid:!0,p:"md",children:o.jsx(Ae,{children:`${t} ${n}`})}),o.jsxs(Et.List,{children:[o.jsx(Et.Tab,{value:"diff",children:"Diff"}),o.jsx(Et.Tab,{value:"raw",children:"Raw"})]})]}),o.jsxs(ot,{children:[m&&o.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)}),o.jsx(Et.Panel,{value:"diff",children:j?o.jsxs(o.Fragment,{children:[o.jsxs("ul",{children:[o.jsxs("li",{children:["Current: ",(T=S.meta)==null?void 0:T.versionId]}),o.jsxs("li",{children:["Previous:"," ",o.jsx(mt,{to:`/${t}/${n}/_history/${(D=j.meta)==null?void 0:D.versionId}`,children:(E=j.meta)==null?void 0:E.versionId})]})]}),o.jsx($Y,{original:j,revised:S})]}):o.jsxs(o.Fragment,{children:[o.jsxs("ul",{children:[o.jsxs("li",{children:["Current: ",(R=S.meta)==null?void 0:R.versionId]}),o.jsx("li",{children:"Previous: (none)"})]}),o.jsx("pre",{children:JSON.stringify(S,void 0,2)})]})}),o.jsx(Et.Panel,{value:"raw",children:o.jsx("pre",{children:JSON.stringify(S,void 0,2)})})]})]})}function Hee(){const{resourceType:e,id:t}=qt(),n=wn(),[r,i]=v.useState({resourceType:"Subscription",filters:[{code:"url",operator:ue.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return o.jsx(ot,{children:o.jsx(IQ,{search:r,onClick:s=>{var c;return(c=n(`/${s.resource.resourceType}/${s.resource.id}`))==null?void 0:c.catch(console.error)},onChange:s=>i(s.definition),hideFilters:!0})})}function qee(e){const t=_e(),{resource:n,opened:r,onClose:i}=e,[s,c]=v.useState(!1),[u,f]=v.useState(),[p,m]=v.useState(!1),g=v.useCallback(async()=>{if(n!=null&&n.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:s&&u?zt(u):void 0,verbose:p}),Oe({color:"green",message:"Done"}),i()}catch(y){Oe({color:"red",message:Ye(y),autoClose:!1})}},[t,n,i,s,u,p]);return o.jsx(Un,{opened:r,onClose:i,title:"Resend Subscriptions",children:o.jsx(pt,{onSubmit:g,children:o.jsxs(Ge,{children:[o.jsx(zn,{label:"Choose subscription (all subscriptions by default)",onChange:y=>c(y.currentTarget.checked)}),s&&o.jsx(il,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:f}),o.jsx(zn,{label:"Verbose mode",onChange:y=>m(y.currentTarget.checked)}),o.jsx(je,{justify:"flex-end",children:o.jsx(Ne,{type:"submit",children:"Resend"})})]})})})}function tR(){const e=_e(),t=Jp(),{resourceType:n,id:r}=qt(),i={reference:n+"/"+r},[s,c]=v.useState(),u=op(!1);function f(D,E){return e.updateResource({...D,priority:E})}function p(D,E){f(D,"stat").then(E).catch(console.error)}function m(D,E){f(D,"routine").then(E).catch(console.error)}function g(D){t(`/${D.resourceType}/${D.id}`)}function y(D){t(`/${D.resourceType}/${D.id}/edit`)}function b(D){t(`/${D.resourceType}/${D.id}/delete`)}function S(D){c(D),u[1].open()}function j(D){var E;t(`/${D.resourceType}/${D.id}/_history/${(E=D.meta)==null?void 0:E.versionId}`)}function C(D,E){const R="aws-textract";Oe({id:R,title:"AWS Textract in Progress",message:"Extracting text... This may take a moment...",loading:!0,autoClose:!1}),e.post(e.fhirUrl(D.resourceType,D.id,"$aws-textract"),{}).then(()=>{E(),As({id:R,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:o.jsx(eo,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(A=>As({id:R,title:"AWS Textract Error",color:"red",message:Ye(A),icon:o.jsx(Hs,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function T(D){var P;const{primaryResource:E,currentResource:R,reloadTimeline:A}=D,k=R.resourceType===E.resourceType&&R.id===E.id,M=R.resourceType==="Communication"&&R.priority!=="stat",I=R.resourceType==="Communication"&&R.priority==="stat",$=k,V=!k,Y=!k,Q=!k,J=(P=e.getProjectMembership())==null?void 0:P.admin,G=J,K=xJ()&&(R.resourceType==="DocumentReference"||R.resourceType==="Media");return o.jsxs(Ce.Dropdown,{children:[o.jsx(Ce.Label,{children:"Resource"}),M&&o.jsx(Ce.Item,{leftSection:o.jsx(CF,{size:14}),onClick:()=>p(R,A),"aria-label":`Pin ${zt(R)}`,children:"Pin"}),I&&o.jsx(Ce.Item,{leftSection:o.jsx(EF,{size:14}),onClick:()=>m(R,A),"aria-label":`Unpin ${zt(R)}`,children:"Unpin"}),V&&o.jsx(Ce.Item,{leftSection:o.jsx(ME,{size:14}),onClick:()=>g(R),"aria-label":`Details ${zt(R)}`,children:"Details"}),$&&o.jsx(Ce.Item,{leftSection:o.jsx(ME,{size:14}),onClick:()=>j(R),"aria-label":`Details ${zt(R)}`,children:"Details"}),Y&&o.jsx(Ce.Item,{leftSection:o.jsx(n_,{size:14}),onClick:()=>y(R),"aria-label":`Edit ${zt(R)}`,children:"Edit"}),J&&o.jsxs(o.Fragment,{children:[o.jsx(Ce.Divider,{}),o.jsx(Ce.Label,{children:"Admin"}),G&&o.jsx(Ce.Item,{leftSection:o.jsx(DF,{size:14}),onClick:()=>S(R),"aria-label":`Resend Subscriptions ${zt(R)}`,children:"Resend Subscriptions"})]}),K&&o.jsxs(o.Fragment,{children:[o.jsx(Ce.Divider,{}),o.jsx(Ce.Label,{children:"AWS AI"}),o.jsx(Ce.Item,{leftSection:o.jsx(IF,{size:14}),onClick:()=>C(R,A),"aria-label":`AWS Textract ${zt(R)}`,children:"AWS Textract"})]}),Q&&o.jsxs(o.Fragment,{children:[o.jsx(Ce.Divider,{}),o.jsx(Ce.Label,{children:"Danger zone"}),o.jsx(Ce.Item,{color:"red",leftSection:o.jsx(yb,{size:14}),onClick:()=>b(R),"aria-label":`Delete ${zt(R)}`,children:"Delete"})]})]})}return o.jsxs(o.Fragment,{children:[n==="Encounter"&&o.jsx(HG,{encounter:i,getMenu:T}),n==="Patient"&&o.jsx(rW,{patient:i,getMenu:T}),n==="ServiceRequest"&&o.jsx(GY,{serviceRequest:i,getMenu:T}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&o.jsx(FG,{resource:i,getMenu:T}),o.jsx(qee,{resource:s,opened:u[0],onClose:u[1].close},`resend-subscriptions-${s==null?void 0:s.id}`)]})}function Gee(e){const{opened:t,close:n,version:r,loadingStatus:i,handleStatus:s,handleUpgrade:c}=e,[u,f]=v.useState(),[p,m]=v.useState(!1);return v.useEffect(()=>{t&&(u||LV("app-tools-page").then(f).catch(console.error),s())},[t,u,s]),u&&r&&!i?r==="unknown"?o.jsx("p",{children:"Unable to determine the current version of the agent. Check the network connectivity of the agent."}):r.startsWith(u)?o.jsxs("p",{children:["This agent is already on the latest version (",u,")."]}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["Are you sure you want to upgrade this agent from version ",r," to version ",u,"?"]}),o.jsxs(je,{children:[o.jsx(Ne,{onClick:()=>{c(p),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"}),o.jsx(zn,{label:"Force",onChange:g=>m(g.currentTarget.checked)})]})]}):o.jsx(gi,{})}function Qee(){const e=_e(),{id:t}=qt(),n=v.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,i]=v.useState(!1),[s,c]=v.useState(!1),[u,f]=v.useState(!1),[p,m]=v.useState(),[g,y]=v.useState(),[b,S]=v.useState(),[j,C]=v.useState(),[T,D]=v.useState(!1),[E,R]=v.useState(!1),[A,{open:k,close:M}]=op(!1);v.useEffect(()=>{if(r||s||u||T){R(!0);return}R(!1)},[r,s,u,T]);const I=v.useCallback(()=>{i(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(G=>{var K,P,L,z,H,O;m((P=(K=G.parameter)==null?void 0:K.find(U=>U.name==="status"))==null?void 0:P.valueCode),y((z=(L=G.parameter)==null?void 0:L.find(U=>U.name==="version"))==null?void 0:z.valueString),S((O=(H=G.parameter)==null?void 0:H.find(U=>U.name==="lastUpdated"))==null?void 0:O.valueInstant)}).catch(G=>J(Ye(G))).finally(()=>i(!1))},[e,t]),$=v.useCallback(G=>{const K=G.host,P=G.pingCount||1;K&&(D(!0),e.pushToAgent(n,K,`PING ${P}`,hn.PING,!0).then(L=>C(L)).catch(L=>J(Ye(L))).finally(()=>D(!1)))},[e,n]),V=v.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(G=>{Q("Agent config reloaded successfully.")}).catch(G=>J(Ye(G))).finally(()=>c(!1))},[e,t]),Y=v.useCallback(G=>{f(!0),e.get(e.fhirUrl("Agent",t,"$upgrade",`?force=${G}`),{cache:"reload"}).then(K=>{Q("Agent upgraded successfully.")}).catch(K=>J(Ye(K))).finally(()=>f(!1))},[e,t]);function Q(G){Oe({color:"green",title:"Success",icon:o.jsx(eo,{size:"1rem"}),message:G})}function J(G){Oe({color:"red",title:"Error",message:G,autoClose:!1})}return o.jsxs(ot,{children:[o.jsx(Un,{opened:A,onClose:M,title:"Upgrade Agent",centered:!0,children:o.jsx(Gee,{opened:A,close:M,version:g,loadingStatus:r,handleStatus:I,handleUpgrade:Y})}),o.jsx(Le,{order:1,children:"Agent Tools"}),o.jsxs("div",{style:{marginBottom:10},children:["Agent: ",o.jsx(Lc,{value:n,link:!0})]}),o.jsx(Cn,{my:"lg"}),o.jsx(Le,{order:2,children:"Agent Status"}),o.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."}),o.jsx(Ne,{onClick:I,loading:r,disabled:E&&!r,children:"Get Status"}),!r&&p&&o.jsx(ye,{children:o.jsxs(ye.Tbody,{children:[o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:"Status"}),o.jsx(ye.Td,{children:o.jsx(am,{status:p})})]}),o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:"Version"}),o.jsx(ye.Td,{children:g})]}),o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:"Last Updated"}),o.jsx(ye.Td,{children:gr(b,void 0,{timeZoneName:"longOffset"})})]})]})}),o.jsx(Cn,{my:"lg"}),o.jsx(Le,{order:2,children:"Reload Config"}),o.jsx("p",{children:"Reload the configuration of this agent, syncing it with the current version of the Agent resource on the Medplum server."}),o.jsx(Ne,{onClick:V,loading:s,disabled:E&&!s,"aria-label":"Reload config",children:"Reload Config"}),o.jsx(Cn,{my:"lg"}),o.jsx(Le,{order:2,children:"Upgrade Agent"}),o.jsx("p",{children:"Upgrade the version of this agent, to either the latest (default) or a specified version."}),o.jsx(Ne,{onClick:k,loading:u,disabled:E&&!u,"aria-label":"Upgrade agent",children:"Upgrade"}),o.jsx(Cn,{my:"lg"}),o.jsx(Le,{order:2,children:"Ping from Agent"}),o.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."}),o.jsx(pt,{onSubmit:$,children:o.jsxs(je,{children:[o.jsx(ze,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:o.jsx(_n,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:T,disabled:E&&!T,children:o.jsx(_F,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),o.jsx(Ip,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!T&&j&&o.jsxs(o.Fragment,{children:[o.jsx(Le,{order:5,mt:"sm",mb:0,children:"Last Ping"}),o.jsx("pre",{children:j})]})]})}function Wee(){return o.jsx(CX,{children:o.jsxs(Fe,{errorElement:o.jsx(oJ,{}),children:[o.jsx(Fe,{path:"/signin",element:o.jsx(EJ,{})}),o.jsx(Fe,{path:"/oauth",element:o.jsx(bJ,{})}),o.jsx(Fe,{path:"/resetpassword",element:o.jsx(wJ,{})}),o.jsx(Fe,{path:"/setpassword/:id/:secret",element:o.jsx(CJ,{})}),o.jsx(Fe,{path:"/register",element:o.jsx(SJ,{})}),o.jsx(Fe,{path:"/changepassword",element:o.jsx(rJ,{})}),o.jsx(Fe,{path:"/security",element:o.jsx(jJ,{})}),o.jsx(Fe,{path:"/mfa",element:o.jsx(yJ,{})}),o.jsx(Fe,{path:"/batch",element:o.jsx(tJ,{})}),o.jsx(Fe,{path:"/bulk/:resourceType",element:o.jsx(nJ,{})}),o.jsx(Fe,{path:"/smart",element:o.jsx(TJ,{})}),o.jsx(Fe,{path:"/forms/:id",element:o.jsx(lJ,{})}),o.jsx(Fe,{path:"/admin/super",element:o.jsx(qJ,{})}),o.jsx(Fe,{path:"/admin/super/asyncjob",element:o.jsx($J,{})}),o.jsx(Fe,{path:"/admin/config",element:o.jsx(MJ,{})}),o.jsxs(Fe,{path:"/admin",element:o.jsx(IJ,{}),children:[o.jsx(Fe,{path:"patients",element:o.jsx(OJ,{})}),o.jsx(Fe,{path:"bots/new",element:o.jsx(AJ,{})}),o.jsx(Fe,{path:"bots",element:o.jsx(RJ,{})}),o.jsx(Fe,{path:"clients/new",element:o.jsx(_J,{})}),o.jsx(Fe,{path:"clients",element:o.jsx(DJ,{})}),o.jsx(Fe,{path:"details",element:o.jsx(WT,{})}),o.jsx(Fe,{path:"invite",element:o.jsx(NJ,{})}),o.jsx(Fe,{path:"users",element:o.jsx(QJ,{})}),o.jsx(Fe,{path:"project",element:o.jsx(WT,{})}),o.jsx(Fe,{path:"secrets",element:o.jsx(LJ,{})}),o.jsx(Fe,{path:"sites",element:o.jsx(zJ,{})}),o.jsx(Fe,{path:"members/:membershipId",element:o.jsx(PJ,{})})]}),o.jsx(Fe,{path:"/lab/assays",element:o.jsx(WJ,{})}),o.jsx(Fe,{path:"/lab/panels",element:o.jsx(YJ,{})}),o.jsx(Fe,{path:"/:resourceType/:id/_history/:versionId/:tab",element:o.jsx(eR,{})}),o.jsx(Fe,{path:"/:resourceType/:id/_history/:versionId",element:o.jsx(eR,{})}),o.jsxs(Fe,{path:"/:resourceType/new",element:o.jsx(aJ,{}),children:[o.jsx(Fe,{index:!0,element:o.jsx(hy,{})}),o.jsx(Fe,{path:"form",element:o.jsx(hy,{})}),o.jsx(Fe,{path:"json",element:o.jsx(xee,{})}),o.jsx(Fe,{path:"profiles",element:o.jsx(hy,{})})]}),o.jsxs(Fe,{path:"/:resourceType/:id",element:o.jsx(Fee,{}),children:[o.jsx(Fe,{index:!0,element:o.jsx(tR,{})}),o.jsx(Fe,{path:"apply",element:o.jsx(XJ,{})}),o.jsx(Fe,{path:"apps",element:o.jsx(ZJ,{})}),o.jsx(Fe,{path:"event",element:o.jsx(eee,{})}),o.jsx(Fe,{path:"blame",element:o.jsx(tee,{})}),o.jsx(Fe,{path:"bots",element:o.jsx(Eee,{})}),o.jsx(Fe,{path:"builder",element:o.jsx(uee,{})}),o.jsx(Fe,{path:"checklist",element:o.jsx(dee,{})}),o.jsx(Fe,{path:"delete",element:o.jsx(fee,{})}),o.jsx(Fe,{path:"details",element:o.jsx(mee,{})}),o.jsx(Fe,{path:"edit",element:o.jsx(gee,{})}),o.jsx(Fe,{path:"editor",element:o.jsx(lee,{})}),o.jsx(Fe,{path:"history",element:o.jsx(yee,{})}),o.jsx(Fe,{path:"json",element:o.jsx(bee,{})}),o.jsx(Fe,{path:"preview",element:o.jsx(See,{})}),o.jsx(Fe,{path:"responses",element:o.jsx(Ree,{})}),o.jsx(Fe,{path:"report",element:o.jsx(Aee,{})}),o.jsx(Fe,{path:"ranges",element:o.jsx(Dee,{})}),o.jsx(Fe,{path:"subscriptions",element:o.jsx(Hee,{})}),o.jsx(Fe,{path:"timeline",element:o.jsx(tR,{})}),o.jsx(Fe,{path:"tools",element:o.jsx(Qee,{})}),o.jsx(Fe,{path:"profiles",element:o.jsx(wee,{})}),o.jsx(Fe,{path:"export",element:o.jsx(vee,{})})]}),o.jsx(Fe,{path:"/:resourceType",element:o.jsx(QT,{})}),o.jsx(Fe,{path:"/",element:o.jsx(QT,{})})]})})}function Yee(){const e=_e(),t=e.getUserConfiguration(),n=Mr(),[r]=Zb();return e.isLoading()?o.jsx(gi,{}):o.jsx(_H,{logo:o.jsx(Ui,{size:24}),pathname:n.pathname,searchParams:r,version:qA,menus:Kee(t),displayAddBookmark:!!(t!=null&&t.id),children:o.jsx(v.Suspense,{fallback:o.jsx(gi,{}),children:o.jsx(Wee,{})})})}function Kee(e){var n;const t=((n=e==null?void 0:e.menu)==null?void 0:n.map(r=>{var i;return{title:r.title,links:((i=r.link)==null?void 0:i.map(s=>({label:s.name,href:s.target,icon:Xee(s.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:o.jsx(yF,{})}]}),t}const nR={Patient:NF,Practitioner:gF,Organization:oF,ServiceRequest:RF,DiagnosticReport:AF,Questionnaire:mF,admin:rF,AccessPolicy:vF,Subscription:LF,batch:jF,Observation:SF};function Xee(e){try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in nR){const n=nR[t];return o.jsx(n,{})}}catch{}return o.jsx(Hp,{w:30})}"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.getRegistrations().then(e=>Promise.all(e.map(t=>t.unregister()))).catch(e=>console.error("SW registration failed: ",e))});async function Zee(){const e=Bd(),t=new GA({baseUrl:e.baseUrl,clientId:e.clientId,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=YX([{path:"*",element:o.jsx(Yee,{})}]),i=c=>r.navigate(c);ZY.createRoot(document.getElementById("root")).render(o.jsx(v.StrictMode,{children:o.jsx(zV,{medplum:t,navigate:i,children:o.jsxs(RR,{theme:n,children:[o.jsx(Za,{position:"bottom-right"}),o.jsx(bX,{router:r})]})})}))}Zee().catch(console.error);
586
- //# sourceMappingURL=index-pFIY7gpZ.js.map
586
+ //# sourceMappingURL=index-CoQi1ijo.js.map