@medplum/app 4.1.13 → 4.1.14
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.
|
@@ -73,9 +73,9 @@ function f3(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
|
|
|
73
73
|
Prefix can't start with '-' when allowNegative is true.
|
|
74
74
|
prefix: `+i+`
|
|
75
75
|
allowNegative: `+s+`
|
|
76
|
-
`),s=!1),Object.assign(Object.assign({},e),{allowNegative:s})}function BL(e){e=UL(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,h=e.prefix;h===void 0&&(h="");var m=e.defaultValue,g=e.value,y=e.valueIsNumericString,b=e.onValueChange,S=wD(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 qC(P,e)},E=function(P,L){return zL(P,L,e)},R=ic(g)?m:g,A=y??LL(R,h,t);ic(g)?ic(m)||(A=A||typeof m=="number"):A=A||typeof g=="number";var k=function(P){return jD(P)?P:(typeof P=="number"&&(P=TD(P)),A&&typeof u=="number"?FC(P,u,!!f):P)},M=DD(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<h.length){P.preventDefault();return}if(H!==O){i(P);return}z==="Backspace"&&U[0]==="-"&&H===h.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 K=c===!0?",":c;z==="Backspace"&&U[H-1]===K&&Es(L,H-1),z==="Delete"&&U[H]===K&&Es(L,H+1),i(P)},J=function(P){var L=$;if(L.match(/\d/g)||(L=""),r||(L=CL(L)),f&&u&&(L=FC(L,u,f)),L!==$){var z=qC(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)},Z=function(P){var L=P.currentValue,z=P.lastValue,H=P.formattedValue,O=P.currentValueIndex,U=P.formattedValueIndex,K=L[O],ee=H[U],Se=RD(z,L),be=Se.to,xe=function(qe){return E(qe).indexOf(".")+h.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(K)&&ee===C?!0:K===ee};return Object.assign(Object.assign({},S),{value:V,valueIsNumericString:!1,isValidInputCharacter:G,isCharacterSame:Z,onValueChange:Y,format:D,removeFormatting:E,getCaretBoundary:function(P){return $L(P,e)},onKeyDown:Q,onBlur:J})}function VL(e){var t=BL(e);return En.createElement(OL,Object.assign({},t))}function GC({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 _y={root:"m_e2f5cd4e",controls:"m_95e17d22",control:"m_80b4b171"};const FL=/^(0\.0*|-0(\.0*)?)$/,HL=/^-?0\d+(\.\d+)?\.?$/;function ky(e){return typeof e=="string"&&e!==""&&!Number.isNaN(Number(e))}function Bv(e){return typeof e=="number"?e<Number.MAX_SAFE_INTEGER:e===""||ky(e)&&Number(e)<Number.MAX_SAFE_INTEGER}function qL(e){return e.toString().replace(".","").length}function GL(e,t){return(typeof e=="number"?e<Number.MAX_SAFE_INTEGER:!Number.isNaN(Number(e)))&&!Number.isNaN(e)&&qL(t)<14&&t!==""}function QC(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 QL={step:1,clampBehavior:"blur",allowDecimal:!0,allowNegative:!0,withKeyboardEvents:!0,allowLeadingZeros:!0,trimLeadingZeroesOnBlur:!0,startValue:0},WL=(e,{size:t})=>({controls:{"--ni-chevron-size":rt(t,"ni-chevron-size")}});function YL(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:gh(i,n,t)}const Ip=ve((e,t)=>{const n=se("NumberInput",QL,e),{className:r,classNames:i,styles:s,unstyled:c,vars:u,onChange:f,onValueChange:h,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:Z,stepHoldInterval:P,stepHoldDelay:L,allowLeadingZeros:z,withKeyboardEvents:H,trimLeadingZeroesOnBlur:O,...U}=n,K=Ie({name:"NumberInput",classes:_y,props:n,classNames:i,styles:s,unstyled:c,vars:u,varsResolver:WL}),{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(GL(we.floatValue,we.value)&&!FL.test(we.value)&&!(z&&HL.test(we.value))?we.floatValue:we.value),h==null||h(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(Rh);gt.current=()=>{if(!Bv(be))return;let we;const $e=It(be),yt=It(S),ft=Math.max($e,yt),Gt=10**ft;if(!ky(be)&&(typeof be!="number"||Number.isNaN(be)))we=gh($,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)),h==null||h({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(Rh);At.current=()=>{if(!Bv(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(!ky(be)&&typeof be!="number"||Number.isNaN(be))we=gh($,$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)),h==null||h({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=gh($e,b,y)),O&&typeof $e=="string"&&It($e)<15&&($e=YL($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",{...K("controls"),children:[o.jsx(tr,{...K("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(GC,{direction:"up"})}),o.jsx(tr,{...K("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(GC,{direction:"down"})})]});return o.jsx(Pr,{component:VL,allowNegative:Q,className:Ut(_y.root,r),size:G,...U,readOnly:J,disabled:V,value:be,getInputRef:zn(t,Me),onValueChange:vt,rightSection:j||J||!Bv(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:Z??`var(--ni-right-section-width-${G||"sm"})`,allowLeadingZeros:z,onBlur:De,isAllowed:we=>D==="strict"?T?T(we)&&QC(we.floatValue,b,y):QC(we.floatValue,b,y):T?T(we):!0})});Ip.classes={...Pr.classes,..._y};Ip.displayName="@mantine/core/NumberInput";const[KL,Lp]=vr("Pagination.Root component was not found in tree");var Sd={root:"m_4addd315",control:"m_326d024a",dots:"m_4ad7767d"};const XL={withPadding:!0},wd=ve((e,t)=>{const n=se("PaginationControl",XL,e),{classNames:r,className:i,style:s,styles:c,vars:u,active:f,disabled:h,withPadding:m,mod:g,...y}=n,b=Lp(),S=h||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})});wd.classes=Sd;wd.displayName="@mantine/core/PaginationControl";function jd({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 ZL=e=>o.jsx(jd,{...e,path:"M8.781 8l-3.3-3.3.943-.943L10.667 8l-4.243 4.243-.943-.943 3.3-3.3z"}),JL=e=>o.jsx(jd,{...e,path:"M7.219 8l3.3 3.3-.943.943L5.333 8l4.243-4.243.943.943-3.3 3.3z"}),e6=e=>o.jsx(jd,{...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"}),t6=e=>o.jsx(jd,{...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"}),n6=e=>o.jsx(jd,{...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"}),r6={icon:n6},zp=ve((e,t)=>{const n=se("PaginationDots",r6,e),{classNames:r,className:i,style:s,styles:c,vars:u,icon:f,...h}=n,m=Lp(),g=f;return o.jsx(ce,{ref:t,...m.getStyles("dots",{className:i,style:s,styles:c,classNames:r}),...h,children:o.jsx(g,{style:{width:"calc(var(--pagination-control-size) / 1.8)",height:"calc(var(--pagination-control-size) / 1.8)"}})})});zp.classes=Sd;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,...h}=se(t,i,c),m=f,g=Lp(),y=r==="next"?g.active===g.total:g.active===1;return o.jsx(wd,{disabled:g.disabled||y,ref:u,onClick:g[n],withPadding:!1,...h,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 AD=$p({icon:ZL,name:"PaginationNext",action:"onNext",type:"next"}),_D=$p({icon:JL,name:"PaginationPrevious",action:"onPrevious",type:"previous"}),kD=$p({icon:e6,name:"PaginationFirst",action:"onFirst",type:"previous"}),PD=$p({icon:t6,name:"PaginationLast",action:"onLast",type:"next"});function _0({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(wd,{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})}_0.displayName="@mantine/core/PaginationItems";const i6={siblings:1,boundaries:1},a6=(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",i6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,total:h,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:Sd,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:a6}),{range:V,setPage:Y,next:Q,previous:J,active:G,first:Z,last:P}=CN({page:m,initialPage:g,onChange:y,total:h,siblings:S,boundaries:j}),L=Rr(D,Q),z=Rr(E,J),H=Rr(R,Z),O=Rr(A,P);return o.jsx(KL,{value:{total:h,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=Sd;Up.displayName="@mantine/core/PaginationRoot";const o6={withControls:!0,withPages:!0,siblings:1,boundaries:1,gap:8},$i=ve((e,t)=>{const n=se("Pagination",o6,e),{withEdges:r,withControls:i,getControlProps:s,nextIcon:c,previousIcon:u,lastIcon:f,firstIcon:h,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(Ce,{gap:y,children:[r&&o.jsx(kD,{icon:h,...s==null?void 0:s("first")}),i&&o.jsx(_D,{icon:u,...s==null?void 0:s("previous")}),S&&o.jsx(_0,{dotsIcon:m}),i&&o.jsx(AD,{icon:c,...s==null?void 0:s("next")}),r&&o.jsx(PD,{icon:f,...s==null?void 0:s("last")})]})})});$i.classes=Sd;$i.displayName="@mantine/core/Pagination";$i.Root=Up;$i.Control=wd;$i.Dots=zp;$i.First=kD;$i.Last=PD;$i.Next=AD;$i.Previous=_D;$i.Items=_0;const s6=({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 Py={root:"m_f61ca620",input:"m_ccf8da4c",innerInput:"m_f2d85dd2",visibilityToggle:"m_b1072d44"};const l6={visibilityToggleIcon:s6},c6=(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",l6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,required:h,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:Z,onVisibilityChange:P,visibilityToggleIcon:L,visibilityToggleButtonProps:z,rightSectionProps:H,leftSectionProps:O,leftSectionPointerEvents:U,withErrorStyles:K,mod:ee,...Se}=n,be=yr(b),[xe,qe]=Yn({value:G,defaultValue:Z,finalValue:!1,onChange:P}),Me=()=>qe(!xe),tt=Ie({name:"PasswordInput",classes:Py,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:c6}),{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:h,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(Py.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:K,children:o.jsx("input",{required:h,"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,...Py};Ni.displayName="@mantine/core/PasswordInput";const[u6,ND]=Ha(),[d6,f6]=Ha();var OD={card:"m_9dc8ae12"};const h6={withBorder:!0},p6=(e,{radius:t})=>({card:{"--card-radius":Vt(t)}}),k0=ve((e,t)=>{const n=se("RadioCard",h6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,checked:h,mod:m,withBorder:g,value:y,onClick:b,name:S,onKeyDown:j,...C}=n,T=Ie({name:"RadioCard",classes:OD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:p6,rootSelector:"card"}),{dir:D}=Zs(),E=ND(),R=typeof h=="boolean"?h:(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(d6,{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})})});k0.displayName="@mantine/core/RadioCard";k0.classes=OD;const m6={},P0=ve((e,t)=>{const{value:n,defaultValue:r,onChange:i,size:s,wrapperProps:c,children:u,name:f,readOnly:h,...m}=se("RadioGroup",m6,e),g=yr(f),[y,b]=Yn({value:n,defaultValue:r,finalValue:"",onChange:i}),S=j=>!h&&b(typeof j=="string"?j:j.currentTarget.value);return o.jsx(u6,{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(a0,{role:"radiogroup",children:u})})})});P0.classes=mn.Wrapper.classes;P0.displayName="@mantine/core/RadioGroup";function MD({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 ID={indicator:"m_717d7ff6",icon:"m_3e4da632","indicator--outline":"m_2980836c"};const g6={icon:MD},v6=(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}}},N0=ve((e,t)=>{const n=se("RadioIndicator",g6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,icon:h,radius:m,color:g,iconColor:y,autoContrast:b,checked:S,mod:j,variant:C,disabled:T,...D}=n,E=h,R=Ie({name:"RadioIndicator",classes:ID,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:v6,rootSelector:"indicator"}),A=f6(),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")})})});N0.displayName="@mantine/core/RadioIndicator";N0.classes=ID;var LD={root:"m_f3f1af94",inner:"m_89c4f5e4",icon:"m_f3ed6b2b",radio:"m_8a3dbb89","radio--outline":"m_1bfe9d39"};const y6={labelPosition:"right"},x6=(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",y6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,id:h,size:m,label:g,labelPosition:y,description:b,error:S,radius:j,color:C,variant:T,disabled:D,wrapperProps:E,icon:R=MD,rootRef:A,iconColor:k,onChange:M,mod:I,...$}=n,V=Ie({name:"Radio",classes:LD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:x6}),Y=ND(),Q=(Y==null?void 0:Y.size)??m,J=n.size?m:Q,{styleProps:G,rest:Z}=Qa($),P=yr(h),L=Y?{checked:Y.value===Z.value,name:Z.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,...Z,...L,component:"input",mod:{error:!!S},ref:t,id:P,disabled:D,type:"radio"}),o.jsx(R,{...V("icon"),"aria-hidden":!0})]})})});Us.classes=LD;Us.displayName="@mantine/core/Radio";Us.Group=P0;Us.Card=k0;Us.Indicator=N0;const b6={duration:100,transition:"fade"};function S6(e,t){return{...b6,...t,...e}}function w6({offset:e,position:t,defaultOpened:n}){const[r,i]=v.useState(n),s=v.useRef(null),{x:c,y:u,elements:f,refs:h,update:m,placement:g}=Px({placement:t,middleware:[Dx({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})=>{h.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(h.floating.current){const j=s.current;j.addEventListener("mousemove",S);const C=Ia(h.floating.current);return C.forEach(T=>{T.addEventListener("scroll",m)}),()=>{j.removeEventListener("mousemove",S),C.forEach(T=>{T.removeEventListener("scroll",m)})}}},[f.reference,h.floating.current,m,S,r]),{handleMouseMove:S,x:c,y:u,opened:r,setOpened:i,boundaryRef:s,floating:h.setFloating}}var Bp={tooltip:"m_1b3c8819",arrow:"m_f898399f"};const j6={refProp:"ref",withinPortal:!0,offset:10,defaultOpened:!1,position:"right",zIndex:Wr("popover")},C6=(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}}),O0=ve((e,t)=>{const n=se("TooltipFloating",j6,e),{children:r,refProp:i,withinPortal:s,style:c,className:u,classNames:f,styles:h,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:h,unstyled:m,rootSelector:"tooltip",vars:A,varsResolver:C6}),{handleMouseMove:V,x:Y,y:Q,opened:J,boundaryRef:G,floating:Z,setOpened:P}=w6({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=zn(G,sp(r),t),z=r.props,H=U=>{var K;(K=z.onMouseEnter)==null||K.call(z,U),V(U),P(!0)},O=U=>{var K;(K=z.onMouseLeave)==null||K.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:Z,mod:{multiline:C},children:b})}),v.cloneElement(r,{...z,[i]:L,onMouseEnter:H,onMouseLeave:O})]})});O0.classes=Bp;O0.displayName="@mantine/core/TooltipFloating";const zD=v.createContext(!1),E6=zD.Provider,T6=()=>v.useContext(zD),R6={openDelay:0,closeDelay:0};function M0(e){const{openDelay:t,closeDelay:n,children:r}=se("TooltipGroup",R6,e);return o.jsx(E6,{value:!0,children:o.jsx(n9,{delay:{open:t,close:n},children:r})})}M0.displayName="@mantine/core/TooltipGroup";M0.extend=e=>e;function D6(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 A6(e){const t=D6(e.middlewares),n=[QR(e.offset)];return t.shift&&n.push(Dx(typeof t.shift=="boolean"?{padding:8}:{padding:8,...t.shift})),t.flip&&n.push(typeof t.flip=="boolean"?Nh():Nh(t.flip)),n.push(WR({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 _6(e){var k,M,I;const[t,n]=v.useState(e.defaultOpened),i=typeof e.opened=="boolean"?e.opened:t,s=T6(),c=yr(),u=v.useCallback($=>{n($),$&&D(c)},[c]),{x:f,y:h,context:m,refs:g,update:y,placement:b,middlewareData:{arrow:{x:S,y:j}={}}}=Px({strategy:e.strategy,placement:e.position,open:i,onOpenChange:u,middleware:A6(e)}),{delay:C,currentId:T,setCurrentId:D}=r9(m,{id:c}),{getReferenceProps:E,getFloatingProps:R}=u9([e9(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)}),c9(m,{enabled:(I=e.events)==null?void 0:I.focus,visibleOnly:!0}),f9(m,{role:"tooltip"}),s9(m,{enabled:typeof e.opened>"u"})]);b2({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:h,arrowX:S,arrowY:j,reference:g.setReference,floating:g.setFloating,getFloatingProps:R,getReferenceProps:E,isGroupPhase:A,opened:i,placement:b}}const WC={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}},k6=(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",WC,e),{children:r,position:i,refProp:s,label:c,openDelay:u,closeDelay:f,onPositionChange:h,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:Z,onClick:P,onMouseEnter:L,onMouseLeave:z,inline:H,variant:O,keepMounted:U,vars:K,portalProps:ee,mod:Se,floatingStrategy:be,middlewares:xe,...qe}=se("Tooltip",WC,n),{dir:Me}=Zs(),tt=v.useRef(null),ke=_6({position:h2(Me,i),closeDelay:f,openDelay:u,onPositionChange:h,opened:m,defaultOpened:g,events:Q,arrowRef:tt,arrowOffset:k,offset:typeof $=="number"?$+(R?A/2:0):$,positionDependencies:[...Z,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:K,varsResolver:k6});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=zn(ke.reference,sp(r),t),Lt=S6(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(Ix,{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=O0;el.Group=M0;function P6({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 $D({size:e,value:t,offset:n,sum:r,thickness:i,root:s,color:c,lineRoundCaps:u,tooltip:f,getStyles:h,display:m,...g}){const y=Sn();return o.jsx(el.Floating,{disabled:!f,label:f,children:o.jsx(ce,{component:"circle",...g,...h("curve"),__vars:{"--curve-color":c?Ht(c,y):void 0},fill:"none",strokeLinecap:u?"round":"butt",...P6({sum:r,size:e,thickness:i,value:t,offset:n,root:s})})})}$D.displayName="@mantine/core/Curve";function N6({size:e,thickness:t,sections:n,renderRoundedLineCaps:r,rootColor:i}){const s=n.reduce((m,g)=>m+g.value,0),c=Math.PI*((e*.9-t*2)/2)*2;let u=c;const f=[],h=[];for(let m=0;m<n.length;m+=1)f.push({sum:s,offset:u,data:n[m],root:!1}),u-=n[m].value/100*c;if(f.push({sum:s,offset:u,data:{color:i},root:!0}),h.push({...f[f.length-1],lineRoundCaps:!1}),f.length>2){h.push({...f[0],lineRoundCaps:r}),h.push({...f[f.length-2],lineRoundCaps:r});for(let m=1;m<=f.length-3;m+=1)h.push({...f[m],lineRoundCaps:!1})}else h.push({...f[0],lineRoundCaps:r});return h}var UD={root:"m_b32e4812",svg:"m_d43b5134",curve:"m_b1ca1fbf",label:"m_b23f9dc4"};function O6(e,t){return Math.min(e||12,(t||120)/4)}const M6={size:120,thickness:12},I6=(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",M6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,label:h,sections:m,size:g,thickness:y,roundCaps:b,rootColor:S,transitionDuration:j,...C}=n,T=Ie({name:"RingProgress",classes:UD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:I6}),D=O6(y,g),E=N6({size:g,thickness:D,sections:m,renderRoundedLineCaps:b,rootColor:S}).map(({data:R,sum:A,root:k,lineRoundCaps:M,offset:I},$)=>v.createElement($D,{...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}),h&&o.jsx("div",{...T("label"),children:h})]})});Vp.classes=UD;Vp.displayName="@mantine/core/RingProgress";var BD={root:"m_cf365364",indicator:"m_9e182ccd",label:"m_1738fcb2",input:"m_1714d588",control:"m_69686b9b",innerLabel:"m_78882f40"};const L6={withItemsBorders:!0},z6=(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",L6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,data:h,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:BD,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:z6}),J=Sn(),G=h.map(ke=>typeof ke=="string"?{label:ke,value:ke}:ke),Z=_N(),[P,L]=v.useState(Dh()),[z,H]=v.useState(null),[O,U]=v.useState({}),K=(ke,vt)=>{O[vt]=ke,U(O)},[ee,Se]=Yn({value:m,defaultValue:g,finalValue:Array.isArray(h)?((Me=G.find(ke=>!ke.disabled))==null?void 0:Me.value)??((tt=h[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=>K(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=zn(t,ke=>H(ke));return RN(()=>{L(Dh())},[h.length]),h.length===0?null:o.jsxs(ce,{...Q("root"),variant:M,size:b,ref:qe,mod:[{"full-width":T,orientation:D,initialized:Z,"with-items-borders":$},V],...Y,role:"radiogroup","data-disabled":j,children:[typeof ee=="string"&&o.jsx(Vx,{target:O[ee],parent:z,component:"span",transitionDuration:"var(--sc-transition-duration)",...Q("indicator")},P),xe]})});Fp.classes=BD;Fp.displayName="@mantine/core/SegmentedControl";function $6({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),{}),h=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:h,selector:r})}function Vv(e){return typeof e=="object"&&e!==null?sn(e):[]}function U6(e){return e.sort((t,n)=>Ku(t)-Ku(n))}function B6({spacing:e,verticalSpacing:t,cols:n}){const r=Array.from(new Set([...Vv(e),...Vv(t),...Vv(n)]));return U6(r)}function V6({spacing:e,verticalSpacing:t,cols:n,selector:r}){var h;const i=t===void 0?e:t,s=qo({"--sg-spacing-x":Nn(_i(e)),"--sg-spacing-y":Nn(_i(i)),"--sg-cols":(h=_i(n))==null?void 0:h.toString()}),c=B6({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 VD={container:"m_925c2d2c",root:"m_2415a157"};const F6={cols:1,spacing:"md",type:"media"},I0=ve((e,t)=>{const n=se("SimpleGrid",F6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,cols:h,verticalSpacing:m,spacing:g,type:y,...b}=n,S=Ie({name:"SimpleGrid",classes:VD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f}),j=hd();return y==="container"?o.jsxs(o.Fragment,{children:[o.jsx(V6,{...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($6,{...n,selector:`.${j}`}),o.jsx(ce,{ref:t,...S("root",{className:j}),...b})]})});I0.classes=VD;I0.displayName="@mantine/core/SimpleGrid";const H6={},Hp=ve((e,t)=>{const{w:n,h:r,miw:i,mih:s,...c}=se("Space",H6,e);return o.jsx(ce,{ref:t,...c,w:n,miw:i??n,h:r,mih:s??r})});Hp.displayName="@mantine/core/Space";var FD={root:"m_6d731127"};const q6={gap:"md",align:"stretch",justify:"flex-start"},G6=(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",q6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,align:h,justify:m,gap:g,variant:y,...b}=n,S=Ie({name:"Stack",props:n,classes:FD,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:G6});return o.jsx(ce,{ref:t,...S("root"),variant:y,...b})});Ge.classes=FD;Ge.displayName="@mantine/core/Stack";const[Q6,W6]=vr("Stepper component was not found in tree"),Mh=()=>null;Mh.displayName="@mantine/core/StepperCompleted";var L0={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 ah=(e,t)=>typeof e=="function"?o.jsx(e,{step:t||0}):e,Y6={withIcon:!0,allowStepClick:!0,iconPosition:"left"},z0=ve((e,t)=>{const{classNames:n,className:r,style:i,styles:s,vars:c,step:u,state:f,color:h,icon:m,completedIcon:g,progressIcon:y,label:b,description:S,withIcon:j,iconSize:C,loading:T,allowStepClick:D,allowStepSelect:E,iconPosition:R,orientation:A,mod:k,...M}=se("StepperStep",Y6,e),I=W6(),$=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":h?Ht(h,$):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)}):ah(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:h}):ah(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:ah(b,u)}),S&&o.jsx("span",{...I.getStyles("stepDescription",V),children:ah(S,u)})]})]})});z0.classes=L0;z0.displayName="@mantine/core/StepperStep";const K6={orientation:"horizontal",iconPosition:"left",allowNextStepsSelect:!0,wrap:!0},X6=(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",K6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,children:h,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:L0,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:X6}),Y=v.Children.toArray(h),Q=Y.filter(U=>U.type!==Mh),J=Y.find(U=>U.type===Mh),G=Q.reduce((U,K,ee)=>{const Se=g===ee?"stepProgress":g>ee?"stepCompleted":"stepInactive",xe=typeof m!="function"?!1:typeof K.props.allowStepSelect=="boolean"?K.props.allowStepSelect:Se==="stepCompleted"||k;return U.push(v.cloneElement(K,{icon:K.props.icon||y||ee+1,key:ee,step:ee,state:Se,onClick:()=>xe&&(m==null?void 0:m(ee)),allowStepClick:xe,completedIcon:K.props.completedIcon||b,progressIcon:K.props.progressIcon||S,color:K.props.color||j,iconSize:C,iconPosition:K.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},[]),Z=(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:Z;return o.jsx(Q6,{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=L0;mc.displayName="@mantine/core/Stepper";mc.Completed=Mh;mc.Step=z0;const HD=v.createContext(null),Z6=HD.Provider,J6=()=>v.useContext(HD),ez={},$0=ve((e,t)=>{const{value:n,defaultValue:r,onChange:i,size:s,wrapperProps:c,children:u,readOnly:f,...h}=se("SwitchGroup",ez,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(Z6,{value:{value:m,onChange:y,size:s},children:o.jsx(mn.Wrapper,{size:s,ref:t,...c,...h,labelElement:"div",__staticSelector:"SwitchGroup",children:o.jsx(a0,{role:"group",children:u})})})});$0.classes=mn.Wrapper.classes;$0.displayName="@mantine/core/SwitchGroup";var qD={root:"m_5f93f3bb",input:"m_926b4011",track:"m_9307d992",thumb:"m_93039a1d",trackLabel:"m_8277e082"};const tz={labelPosition:"right"},nz=(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}}),Cd=ve((e,t)=>{const n=se("Switch",tz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,color:h,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=J6(),G=S||(J==null?void 0:J.size),Z=Ie({name:"Switch",props:n,classes:qD,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:nz}),{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,{...Z("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:K=>{var ee;J?(ee=H.onChange)==null||ee.call(H,K):R==null||R(K),U(K.currentTarget.checked)},id:z,ref:t,type:"checkbox",role:"switch",...Z("input")}),o.jsxs(ce,{"aria-hidden":"true",component:"span",mod:{error:M,"label-position":A,"without-labels":!y&&!g},...Z("track"),children:[o.jsx(ce,{component:"span",mod:"reduce-motion",...Z("thumb"),children:T}),o.jsx("span",{...Z("trackLabel"),children:O?y:g})]})]})});Cd.classes={...qD,...K2};Cd.displayName="@mantine/core/Switch";Cd.Group=$0;const[rz,iz]=vr("Table component was not found in the tree");var Ed={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 az(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:h,styles:m,...g}=c,y=iz();return o.jsx(ce,{component:e,ref:s,...az(y,t),...y.getStyles(e,{className:f,classNames:u,style:h,styles:m,props:c}),...g})});return r.displayName=`@mantine/core/${n}`,r.classes=Ed,r}const Ny=tl("th",{columnBorder:!0}),GD=tl("td",{columnBorder:!0}),xh=tl("tr",{rowBorder:!0,striped:!0,highlightOnHover:!0}),QD=tl("thead",{stickyHeader:!0}),WD=tl("tbody"),YD=tl("tfoot"),KD=tl("caption",{captionSide:!0});function U0({data:e}){return o.jsxs(o.Fragment,{children:[e.caption&&o.jsx(KD,{children:e.caption}),e.head&&o.jsx(QD,{children:o.jsx(xh,{children:e.head.map((t,n)=>o.jsx(Ny,{children:t},n))})}),e.body&&o.jsx(WD,{children:e.body.map((t,n)=>o.jsx(xh,{children:t.map((r,i)=>o.jsx(GD,{children:r},i))},n))}),e.foot&&o.jsx(YD,{children:o.jsx(xh,{children:e.foot.map((t,n)=>o.jsx(Ny,{children:t},n))})})]})}U0.displayName="@mantine/core/TableDataRenderer";const oz={type:"scrollarea"},sz=(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}}),B0=ve((e,t)=>{const n=se("TableScrollContainer",oz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,children:h,minWidth:m,maxHeight:g,type:y,scrollAreaProps:b,...S}=n,j=Ie({name:"TableScrollContainer",classes:Ed,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:sz,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:h})})});B0.classes=Ed;B0.displayName="@mantine/core/TableScrollContainer";const lz={withRowBorders:!0,verticalSpacing:7},cz=(e,{layout:t,captionSide:n,horizontalSpacing:r,verticalSpacing:i,borderColor:s,stripedColor:c,highlightOnHoverColor:u,striped:f,highlightOnHover:h,stickyHeaderOffset:m,stickyHeader:g})=>({table:{"--table-layout":t,"--table-caption-side":n,"--table-horizontal-spacing":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":h&&u?Ht(u,e):void 0,"--table-sticky-header-offset":g?le(m):void 0}}),ye=ve((e,t)=>{const n=se("Table",lz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,horizontalSpacing:h,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:Ed,classNames:r,styles:c,unstyled:u,rootSelector:"table",vars:f,varsResolver:cz});return o.jsx(rz,{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(U0,{data:k})})})});ye.classes=Ed;ye.displayName="@mantine/core/Table";ye.Td=GD;ye.Th=Ny;ye.Tr=xh;ye.Thead=QD;ye.Tbody=WD;ye.Tfoot=YD;ye.Caption=KD;ye.ScrollContainer=B0;ye.DataRenderer=U0;const[uz,V0]=vr("Tabs component was not found in the tree");var Td={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 dz={},F0=ve((e,t)=>{const n=se("TabsList",dz,e),{children:r,className:i,grow:s,justify:c,classNames:u,styles:f,style:h,mod:m,...g}=n,y=V0();return o.jsx(ce,{...g,...y.getStyles("list",{className:i,style:h,classNames:u,styles:f,props:n,variant:y.variant}),ref:t,role:"tablist",variant:y.variant,mod:[{grow:s,orientation:y.orientation,placement:y.orientation==="vertical"&&y.placement,inverted:y.inverted},m],"aria-orientation":y.orientation,__vars:{"--tabs-justify":c},children:r})});F0.classes=Td;F0.displayName="@mantine/core/TabsList";const fz={},H0=ve((e,t)=>{const n=se("TabsPanel",fz,e),{children:r,className:i,value:s,classNames:c,styles:u,style:f,mod:h,keepMounted:m,...g}=n,y=V0(),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},h],role:"tabpanel",id:y.getPanelId(s),"aria-labelledby":y.getTabId(s),children:S})});H0.classes=Td;H0.displayName="@mantine/core/TabsPanel";const hz={},q0=ve((e,t)=>{const n=se("TabsTab",hz,e),{className:r,children:i,rightSection:s,leftSection:c,value:u,onClick:f,onKeyDown:h,disabled:m,color:g,style:y,classNames:b,styles:S,vars:j,mod:C,tabIndex:T,...D}=n,E=Sn(),{dir:R}=Zs(),A=V0(),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:h}),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})]})});q0.classes=Td;q0.displayName="@mantine/core/TabsTab";const YC="Tabs.Tab or Tabs.Panel component was rendered with invalid value or without value",pz={keepMounted:!0,orientation:"horizontal",loop:!0,activateTabWithKeyboard:!0,allowTabDeactivation:!1,unstyled:!1,inverted:!1,variant:"default",placement:"left"},mz=(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",pz,e),{defaultValue:r,value:i,onChange:s,orientation:c,children:u,loop:f,id:h,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(h),[Q,J]=Yn({value:i,defaultValue:r,finalValue:null,onChange:s}),G=Ie({name:"Tabs",props:n,classes:Td,className:A,style:k,classNames:D,styles:E,unstyled:R,vars:M,varsResolver:mz});return o.jsx(uz,{value:{placement:C,value:Q,orientation:c,id:Y,loop:f,activateTabWithKeyboard:m,getTabId:qj(`${Y}-tab`,YC),getPanelId:qj(`${Y}-panel`,YC),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=Td;Et.displayName="@mantine/core/Tabs";Et.Tab=q0;Et.Panel=H0;Et.List=F0;const gz={},ze=ve((e,t)=>{const n=se("TextInput",gz,e);return o.jsx(Pr,{component:"input",ref:t,...n,__staticSelector:"TextInput"})});ze.classes=Pr.classes;ze.displayName="@mantine/core/TextInput";var XD={root:"m_7341320d"};const vz={},yz=(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}}},G0=ve((e,t)=>{const n=se("ThemeIcon",vz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,autoContrast:h,...m}=n,g=Ie({name:"ThemeIcon",classes:XD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:yz});return o.jsx(ce,{ref:t,...g("root"),...m})});G0.classes=XD;G0.displayName="@mantine/core/ThemeIcon";const xz=["h1","h2","h3","h4","h5","h6"],bz=["xs","sm","md","lg","xl"];function Sz(e,t){const n=t!==void 0?t:`h${e}`;return xz.includes(n)?{fontSize:`var(--mantine-${n}-font-size)`,fontWeight:`var(--mantine-${n}-font-weight)`,lineHeight:`var(--mantine-${n}-line-height)`}:bz.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 ZD={root:"m_8a5d1357"};const wz={order:1},jz=(e,{order:t,size:n,lineClamp:r,textWrap:i})=>{const s=Sz(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",wz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,order:f,vars:h,size:m,variant:g,lineClamp:y,textWrap:b,mod:S,...j}=n,C=Ie({name:"Title",props:n,classes:ZD,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:h,varsResolver:jz});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=ZD;Le.displayName="@mantine/core/Title";function Cz(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 Ez(e){return v.useSyncExternalStore(e.subscribe,()=>e.getState(),()=>e.getState())}function Tz(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 Rz=()=>Cz({notifications:[],queue:[],defaultPosition:"bottom-right",limit:5}),nl=Rz(),Dz=(e=nl)=>Ez(e);function kc(e,t){const n=e.getState(),r=t([...n.notifications,...n.queue]),i=Tz(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||Dh();return kc(t,r=>e.id&&r.some(i=>i.id===e.id)?r:[...r,{...e,id:n}]),n}function JD(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 Az(e=nl){kc(e,()=>[])}function _z(e=nl){kc(e,t=>t.slice(0,e.getState().limit))}const di={show:Oe,hide:JD,update:As,clean:Az,cleanQueue:_z,updateState:kc};function Oy(e,t){return Oy=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},Oy(e,t)}function eA(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,Oy(e,t)}var Fv={exports:{}},Hv,KC;function kz(){if(KC)return Hv;KC=1;var e="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";return Hv=e,Hv}var qv,XC;function Pz(){if(XC)return qv;XC=1;var e=kz();function t(){}function n(){}return n.resetWarningCache=t,qv=function(){function r(c,u,f,h,m,g){if(g!==e){var y=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw y.name="Invariant Violation",y}}r.isRequired=r;function i(){return r}var s={array:r,bigint:r,bool:r,func:r,number:r,object:r,string:r,symbol:r,any:r,arrayOf:i,element:r,elementType:r,instanceOf:i,node:r,objectOf:i,oneOf:i,oneOfType:i,shape:i,exact:i,checkPropTypes:n,resetWarningCache:t};return s.PropTypes=s,s},qv}var ZC;function Nz(){return ZC||(ZC=1,Fv.exports=Pz()()),Fv.exports}var Oz=Nz();const an=lx(Oz),JC={disabled:!1},Ih=En.createContext(null);var Mz=function(t){return t.scrollTop},qu="unmounted",ws="exited",js="entering",ec="entered",My="exiting",Xa=function(e){eA(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=My)}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&&Mz(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],h=f[0],m=f[1],g=this.getTimeouts(),y=u?g.appear:g.enter;if(!i&&!c||JC.disabled){this.safeSetState({status:ec},function(){s.props.onEntered(h)});return}this.props.onEnter(h,m),this.safeSetState({status:js},function(){s.props.onEntering(h,m),s.onTransitionEnd(y,function(){s.safeSetState({status:ec},function(){s.props.onEntered(h,m)})})})},n.performExit=function(){var i=this,s=this.props.exit,c=this.getTimeouts(),u=this.props.nodeRef?void 0:Hu.findDOMNode(this);if(!s||JC.disabled){this.safeSetState({status:ws},function(){i.props.onExited(u)});return}this.props.onExit(u),this.safeSetState({status:My},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],h=f[0],m=f[1];this.props.addEndListener(h,m)}i!=null&&setTimeout(this.nextCallback,i)},n.render=function(){var i=this.state.status;if(i===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=g0(s,["children","in","mountOnEnter","unmountOnExit","appear","enter","exit","timeout","addEndListener","onEnter","onEntering","onEntered","onExit","onExiting","onExited","nodeRef"]);return En.createElement(Ih.Provider,{value:null},typeof c=="function"?c(i,u):En.cloneElement(En.Children.only(c),u))},t}(En.Component);Xa.contextType=Ih;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=My;function Iz(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Q0(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 Lz(e,t){e=e||{},t=t||{};function n(m){return m in t?t[m]:e[m]}var r=Object.create(null),i=[];for(var s in e)s in t?i.length&&(r[s]=i,i=[]):i.push(s);var c,u={};for(var f in t){if(r[f])for(c=0;c<r[f].length;c++){var h=r[f][c];u[r[f][c]]=n(h)}u[f]=n(f)}for(c=0;c<i.length;c++)u[i[c]]=n(i[c]);return u}function _s(e,t,n){return n[t]!=null?n[t]:e.props[t]}function zz(e,t){return Q0(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 $z(e,t,n){var r=Q0(e.children),i=Lz(t,r);return Object.keys(i).forEach(function(s){var c=i[s];if(v.isValidElement(c)){var u=s in t,f=s in r,h=t[s],m=v.isValidElement(h)&&!h.props.in;f&&(!u||m)?i[s]=v.cloneElement(c,{onExited:n.bind(null,c),in:!0,exit:_s(c,"exit",e),enter:_s(c,"enter",e)}):!f&&u&&!m?i[s]=v.cloneElement(c,{in:!1}):f&&u&&v.isValidElement(h)&&(i[s]=v.cloneElement(c,{onExited:n.bind(null,c),in:h.props.in,exit:_s(c,"exit",e),enter:_s(c,"enter",e)}))}}),i}var Uz=Object.values||function(e){return Object.keys(e).map(function(t){return e[t]})},Bz={component:"div",childFactory:function(t){return t}},Oo=function(e){eA(t,e);function t(r,i){var s;s=e.call(this,r,i)||this;var c=s.handleExited.bind(Iz(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?zz(i,u):$z(i,c,u),firstRender:!1}},n.handleExited=function(i,s){var c=Q0(this.props.children);i.key in c||(i.props.onExited&&i.props.onExited(s),this.mounted&&this.setState(function(u){var f=Oh({},u.children);return delete f[i.key],{children:f}}))},n.render=function(){var i=this.props,s=i.component,c=i.childFactory,u=g0(i,["component","childFactory"]),f=this.state.contextValue,h=Uz(this.state.children).map(c);return delete u.appear,delete u.enter,delete u.exit,s===null?En.createElement(Ih.Provider,{value:f},h):En.createElement(Ih.Provider,{value:f},En.createElement(s,u,h))},t}(En.Component);Oo.propTypes={};Oo.defaultProps=Bz;const tA=["bottom-center","bottom-left","bottom-right","top-center","top-left","top-right"];function Vz(e,t){return e.reduce((n,r)=>(n[r.position||t].push(r),n),tA.reduce((n,r)=>(n[r]=[],n),{}))}const eE={left:"translateX(-100%)",right:"translateX(100%)","top-center":"translateY(-100%)","bottom-center":"translateY(100%)"},Fz={left:"translateX(0)",right:"translateX(0)","top-center":"translateY(0)","bottom-center":"translateY(0)"};function Hz({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:eE[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:Fz[c]},h={opacity:0,maxHeight:0,transform:eE[c]};return{...u,...{entering:f,entered:f,exiting:h,exited:h}[e]}}function qz(e,t){return typeof t=="number"?t:t===!1||e===!1?!1:e}const nA=v.forwardRef(({data:e,onHide:t,autoClose:n,...r},i)=>{const{autoClose:s,message:c,...u}=e,f=qz(n,e.autoClose),h=v.useRef(-1),m=()=>window.clearTimeout(h.current),g=()=>{t(e.id),m()},y=()=>{typeof f=="number"&&(h.current=window.setTimeout(g,f))};return v.useEffect(()=>{var b;(b=e.onOpen)==null||b.call(e,e)},[]),v.useEffect(()=>(y(),m),[f]),o.jsx(D0,{...r,...u,onClose:g,ref:i,onMouseEnter:m,onMouseLeave:y,children:c})});nA.displayName="@mantine/notifications/NotificationContainer";var rA={root:"m_b37d9ac7",notification:"m_5ed0edd0"};const Gz=Xa,Qz={position:"bottom-right",autoClose:4e3,transitionDuration:250,containerWidth:440,notificationMaxHeight:200,limit:5,zIndex:Wr("overlay"),store:nl,withinPortal:!0},Wz=(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",Qz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,position:h,autoClose:m,transitionDuration:g,containerWidth:y,notificationMaxHeight:b,limit:S,zIndex:j,store:C,portalProps:T,withinPortal:D,...E}=n,R=Sn(),A=Dz(C),k=bN(),M=hx(),I=v.useRef({}),$=v.useRef(0),Y=(R.respectReducedMotion?M:!1)?1:g,Q=Ie({name:"Notifications",classes:rA,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:Wz});v.useEffect(()=>{C==null||C.updateState(Z=>({...Z,limit:S||5,defaultPosition:h}))},[S,h]),za(()=>{A.notifications.length>$.current&&setTimeout(()=>k(),0),$.current=A.notifications.length},[A.notifications]);const J=Vz(A.notifications,h),G=tA.reduce((Z,P)=>(Z[P]=J[P].map(({style:L,...z})=>o.jsx(Gz,{timeout:Y,onEnter:()=>I.current[z.id].offsetHeight,nodeRef:{current:I.current[z.id]},children:H=>o.jsx(nA,{ref:O=>{I.current[z.id]=O},data:z,onHide:O=>JD(O,C),autoClose:m,...Q("notification",{style:{...Hz({state:H,position:P,transitionDuration:Y,maxHeight:b}),...L}})})},z.id)),Z),{});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=rA;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 Yz{constructor(t,n){this.operator=t,this.child=n}toString(){return`${this.operator}(${this.child.toString()})`}}class Rd{constructor(t,n,r){this.operator=t,this.left=n,this.right=r}toString(){return`(${this.left.toString()} ${this.operator} ${this.right.toString()})`}}class Kz{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 Xz(t,this.prefixParselets,this.infixParselets)}}class Xz{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 iA{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 Dd="http://hl7.org",aA="ok",Zz="created",Jz="gone",e$="not-modified",t$="not-found",n$="unauthorized",r$="forbidden",i$="accepted",a$={resourceType:"OperationOutcome",id:aA,issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},o$={resourceType:"OperationOutcome",id:t$,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},id={resourceType:"OperationOutcome",id:n$,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},s$={...id,issue:[...id.issue,{severity:"error",code:"expired",details:{text:"Token expired"}}]},tE={...id,issue:[...id.issue,{severity:"error",code:"invalid",details:{text:"Token not issued for this audience"}}]},W0={resourceType:"OperationOutcome",id:r$,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 l$(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"exception",details:{text:"Internal server error"},diagnostics:e.toString()}]}}function c$(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 oA(e){return e.id===aA||e.id===Zz||e.id===e$||e.id===i$}function u$(e){return e.id===Jz}class dt extends Error{constructor(t,n){super(sA(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:c$(e)?e.message:qp(e)?sA(e):typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:JSON.stringify(e):"Unknown error"}function sA(e){var n;const t=((n=e.issue)==null?void 0:n.map(lA))??[];return t.length>0?t.join("; "):"Unknown error"}function lA(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 d$(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 f$(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,d$(i,s)])),constraints:[],innerTypes:[]};return t}const h$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]}}},p$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]}}},m$={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"}]}}},g$={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"}]}}},v$={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"}]}}},y$={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"}]}}},x$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},coding:{max:9007199254740991,type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},b$={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"}]}}},S$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:9007199254740991,type:[{code:"ContactPoint"}]}}},w$={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"}]}}},j$={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"}]}}},C$={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"}]}}},E$={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"}]}}},T$={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"}]}}},R$={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"}]}}},D$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},A$={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"}]}}},_$={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"]}]}}},k$={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"]}]}}},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"}]}}},N$={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"}]}}},O$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},M$={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"}]}}},I$={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"}]}}},L$={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"}]}}},z$={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"}]}}},$$={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"]}]}}},U$={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"]}]}}},B$={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"}]}}},V$={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"}]}}},F$={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"}]}}},H$={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"}]}}},q$={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"]}]}}},G$={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"}]}}},Q$={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"}]}}},W$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},Y$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},K$={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"]}]}}},X$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},Z$={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"}]}}},J$={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"}]}}},e8={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"}]}}},t8={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"}]}}},n8={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"]}]}}},r8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},i8={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"}]}}},a8={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"]}]}}},o8={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"}]}}},s8={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"}]}}},l8={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"}]}}},c8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]},highLimit:{type:[{code:"Quantity"}]}}},u8={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"}]}}},d8={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"}]}}},f8={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"}]}}},h8={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"]}]}}},p8={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"}]}}},m8={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"}]}}},g8={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"}]}}},v8={Element:h$,BackboneElement:p$,Address:m$,Age:g$,Annotation:v$,Attachment:y$,CodeableConcept:x$,Coding:b$,ContactDetail:S$,ContactPoint:w$,Contributor:j$,Count:C$,DataRequirement:E$,DataRequirementCodeFilter:T$,DataRequirementDateFilter:R$,DataRequirementSort:D$,Distance:A$,Dosage:_$,DosageDoseAndRate:k$,Duration:P$,ElementDefinition:N$,ElementDefinitionSlicingDiscriminator:O$,ElementDefinitionSlicing:M$,ElementDefinitionBase:I$,ElementDefinitionType:L$,ElementDefinitionExample:z$,ElementDefinitionConstraint:$$,ElementDefinitionBinding:U$,ElementDefinitionMapping:B$,Expression:V$,Extension:F$,HumanName:H$,Identifier:q$,MarketingStatus:G$,Meta:Q$,Money:W$,Narrative:Y$,ParameterDefinition:K$,Period:X$,Population:Z$,ProdCharacteristic:J$,ProductShelfLife:e8,Quantity:t8,Range:n8,Ratio:r8,Reference:i8,RelatedArtifact:a8,SampledData:o8,Signature:s8,SubstanceAmount:l8,SubstanceAmountReferenceRange:c8,Timing:u8,TimingRepeat:d8,TriggerDefinition:f8,UsageContext:h8,MoneyQuantity:p8,SimpleQuantity:m8,IdentityProvider:g8};function y8(e){return new b8(e).parse()}const Lh=f$(v8),Y0=Object.create(null),nE=Object.create(null),x8={"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 cA(e){let t;return t=nE[e],t||(t=nE[e]=Object.create(null)),t}function rE(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");dU(n);for(const i of n)uA(i)}function uA(e){var s,c;if(!(e!=null&&e.name))throw new Error("Failed loading StructureDefinition from bundle");if(e.resourceType!=="StructureDefinition")return;const t=y8(e),n=x8[e.url];let r,i;n?(r=Lh,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=Lh,i=e.type):(r=cA(e.url),i=e.type),r[i]=t;for(const u of t.innerTypes)u.parentType=t,r[u.name]=u;Y0[e.url]=t}function dA(e){return!!Lh[e]}function Gp(e,t){if(t){const n=cA(t)[e];if(n)return n}return Lh[e]}function fA(e,t){const n=Gp(e,t);if(!n)throw new dt(ra("Unknown data type: "+e));return n}function K0(e){return!!Y0[e]}function Pc(e){return Y0[e]}class b8{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:j8(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=Gv(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[Gv(t,f.path)]=u;break}f=f.parent}if(!f){const h=Gv(t,this.root.path);t.isSummary&&((s=this.resourceSchema.summaryProperties)==null||s.add(h.replace("[x]",""))),u.min>0&&((c=this.resourceSchema.mandatoryProperties)==null||c.add(h.replace("[x]",""))),this.resourceSchema.elements[h]=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=fE(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;w8(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=fE(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=iE(t.max),r=(s=t.base)!=null&&s.max?iE(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:aE(gc(i,"fixed[x]")),pattern:aE(gc(i,"pattern[x]")),binding:t.binding}}}function iE(e){return e==="*"?Number.POSITIVE_INFINITY:Number.parseInt(e,10)}function Gv(e,t=""){return S8(e.path,t)}function S8(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 aE(e){return Array.isArray(e)&&e.length>0?e[0]:Rn(e)?void 0:e}function w8(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 j8(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 C8(e,t,n){if(e===void 0)return[void 0];if(t==="$this")return[e];const r=n!=null&&n.withPath?E8:gc,[i,...s]=t.split(".");let c=[r(e,i,n)];for(const u of s){const f=[];for(const h of c)if(Array.isArray(h))for(const m of h)f.push(r(m,u,n));else(n!=null&&n.withPath&&h&&h.value!==void 0||!(n!=null&&n.withPath)&&h!==void 0)&&f.push(r(h,u,n));c=f}return c}function E8(e,t,n){const r=e.path;return T8(gc(e,t,n),r,t)}function T8(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 hA={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 R8(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 J0(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}:jA(e)?{type:oe.CodeableConcept,value:e}:wA(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?pA(e,t,r):Ad(e,t)}function pA(e,t,n){const r=e.value,i=n.type;if(!i||i.length===0)return;let s,c="undefined",u;const f=n.path.lastIndexOf("."),h=n.path.substring(f+1);for(const m of i){const g=h.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]=cE(s[m],u[m])}else s=cE(s,u);if(!Rn(s))return(c==="Element"||c==="BackboneElement")&&(c=n.type[0].code),Array.isArray(s)?s.map(m=>oE(m,c)):oE(s,c)}function oE(e,t){return t==="Resource"&&fa(e)&&(t=e.resourceType),{type:t,value:e}}function Ad(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 mA(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 D8(e){return We(!ea(e))}function A8(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 _8(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(xA(n,r)):We(typeof n=="object"&&typeof r=="object"?X0(e,t):n===r)}function gA(e,t){return e.length===0&&t.length===0?We(!0):e.length!==t.length?We(!1):(e.sort(sE),t.sort(sE),We(e.every((n,r)=>ea(k8(n,t[r])))))}function k8(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(xA(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"?X0({...c,id:void 0},{...u,id:void 0}):typeof c=="string"&&typeof u=="string"?c.toLowerCase()===u.toLowerCase():c===u)}function sE(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 vA(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 P8(n);case"DateTime":return zh(n);case"Time":return typeof n=="string"&&!!/^T\d/.exec(n);case"Period":return yA(n);case"Quantity":return fi(n);default:return e.type===r||typeof n=="object"&&(n==null?void 0:n.resourceType)===r}}function P8(e){return typeof e=="string"&&!!hA.date.exec(e)}function zh(e){return typeof e=="string"&&!!hA.dateTime.exec(e)}function yA(e){return!!(e&&typeof e=="object"&&("start"in e&&zh(e.start)||"end"in e&&zh(e.end)))}function fi(e){return!!(e&&typeof e=="object"&&"value"in e&&typeof e.value=="number")}function xA(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 X0(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(lE(s)&&lE(c)){if(!X0(s,c))return!1}else if(s!==c)return!1}return!0}function lE(e){return e!==null&&typeof e=="object"}function cE(e,t){if(t){if(typeof t!="object")throw new Error("Primitive extension must be an object");return N8(e??{},t)}return e}function N8(e,t){return delete t.__proto__,delete t.constructor,Object.assign(e,t)}function O8(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(O8(e))return`${e.resourceType}/${e.id}`}function Bs(e){if(e)return Ko(e)?e.reference.split("/")[1]:e.id}function M8(e){return e.resourceType==="Patient"||e.resourceType==="Practitioner"||e.resourceType==="RelatedPerson"}function Va(e){if(M8(e)){const t=I8(e);if(t)return t}if(e.resourceType==="Device"){const t=L8(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]),jA(t))return Fo(t);if(Q8(t))return t.text}return zt(e)??""}function I8(e){const t=e.name;if(t&&t.length>0)return Nc(t[0])}function L8(e){const t=e.deviceName;if(t&&t.length>0)return t[0].name}function z8(e){if(!("photo"in e))return;const t=e.photo;if(t)if(Array.isArray(t))for(const n of t){const r=uE(n);if(r)return r}else return uE(t)}function uE(e){var t;if(e.url&&((t=e.contentType)!=null&&t.startsWith("image/")))return e.url}function bA(e,t){const n=new Date(e);n.setUTCHours(0,0,0,0);const r=t?new Date(t):new Date;r.setUTCHours(0,0,0,0);const i=n.getUTCFullYear(),s=n.getUTCMonth(),c=n.getUTCDate(),u=r.getUTCFullYear(),f=r.getUTCMonth(),h=r.getUTCDate();let m=u-i;(f<s||f===s&&h<c)&&m--;let g=u*12+f-(i*12+s);h<c&&g--;const y=Math.floor((r.getTime()-n.getTime())/(1e3*60*60*24));return{years:m,months:g,days:y}}function $8(e,t){const{years:n,months:r,days:i}=bA(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=Z0(e);return JSON.stringify(n,null,t?2:void 0)??""}function Z0(e){if(!(e==null||e===""))return typeof e=="object"?Array.isArray(e)?U8(e):B8(e):e}function U8(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=Z0(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 B8(e){let t,n=0;for(const r in e){const i=e[r],s=Z0(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)?V8(e,t):Array.isArray(e)||Array.isArray(t)?!1:sr(e)&&sr(t)?F8(e,t,n):(sr(e)||sr(t),!1)}function V8(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 F8(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 J0(e,t){return Rn(e)?!0:Rn(t)?!1:Array.isArray(e)&&Array.isArray(t)?H8(e,t):Array.isArray(e)||Array.isArray(t)?!1:sr(e)&&sr(t)?q8(e,t):sr(e)||sr(t)?!1:e===t}function H8(e,t){return t.every(n=>e.some(r=>J0(r,n)))}function q8(e,t){return Object.entries(t).every(([n,r])=>n in e&&J0(e[n],r))}function Qr(e){return e===void 0?e:JSON.parse(JSON.stringify(e))}function SA(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 G8(e){return typeof e=="string"}function wA(e){return sr(e)&&"code"in e&&typeof e.code=="string"}function jA(e){return sr(e)&&"coding"in e&&Array.isArray(e.coding)&&e.coding.every(wA)}function Q8(e){return sr(e)&&"text"in e&&typeof e.text=="string"}const CA=[];for(let e=0;e<256;e++)CA.push(e.toString(16).padStart(2,"0"));function W8(e){const t=EA(e),n=new Uint8Array(t),r=new Array(n.length);for(let i=0;i<n.length;i++)r[i]=CA[n[i]];return r.join("")}function Y8(e){const t=EA(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 EA(e){return ArrayBuffer.isView(e)?e.buffer:e}function Hn(e){return e?e.charAt(0).toUpperCase()+e.substring(1):""}function eb(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 K8(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 X8(e){if(e!==void 0)return Array.isArray(e)?e:[e]}const dE=e=>new Promise(t=>{setTimeout(t,e)});function Iy(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 Z8(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 tb(e){return e.endsWith("/")?e:e+"/"}function J8(e){return e.startsWith("/")?e.slice(1):e}function Xi(e,t){return new URL(J8(t),tb(e.toString())).toString()}function eU(e,t){return Xi(e,t).toString().replace("http://","ws://").replace("https://","wss://")}function tU(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 TA(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 nU(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 RA(e.value);case"CodeableConcept":return Fo(e.value);case"Coding":return _d(e.value);case"ContactPoint":return e.value.value;case"HumanName":return Nc(e.value);case"Quantity":return Ps(e.value);case"Reference":return rU(e.value);default:return e.value.toString()}}function rU(e){return e?e.display??e.reference??Ii(e):""}function RA(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 iU(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 aU(e,t,n){return!e||!e.start&&!e.end?"":gr(e.start,t,n)+" - "+gr(e.end,t,n)}const oU={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},sU={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},lU={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function DA(e){if(!e)return"";const t=[];return cU(t,e.repeat),e.event&&t.push(e.event.map(n=>gr(n)).join(", ")),Hn(t.join(" ").trim())}function cU(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(oU[i]):(n===1?e.push("once"):e.push(n+" times"),r===1?e.push("per "+sU[i]):e.push("per "+r+" "+lU[i])),t.dayOfWeek&&e.push("on "+t.dayOfWeek.map(Hn).join(", ")),t.timeOfDay&&e.push("at "+t.timeOfDay.map(s=>iU(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 uU(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=>_d(n)).join(", "):"")}function _d(e,t){const n=sd(e==null?void 0:e.display);return n?`${n}`:sd(e==null?void 0:e.code)??""}function AA(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=>AA(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 dU(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"&&_A(r.type)}function _A(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 fU(e){for(const t of e.base??[]){const n=_A(t);n.searchParams||(n.searchParams={}),n.searchParams[e.code]=e}}function fE(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"?hU((s=((i=e.base)==null?void 0:i.path)??e.path)==null?void 0:s.split(".")):t}function hU(e){return e.length===1?e[0]:e.map(Hn).join("")}function nb(e){var t;return(t=la.types[e])==null?void 0:t.searchParams}function pU(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 kA(t)}function kA(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(gU).join(" ").replace("_"," ").replace(/\s+/g," ")}const mU=new Set(["ID","IP","PKCE","JWKS","URI","URL","OMB","UDI"]);function gU(e){const t=e.toUpperCase();return e===t?e:mU.has(t)?t:t.charAt(0)+e.slice(1)}function Yo(e,t,n){const r=Gp(e,n);if(r)return vU(r.elements,t)}function vU(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 bh(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 mA([...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:bh(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:bh(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:bh("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 h;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=(h=i.eval(e,t)[0])==null?void 0:h.value;if(u!=="years"&&u!=="months"&&u!=="days")throw new Error("Invalid units");const f=bA(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 ld?r=n.name:n instanceof Yp&&(r=n.left.name+"."+n.right.name),r?t.map(i=>({type:oe.boolean,value:vA(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 ld&&(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,h=s?{...i,value:u}:u;return[{type:f,value:h}]}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 rb{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 ld{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 yU{eval(){return[]}toString(){return"{}"}}class xU extends Yz{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 Rd{constructor(t,n){super("as",t,n)}eval(t,n){return Tr.ofType(t,this.left.eval(t,n),this.right)}}class Nr extends Rd{}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,h=this.impl(u,f);return typeof h=="boolean"?We(h):fi(s)?[{type:oe.Quantity,value:{...s,value:h}}]:[mi(h)]}}class bU extends Rd{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 SU 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 wU 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 Yp extends Rd{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 ib extends Rd{constructor(t,n){super("|",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return mA([...r,...i])}}class jU 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 A8(r,i)}}class CU 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 _8(r,i)}}class EU 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 gA(r,i)}}class TU 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 D8(gA(r,i))}}class ab 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(vA(r[0],i))}}class RU 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 DU 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 AU 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 _U 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 ob{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 sb{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 kU=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"];class PU{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()!==`
|
|
76
|
+
`),s=!1),Object.assign(Object.assign({},e),{allowNegative:s})}function BL(e){e=UL(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,h=e.prefix;h===void 0&&(h="");var m=e.defaultValue,g=e.value,y=e.valueIsNumericString,b=e.onValueChange,S=wD(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 qC(P,e)},E=function(P,L){return zL(P,L,e)},R=ic(g)?m:g,A=y??LL(R,h,t);ic(g)?ic(m)||(A=A||typeof m=="number"):A=A||typeof g=="number";var k=function(P){return jD(P)?P:(typeof P=="number"&&(P=TD(P)),A&&typeof u=="number"?FC(P,u,!!f):P)},M=DD(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<h.length){P.preventDefault();return}if(H!==O){i(P);return}z==="Backspace"&&U[0]==="-"&&H===h.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 K=c===!0?",":c;z==="Backspace"&&U[H-1]===K&&Es(L,H-1),z==="Delete"&&U[H]===K&&Es(L,H+1),i(P)},J=function(P){var L=$;if(L.match(/\d/g)||(L=""),r||(L=CL(L)),f&&u&&(L=FC(L,u,f)),L!==$){var z=qC(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)},Z=function(P){var L=P.currentValue,z=P.lastValue,H=P.formattedValue,O=P.currentValueIndex,U=P.formattedValueIndex,K=L[O],ee=H[U],Se=RD(z,L),be=Se.to,xe=function(qe){return E(qe).indexOf(".")+h.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(K)&&ee===C?!0:K===ee};return Object.assign(Object.assign({},S),{value:V,valueIsNumericString:!1,isValidInputCharacter:G,isCharacterSame:Z,onValueChange:Y,format:D,removeFormatting:E,getCaretBoundary:function(P){return $L(P,e)},onKeyDown:Q,onBlur:J})}function VL(e){var t=BL(e);return En.createElement(OL,Object.assign({},t))}function GC({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 _y={root:"m_e2f5cd4e",controls:"m_95e17d22",control:"m_80b4b171"};const FL=/^(0\.0*|-0(\.0*)?)$/,HL=/^-?0\d+(\.\d+)?\.?$/;function ky(e){return typeof e=="string"&&e!==""&&!Number.isNaN(Number(e))}function Bv(e){return typeof e=="number"?e<Number.MAX_SAFE_INTEGER:e===""||ky(e)&&Number(e)<Number.MAX_SAFE_INTEGER}function qL(e){return e.toString().replace(".","").length}function GL(e,t){return(typeof e=="number"?e<Number.MAX_SAFE_INTEGER:!Number.isNaN(Number(e)))&&!Number.isNaN(e)&&qL(t)<14&&t!==""}function QC(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 QL={step:1,clampBehavior:"blur",allowDecimal:!0,allowNegative:!0,withKeyboardEvents:!0,allowLeadingZeros:!0,trimLeadingZeroesOnBlur:!0,startValue:0},WL=(e,{size:t})=>({controls:{"--ni-chevron-size":rt(t,"ni-chevron-size")}});function YL(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:gh(i,n,t)}const Ip=ve((e,t)=>{const n=se("NumberInput",QL,e),{className:r,classNames:i,styles:s,unstyled:c,vars:u,onChange:f,onValueChange:h,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:Z,stepHoldInterval:P,stepHoldDelay:L,allowLeadingZeros:z,withKeyboardEvents:H,trimLeadingZeroesOnBlur:O,...U}=n,K=Ie({name:"NumberInput",classes:_y,props:n,classNames:i,styles:s,unstyled:c,vars:u,varsResolver:WL}),{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(GL(we.floatValue,we.value)&&!FL.test(we.value)&&!(z&&HL.test(we.value))?we.floatValue:we.value),h==null||h(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(Rh);gt.current=()=>{if(!Bv(be))return;let we;const $e=It(be),yt=It(S),ft=Math.max($e,yt),Gt=10**ft;if(!ky(be)&&(typeof be!="number"||Number.isNaN(be)))we=gh($,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)),h==null||h({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(Rh);At.current=()=>{if(!Bv(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(!ky(be)&&typeof be!="number"||Number.isNaN(be))we=gh($,$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)),h==null||h({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=gh($e,b,y)),O&&typeof $e=="string"&&It($e)<15&&($e=YL($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",{...K("controls"),children:[o.jsx(tr,{...K("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(GC,{direction:"up"})}),o.jsx(tr,{...K("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(GC,{direction:"down"})})]});return o.jsx(Pr,{component:VL,allowNegative:Q,className:Ut(_y.root,r),size:G,...U,readOnly:J,disabled:V,value:be,getInputRef:zn(t,Me),onValueChange:vt,rightSection:j||J||!Bv(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:Z??`var(--ni-right-section-width-${G||"sm"})`,allowLeadingZeros:z,onBlur:De,isAllowed:we=>D==="strict"?T?T(we)&&QC(we.floatValue,b,y):QC(we.floatValue,b,y):T?T(we):!0})});Ip.classes={...Pr.classes,..._y};Ip.displayName="@mantine/core/NumberInput";const[KL,Lp]=vr("Pagination.Root component was not found in tree");var Sd={root:"m_4addd315",control:"m_326d024a",dots:"m_4ad7767d"};const XL={withPadding:!0},wd=ve((e,t)=>{const n=se("PaginationControl",XL,e),{classNames:r,className:i,style:s,styles:c,vars:u,active:f,disabled:h,withPadding:m,mod:g,...y}=n,b=Lp(),S=h||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})});wd.classes=Sd;wd.displayName="@mantine/core/PaginationControl";function jd({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 ZL=e=>o.jsx(jd,{...e,path:"M8.781 8l-3.3-3.3.943-.943L10.667 8l-4.243 4.243-.943-.943 3.3-3.3z"}),JL=e=>o.jsx(jd,{...e,path:"M7.219 8l3.3 3.3-.943.943L5.333 8l4.243-4.243.943.943-3.3 3.3z"}),e6=e=>o.jsx(jd,{...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"}),t6=e=>o.jsx(jd,{...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"}),n6=e=>o.jsx(jd,{...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"}),r6={icon:n6},zp=ve((e,t)=>{const n=se("PaginationDots",r6,e),{classNames:r,className:i,style:s,styles:c,vars:u,icon:f,...h}=n,m=Lp(),g=f;return o.jsx(ce,{ref:t,...m.getStyles("dots",{className:i,style:s,styles:c,classNames:r}),...h,children:o.jsx(g,{style:{width:"calc(var(--pagination-control-size) / 1.8)",height:"calc(var(--pagination-control-size) / 1.8)"}})})});zp.classes=Sd;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,...h}=se(t,i,c),m=f,g=Lp(),y=r==="next"?g.active===g.total:g.active===1;return o.jsx(wd,{disabled:g.disabled||y,ref:u,onClick:g[n],withPadding:!1,...h,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 AD=$p({icon:ZL,name:"PaginationNext",action:"onNext",type:"next"}),_D=$p({icon:JL,name:"PaginationPrevious",action:"onPrevious",type:"previous"}),kD=$p({icon:e6,name:"PaginationFirst",action:"onFirst",type:"previous"}),PD=$p({icon:t6,name:"PaginationLast",action:"onLast",type:"next"});function _0({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(wd,{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})}_0.displayName="@mantine/core/PaginationItems";const i6={siblings:1,boundaries:1},a6=(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",i6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,total:h,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:Sd,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:a6}),{range:V,setPage:Y,next:Q,previous:J,active:G,first:Z,last:P}=CN({page:m,initialPage:g,onChange:y,total:h,siblings:S,boundaries:j}),L=Rr(D,Q),z=Rr(E,J),H=Rr(R,Z),O=Rr(A,P);return o.jsx(KL,{value:{total:h,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=Sd;Up.displayName="@mantine/core/PaginationRoot";const o6={withControls:!0,withPages:!0,siblings:1,boundaries:1,gap:8},$i=ve((e,t)=>{const n=se("Pagination",o6,e),{withEdges:r,withControls:i,getControlProps:s,nextIcon:c,previousIcon:u,lastIcon:f,firstIcon:h,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(Ce,{gap:y,children:[r&&o.jsx(kD,{icon:h,...s==null?void 0:s("first")}),i&&o.jsx(_D,{icon:u,...s==null?void 0:s("previous")}),S&&o.jsx(_0,{dotsIcon:m}),i&&o.jsx(AD,{icon:c,...s==null?void 0:s("next")}),r&&o.jsx(PD,{icon:f,...s==null?void 0:s("last")})]})})});$i.classes=Sd;$i.displayName="@mantine/core/Pagination";$i.Root=Up;$i.Control=wd;$i.Dots=zp;$i.First=kD;$i.Last=PD;$i.Next=AD;$i.Previous=_D;$i.Items=_0;const s6=({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 Py={root:"m_f61ca620",input:"m_ccf8da4c",innerInput:"m_f2d85dd2",visibilityToggle:"m_b1072d44"};const l6={visibilityToggleIcon:s6},c6=(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",l6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,required:h,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:Z,onVisibilityChange:P,visibilityToggleIcon:L,visibilityToggleButtonProps:z,rightSectionProps:H,leftSectionProps:O,leftSectionPointerEvents:U,withErrorStyles:K,mod:ee,...Se}=n,be=yr(b),[xe,qe]=Yn({value:G,defaultValue:Z,finalValue:!1,onChange:P}),Me=()=>qe(!xe),tt=Ie({name:"PasswordInput",classes:Py,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:c6}),{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:h,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(Py.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:K,children:o.jsx("input",{required:h,"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,...Py};Ni.displayName="@mantine/core/PasswordInput";const[u6,ND]=Ha(),[d6,f6]=Ha();var OD={card:"m_9dc8ae12"};const h6={withBorder:!0},p6=(e,{radius:t})=>({card:{"--card-radius":Vt(t)}}),k0=ve((e,t)=>{const n=se("RadioCard",h6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,checked:h,mod:m,withBorder:g,value:y,onClick:b,name:S,onKeyDown:j,...C}=n,T=Ie({name:"RadioCard",classes:OD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:p6,rootSelector:"card"}),{dir:D}=Zs(),E=ND(),R=typeof h=="boolean"?h:(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(d6,{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})})});k0.displayName="@mantine/core/RadioCard";k0.classes=OD;const m6={},P0=ve((e,t)=>{const{value:n,defaultValue:r,onChange:i,size:s,wrapperProps:c,children:u,name:f,readOnly:h,...m}=se("RadioGroup",m6,e),g=yr(f),[y,b]=Yn({value:n,defaultValue:r,finalValue:"",onChange:i}),S=j=>!h&&b(typeof j=="string"?j:j.currentTarget.value);return o.jsx(u6,{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(a0,{role:"radiogroup",children:u})})})});P0.classes=mn.Wrapper.classes;P0.displayName="@mantine/core/RadioGroup";function MD({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 ID={indicator:"m_717d7ff6",icon:"m_3e4da632","indicator--outline":"m_2980836c"};const g6={icon:MD},v6=(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}}},N0=ve((e,t)=>{const n=se("RadioIndicator",g6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,icon:h,radius:m,color:g,iconColor:y,autoContrast:b,checked:S,mod:j,variant:C,disabled:T,...D}=n,E=h,R=Ie({name:"RadioIndicator",classes:ID,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:v6,rootSelector:"indicator"}),A=f6(),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")})})});N0.displayName="@mantine/core/RadioIndicator";N0.classes=ID;var LD={root:"m_f3f1af94",inner:"m_89c4f5e4",icon:"m_f3ed6b2b",radio:"m_8a3dbb89","radio--outline":"m_1bfe9d39"};const y6={labelPosition:"right"},x6=(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",y6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,id:h,size:m,label:g,labelPosition:y,description:b,error:S,radius:j,color:C,variant:T,disabled:D,wrapperProps:E,icon:R=MD,rootRef:A,iconColor:k,onChange:M,mod:I,...$}=n,V=Ie({name:"Radio",classes:LD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:x6}),Y=ND(),Q=(Y==null?void 0:Y.size)??m,J=n.size?m:Q,{styleProps:G,rest:Z}=Qa($),P=yr(h),L=Y?{checked:Y.value===Z.value,name:Z.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,...Z,...L,component:"input",mod:{error:!!S},ref:t,id:P,disabled:D,type:"radio"}),o.jsx(R,{...V("icon"),"aria-hidden":!0})]})})});Us.classes=LD;Us.displayName="@mantine/core/Radio";Us.Group=P0;Us.Card=k0;Us.Indicator=N0;const b6={duration:100,transition:"fade"};function S6(e,t){return{...b6,...t,...e}}function w6({offset:e,position:t,defaultOpened:n}){const[r,i]=v.useState(n),s=v.useRef(null),{x:c,y:u,elements:f,refs:h,update:m,placement:g}=Px({placement:t,middleware:[Dx({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})=>{h.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(h.floating.current){const j=s.current;j.addEventListener("mousemove",S);const C=Ia(h.floating.current);return C.forEach(T=>{T.addEventListener("scroll",m)}),()=>{j.removeEventListener("mousemove",S),C.forEach(T=>{T.removeEventListener("scroll",m)})}}},[f.reference,h.floating.current,m,S,r]),{handleMouseMove:S,x:c,y:u,opened:r,setOpened:i,boundaryRef:s,floating:h.setFloating}}var Bp={tooltip:"m_1b3c8819",arrow:"m_f898399f"};const j6={refProp:"ref",withinPortal:!0,offset:10,defaultOpened:!1,position:"right",zIndex:Wr("popover")},C6=(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}}),O0=ve((e,t)=>{const n=se("TooltipFloating",j6,e),{children:r,refProp:i,withinPortal:s,style:c,className:u,classNames:f,styles:h,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:h,unstyled:m,rootSelector:"tooltip",vars:A,varsResolver:C6}),{handleMouseMove:V,x:Y,y:Q,opened:J,boundaryRef:G,floating:Z,setOpened:P}=w6({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=zn(G,sp(r),t),z=r.props,H=U=>{var K;(K=z.onMouseEnter)==null||K.call(z,U),V(U),P(!0)},O=U=>{var K;(K=z.onMouseLeave)==null||K.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:Z,mod:{multiline:C},children:b})}),v.cloneElement(r,{...z,[i]:L,onMouseEnter:H,onMouseLeave:O})]})});O0.classes=Bp;O0.displayName="@mantine/core/TooltipFloating";const zD=v.createContext(!1),E6=zD.Provider,T6=()=>v.useContext(zD),R6={openDelay:0,closeDelay:0};function M0(e){const{openDelay:t,closeDelay:n,children:r}=se("TooltipGroup",R6,e);return o.jsx(E6,{value:!0,children:o.jsx(n9,{delay:{open:t,close:n},children:r})})}M0.displayName="@mantine/core/TooltipGroup";M0.extend=e=>e;function D6(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 A6(e){const t=D6(e.middlewares),n=[QR(e.offset)];return t.shift&&n.push(Dx(typeof t.shift=="boolean"?{padding:8}:{padding:8,...t.shift})),t.flip&&n.push(typeof t.flip=="boolean"?Nh():Nh(t.flip)),n.push(WR({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 _6(e){var k,M,I;const[t,n]=v.useState(e.defaultOpened),i=typeof e.opened=="boolean"?e.opened:t,s=T6(),c=yr(),u=v.useCallback($=>{n($),$&&D(c)},[c]),{x:f,y:h,context:m,refs:g,update:y,placement:b,middlewareData:{arrow:{x:S,y:j}={}}}=Px({strategy:e.strategy,placement:e.position,open:i,onOpenChange:u,middleware:A6(e)}),{delay:C,currentId:T,setCurrentId:D}=r9(m,{id:c}),{getReferenceProps:E,getFloatingProps:R}=u9([e9(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)}),c9(m,{enabled:(I=e.events)==null?void 0:I.focus,visibleOnly:!0}),f9(m,{role:"tooltip"}),s9(m,{enabled:typeof e.opened>"u"})]);b2({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:h,arrowX:S,arrowY:j,reference:g.setReference,floating:g.setFloating,getFloatingProps:R,getReferenceProps:E,isGroupPhase:A,opened:i,placement:b}}const WC={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}},k6=(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",WC,e),{children:r,position:i,refProp:s,label:c,openDelay:u,closeDelay:f,onPositionChange:h,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:Z,onClick:P,onMouseEnter:L,onMouseLeave:z,inline:H,variant:O,keepMounted:U,vars:K,portalProps:ee,mod:Se,floatingStrategy:be,middlewares:xe,...qe}=se("Tooltip",WC,n),{dir:Me}=Zs(),tt=v.useRef(null),ke=_6({position:h2(Me,i),closeDelay:f,openDelay:u,onPositionChange:h,opened:m,defaultOpened:g,events:Q,arrowRef:tt,arrowOffset:k,offset:typeof $=="number"?$+(R?A/2:0):$,positionDependencies:[...Z,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:K,varsResolver:k6});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=zn(ke.reference,sp(r),t),Lt=S6(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(Ix,{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=O0;el.Group=M0;function P6({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 $D({size:e,value:t,offset:n,sum:r,thickness:i,root:s,color:c,lineRoundCaps:u,tooltip:f,getStyles:h,display:m,...g}){const y=Sn();return o.jsx(el.Floating,{disabled:!f,label:f,children:o.jsx(ce,{component:"circle",...g,...h("curve"),__vars:{"--curve-color":c?Ht(c,y):void 0},fill:"none",strokeLinecap:u?"round":"butt",...P6({sum:r,size:e,thickness:i,value:t,offset:n,root:s})})})}$D.displayName="@mantine/core/Curve";function N6({size:e,thickness:t,sections:n,renderRoundedLineCaps:r,rootColor:i}){const s=n.reduce((m,g)=>m+g.value,0),c=Math.PI*((e*.9-t*2)/2)*2;let u=c;const f=[],h=[];for(let m=0;m<n.length;m+=1)f.push({sum:s,offset:u,data:n[m],root:!1}),u-=n[m].value/100*c;if(f.push({sum:s,offset:u,data:{color:i},root:!0}),h.push({...f[f.length-1],lineRoundCaps:!1}),f.length>2){h.push({...f[0],lineRoundCaps:r}),h.push({...f[f.length-2],lineRoundCaps:r});for(let m=1;m<=f.length-3;m+=1)h.push({...f[m],lineRoundCaps:!1})}else h.push({...f[0],lineRoundCaps:r});return h}var UD={root:"m_b32e4812",svg:"m_d43b5134",curve:"m_b1ca1fbf",label:"m_b23f9dc4"};function O6(e,t){return Math.min(e||12,(t||120)/4)}const M6={size:120,thickness:12},I6=(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",M6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,label:h,sections:m,size:g,thickness:y,roundCaps:b,rootColor:S,transitionDuration:j,...C}=n,T=Ie({name:"RingProgress",classes:UD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:I6}),D=O6(y,g),E=N6({size:g,thickness:D,sections:m,renderRoundedLineCaps:b,rootColor:S}).map(({data:R,sum:A,root:k,lineRoundCaps:M,offset:I},$)=>v.createElement($D,{...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}),h&&o.jsx("div",{...T("label"),children:h})]})});Vp.classes=UD;Vp.displayName="@mantine/core/RingProgress";var BD={root:"m_cf365364",indicator:"m_9e182ccd",label:"m_1738fcb2",input:"m_1714d588",control:"m_69686b9b",innerLabel:"m_78882f40"};const L6={withItemsBorders:!0},z6=(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",L6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,data:h,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:BD,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:z6}),J=Sn(),G=h.map(ke=>typeof ke=="string"?{label:ke,value:ke}:ke),Z=_N(),[P,L]=v.useState(Dh()),[z,H]=v.useState(null),[O,U]=v.useState({}),K=(ke,vt)=>{O[vt]=ke,U(O)},[ee,Se]=Yn({value:m,defaultValue:g,finalValue:Array.isArray(h)?((Me=G.find(ke=>!ke.disabled))==null?void 0:Me.value)??((tt=h[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=>K(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=zn(t,ke=>H(ke));return RN(()=>{L(Dh())},[h.length]),h.length===0?null:o.jsxs(ce,{...Q("root"),variant:M,size:b,ref:qe,mod:[{"full-width":T,orientation:D,initialized:Z,"with-items-borders":$},V],...Y,role:"radiogroup","data-disabled":j,children:[typeof ee=="string"&&o.jsx(Vx,{target:O[ee],parent:z,component:"span",transitionDuration:"var(--sc-transition-duration)",...Q("indicator")},P),xe]})});Fp.classes=BD;Fp.displayName="@mantine/core/SegmentedControl";function $6({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),{}),h=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:h,selector:r})}function Vv(e){return typeof e=="object"&&e!==null?sn(e):[]}function U6(e){return e.sort((t,n)=>Ku(t)-Ku(n))}function B6({spacing:e,verticalSpacing:t,cols:n}){const r=Array.from(new Set([...Vv(e),...Vv(t),...Vv(n)]));return U6(r)}function V6({spacing:e,verticalSpacing:t,cols:n,selector:r}){var h;const i=t===void 0?e:t,s=qo({"--sg-spacing-x":Nn(_i(e)),"--sg-spacing-y":Nn(_i(i)),"--sg-cols":(h=_i(n))==null?void 0:h.toString()}),c=B6({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 VD={container:"m_925c2d2c",root:"m_2415a157"};const F6={cols:1,spacing:"md",type:"media"},I0=ve((e,t)=>{const n=se("SimpleGrid",F6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,cols:h,verticalSpacing:m,spacing:g,type:y,...b}=n,S=Ie({name:"SimpleGrid",classes:VD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f}),j=hd();return y==="container"?o.jsxs(o.Fragment,{children:[o.jsx(V6,{...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($6,{...n,selector:`.${j}`}),o.jsx(ce,{ref:t,...S("root",{className:j}),...b})]})});I0.classes=VD;I0.displayName="@mantine/core/SimpleGrid";const H6={},Hp=ve((e,t)=>{const{w:n,h:r,miw:i,mih:s,...c}=se("Space",H6,e);return o.jsx(ce,{ref:t,...c,w:n,miw:i??n,h:r,mih:s??r})});Hp.displayName="@mantine/core/Space";var FD={root:"m_6d731127"};const q6={gap:"md",align:"stretch",justify:"flex-start"},G6=(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",q6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,align:h,justify:m,gap:g,variant:y,...b}=n,S=Ie({name:"Stack",props:n,classes:FD,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:G6});return o.jsx(ce,{ref:t,...S("root"),variant:y,...b})});Ge.classes=FD;Ge.displayName="@mantine/core/Stack";const[Q6,W6]=vr("Stepper component was not found in tree"),Mh=()=>null;Mh.displayName="@mantine/core/StepperCompleted";var L0={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 ah=(e,t)=>typeof e=="function"?o.jsx(e,{step:t||0}):e,Y6={withIcon:!0,allowStepClick:!0,iconPosition:"left"},z0=ve((e,t)=>{const{classNames:n,className:r,style:i,styles:s,vars:c,step:u,state:f,color:h,icon:m,completedIcon:g,progressIcon:y,label:b,description:S,withIcon:j,iconSize:C,loading:T,allowStepClick:D,allowStepSelect:E,iconPosition:R,orientation:A,mod:k,...M}=se("StepperStep",Y6,e),I=W6(),$=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":h?Ht(h,$):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)}):ah(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:h}):ah(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:ah(b,u)}),S&&o.jsx("span",{...I.getStyles("stepDescription",V),children:ah(S,u)})]})]})});z0.classes=L0;z0.displayName="@mantine/core/StepperStep";const K6={orientation:"horizontal",iconPosition:"left",allowNextStepsSelect:!0,wrap:!0},X6=(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",K6,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,children:h,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:L0,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:X6}),Y=v.Children.toArray(h),Q=Y.filter(U=>U.type!==Mh),J=Y.find(U=>U.type===Mh),G=Q.reduce((U,K,ee)=>{const Se=g===ee?"stepProgress":g>ee?"stepCompleted":"stepInactive",xe=typeof m!="function"?!1:typeof K.props.allowStepSelect=="boolean"?K.props.allowStepSelect:Se==="stepCompleted"||k;return U.push(v.cloneElement(K,{icon:K.props.icon||y||ee+1,key:ee,step:ee,state:Se,onClick:()=>xe&&(m==null?void 0:m(ee)),allowStepClick:xe,completedIcon:K.props.completedIcon||b,progressIcon:K.props.progressIcon||S,color:K.props.color||j,iconSize:C,iconPosition:K.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},[]),Z=(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:Z;return o.jsx(Q6,{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=L0;mc.displayName="@mantine/core/Stepper";mc.Completed=Mh;mc.Step=z0;const HD=v.createContext(null),Z6=HD.Provider,J6=()=>v.useContext(HD),ez={},$0=ve((e,t)=>{const{value:n,defaultValue:r,onChange:i,size:s,wrapperProps:c,children:u,readOnly:f,...h}=se("SwitchGroup",ez,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(Z6,{value:{value:m,onChange:y,size:s},children:o.jsx(mn.Wrapper,{size:s,ref:t,...c,...h,labelElement:"div",__staticSelector:"SwitchGroup",children:o.jsx(a0,{role:"group",children:u})})})});$0.classes=mn.Wrapper.classes;$0.displayName="@mantine/core/SwitchGroup";var qD={root:"m_5f93f3bb",input:"m_926b4011",track:"m_9307d992",thumb:"m_93039a1d",trackLabel:"m_8277e082"};const tz={labelPosition:"right"},nz=(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}}),Cd=ve((e,t)=>{const n=se("Switch",tz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,color:h,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=J6(),G=S||(J==null?void 0:J.size),Z=Ie({name:"Switch",props:n,classes:qD,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:nz}),{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,{...Z("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:K=>{var ee;J?(ee=H.onChange)==null||ee.call(H,K):R==null||R(K),U(K.currentTarget.checked)},id:z,ref:t,type:"checkbox",role:"switch",...Z("input")}),o.jsxs(ce,{"aria-hidden":"true",component:"span",mod:{error:M,"label-position":A,"without-labels":!y&&!g},...Z("track"),children:[o.jsx(ce,{component:"span",mod:"reduce-motion",...Z("thumb"),children:T}),o.jsx("span",{...Z("trackLabel"),children:O?y:g})]})]})});Cd.classes={...qD,...K2};Cd.displayName="@mantine/core/Switch";Cd.Group=$0;const[rz,iz]=vr("Table component was not found in the tree");var Ed={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 az(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:h,styles:m,...g}=c,y=iz();return o.jsx(ce,{component:e,ref:s,...az(y,t),...y.getStyles(e,{className:f,classNames:u,style:h,styles:m,props:c}),...g})});return r.displayName=`@mantine/core/${n}`,r.classes=Ed,r}const Ny=tl("th",{columnBorder:!0}),GD=tl("td",{columnBorder:!0}),xh=tl("tr",{rowBorder:!0,striped:!0,highlightOnHover:!0}),QD=tl("thead",{stickyHeader:!0}),WD=tl("tbody"),YD=tl("tfoot"),KD=tl("caption",{captionSide:!0});function U0({data:e}){return o.jsxs(o.Fragment,{children:[e.caption&&o.jsx(KD,{children:e.caption}),e.head&&o.jsx(QD,{children:o.jsx(xh,{children:e.head.map((t,n)=>o.jsx(Ny,{children:t},n))})}),e.body&&o.jsx(WD,{children:e.body.map((t,n)=>o.jsx(xh,{children:t.map((r,i)=>o.jsx(GD,{children:r},i))},n))}),e.foot&&o.jsx(YD,{children:o.jsx(xh,{children:e.foot.map((t,n)=>o.jsx(Ny,{children:t},n))})})]})}U0.displayName="@mantine/core/TableDataRenderer";const oz={type:"scrollarea"},sz=(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}}),B0=ve((e,t)=>{const n=se("TableScrollContainer",oz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,children:h,minWidth:m,maxHeight:g,type:y,scrollAreaProps:b,...S}=n,j=Ie({name:"TableScrollContainer",classes:Ed,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:sz,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:h})})});B0.classes=Ed;B0.displayName="@mantine/core/TableScrollContainer";const lz={withRowBorders:!0,verticalSpacing:7},cz=(e,{layout:t,captionSide:n,horizontalSpacing:r,verticalSpacing:i,borderColor:s,stripedColor:c,highlightOnHoverColor:u,striped:f,highlightOnHover:h,stickyHeaderOffset:m,stickyHeader:g})=>({table:{"--table-layout":t,"--table-caption-side":n,"--table-horizontal-spacing":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":h&&u?Ht(u,e):void 0,"--table-sticky-header-offset":g?le(m):void 0}}),ye=ve((e,t)=>{const n=se("Table",lz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,horizontalSpacing:h,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:Ed,classNames:r,styles:c,unstyled:u,rootSelector:"table",vars:f,varsResolver:cz});return o.jsx(rz,{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(U0,{data:k})})})});ye.classes=Ed;ye.displayName="@mantine/core/Table";ye.Td=GD;ye.Th=Ny;ye.Tr=xh;ye.Thead=QD;ye.Tbody=WD;ye.Tfoot=YD;ye.Caption=KD;ye.ScrollContainer=B0;ye.DataRenderer=U0;const[uz,V0]=vr("Tabs component was not found in the tree");var Td={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 dz={},F0=ve((e,t)=>{const n=se("TabsList",dz,e),{children:r,className:i,grow:s,justify:c,classNames:u,styles:f,style:h,mod:m,...g}=n,y=V0();return o.jsx(ce,{...g,...y.getStyles("list",{className:i,style:h,classNames:u,styles:f,props:n,variant:y.variant}),ref:t,role:"tablist",variant:y.variant,mod:[{grow:s,orientation:y.orientation,placement:y.orientation==="vertical"&&y.placement,inverted:y.inverted},m],"aria-orientation":y.orientation,__vars:{"--tabs-justify":c},children:r})});F0.classes=Td;F0.displayName="@mantine/core/TabsList";const fz={},H0=ve((e,t)=>{const n=se("TabsPanel",fz,e),{children:r,className:i,value:s,classNames:c,styles:u,style:f,mod:h,keepMounted:m,...g}=n,y=V0(),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},h],role:"tabpanel",id:y.getPanelId(s),"aria-labelledby":y.getTabId(s),children:S})});H0.classes=Td;H0.displayName="@mantine/core/TabsPanel";const hz={},q0=ve((e,t)=>{const n=se("TabsTab",hz,e),{className:r,children:i,rightSection:s,leftSection:c,value:u,onClick:f,onKeyDown:h,disabled:m,color:g,style:y,classNames:b,styles:S,vars:j,mod:C,tabIndex:T,...D}=n,E=Sn(),{dir:R}=Zs(),A=V0(),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:h}),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})]})});q0.classes=Td;q0.displayName="@mantine/core/TabsTab";const YC="Tabs.Tab or Tabs.Panel component was rendered with invalid value or without value",pz={keepMounted:!0,orientation:"horizontal",loop:!0,activateTabWithKeyboard:!0,allowTabDeactivation:!1,unstyled:!1,inverted:!1,variant:"default",placement:"left"},mz=(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",pz,e),{defaultValue:r,value:i,onChange:s,orientation:c,children:u,loop:f,id:h,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(h),[Q,J]=Yn({value:i,defaultValue:r,finalValue:null,onChange:s}),G=Ie({name:"Tabs",props:n,classes:Td,className:A,style:k,classNames:D,styles:E,unstyled:R,vars:M,varsResolver:mz});return o.jsx(uz,{value:{placement:C,value:Q,orientation:c,id:Y,loop:f,activateTabWithKeyboard:m,getTabId:qj(`${Y}-tab`,YC),getPanelId:qj(`${Y}-panel`,YC),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=Td;Et.displayName="@mantine/core/Tabs";Et.Tab=q0;Et.Panel=H0;Et.List=F0;const gz={},ze=ve((e,t)=>{const n=se("TextInput",gz,e);return o.jsx(Pr,{component:"input",ref:t,...n,__staticSelector:"TextInput"})});ze.classes=Pr.classes;ze.displayName="@mantine/core/TextInput";var XD={root:"m_7341320d"};const vz={},yz=(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}}},G0=ve((e,t)=>{const n=se("ThemeIcon",vz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,autoContrast:h,...m}=n,g=Ie({name:"ThemeIcon",classes:XD,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:yz});return o.jsx(ce,{ref:t,...g("root"),...m})});G0.classes=XD;G0.displayName="@mantine/core/ThemeIcon";const xz=["h1","h2","h3","h4","h5","h6"],bz=["xs","sm","md","lg","xl"];function Sz(e,t){const n=t!==void 0?t:`h${e}`;return xz.includes(n)?{fontSize:`var(--mantine-${n}-font-size)`,fontWeight:`var(--mantine-${n}-font-weight)`,lineHeight:`var(--mantine-${n}-line-height)`}:bz.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 ZD={root:"m_8a5d1357"};const wz={order:1},jz=(e,{order:t,size:n,lineClamp:r,textWrap:i})=>{const s=Sz(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",wz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,order:f,vars:h,size:m,variant:g,lineClamp:y,textWrap:b,mod:S,...j}=n,C=Ie({name:"Title",props:n,classes:ZD,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:h,varsResolver:jz});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=ZD;Le.displayName="@mantine/core/Title";function Cz(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 Ez(e){return v.useSyncExternalStore(e.subscribe,()=>e.getState(),()=>e.getState())}function Tz(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 Rz=()=>Cz({notifications:[],queue:[],defaultPosition:"bottom-right",limit:5}),nl=Rz(),Dz=(e=nl)=>Ez(e);function kc(e,t){const n=e.getState(),r=t([...n.notifications,...n.queue]),i=Tz(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||Dh();return kc(t,r=>e.id&&r.some(i=>i.id===e.id)?r:[...r,{...e,id:n}]),n}function JD(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 Az(e=nl){kc(e,()=>[])}function _z(e=nl){kc(e,t=>t.slice(0,e.getState().limit))}const di={show:Oe,hide:JD,update:As,clean:Az,cleanQueue:_z,updateState:kc};function Oy(e,t){return Oy=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},Oy(e,t)}function eA(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,Oy(e,t)}var Fv={exports:{}},Hv,KC;function kz(){if(KC)return Hv;KC=1;var e="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";return Hv=e,Hv}var qv,XC;function Pz(){if(XC)return qv;XC=1;var e=kz();function t(){}function n(){}return n.resetWarningCache=t,qv=function(){function r(c,u,f,h,m,g){if(g!==e){var y=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw y.name="Invariant Violation",y}}r.isRequired=r;function i(){return r}var s={array:r,bigint:r,bool:r,func:r,number:r,object:r,string:r,symbol:r,any:r,arrayOf:i,element:r,elementType:r,instanceOf:i,node:r,objectOf:i,oneOf:i,oneOfType:i,shape:i,exact:i,checkPropTypes:n,resetWarningCache:t};return s.PropTypes=s,s},qv}var ZC;function Nz(){return ZC||(ZC=1,Fv.exports=Pz()()),Fv.exports}var Oz=Nz();const an=lx(Oz),JC={disabled:!1},Ih=En.createContext(null);var Mz=function(t){return t.scrollTop},qu="unmounted",ws="exited",js="entering",ec="entered",My="exiting",Xa=function(e){eA(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=My)}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&&Mz(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],h=f[0],m=f[1],g=this.getTimeouts(),y=u?g.appear:g.enter;if(!i&&!c||JC.disabled){this.safeSetState({status:ec},function(){s.props.onEntered(h)});return}this.props.onEnter(h,m),this.safeSetState({status:js},function(){s.props.onEntering(h,m),s.onTransitionEnd(y,function(){s.safeSetState({status:ec},function(){s.props.onEntered(h,m)})})})},n.performExit=function(){var i=this,s=this.props.exit,c=this.getTimeouts(),u=this.props.nodeRef?void 0:Hu.findDOMNode(this);if(!s||JC.disabled){this.safeSetState({status:ws},function(){i.props.onExited(u)});return}this.props.onExit(u),this.safeSetState({status:My},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],h=f[0],m=f[1];this.props.addEndListener(h,m)}i!=null&&setTimeout(this.nextCallback,i)},n.render=function(){var i=this.state.status;if(i===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=g0(s,["children","in","mountOnEnter","unmountOnExit","appear","enter","exit","timeout","addEndListener","onEnter","onEntering","onEntered","onExit","onExiting","onExited","nodeRef"]);return En.createElement(Ih.Provider,{value:null},typeof c=="function"?c(i,u):En.cloneElement(En.Children.only(c),u))},t}(En.Component);Xa.contextType=Ih;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=My;function Iz(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Q0(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 Lz(e,t){e=e||{},t=t||{};function n(m){return m in t?t[m]:e[m]}var r=Object.create(null),i=[];for(var s in e)s in t?i.length&&(r[s]=i,i=[]):i.push(s);var c,u={};for(var f in t){if(r[f])for(c=0;c<r[f].length;c++){var h=r[f][c];u[r[f][c]]=n(h)}u[f]=n(f)}for(c=0;c<i.length;c++)u[i[c]]=n(i[c]);return u}function _s(e,t,n){return n[t]!=null?n[t]:e.props[t]}function zz(e,t){return Q0(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 $z(e,t,n){var r=Q0(e.children),i=Lz(t,r);return Object.keys(i).forEach(function(s){var c=i[s];if(v.isValidElement(c)){var u=s in t,f=s in r,h=t[s],m=v.isValidElement(h)&&!h.props.in;f&&(!u||m)?i[s]=v.cloneElement(c,{onExited:n.bind(null,c),in:!0,exit:_s(c,"exit",e),enter:_s(c,"enter",e)}):!f&&u&&!m?i[s]=v.cloneElement(c,{in:!1}):f&&u&&v.isValidElement(h)&&(i[s]=v.cloneElement(c,{onExited:n.bind(null,c),in:h.props.in,exit:_s(c,"exit",e),enter:_s(c,"enter",e)}))}}),i}var Uz=Object.values||function(e){return Object.keys(e).map(function(t){return e[t]})},Bz={component:"div",childFactory:function(t){return t}},Oo=function(e){eA(t,e);function t(r,i){var s;s=e.call(this,r,i)||this;var c=s.handleExited.bind(Iz(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?zz(i,u):$z(i,c,u),firstRender:!1}},n.handleExited=function(i,s){var c=Q0(this.props.children);i.key in c||(i.props.onExited&&i.props.onExited(s),this.mounted&&this.setState(function(u){var f=Oh({},u.children);return delete f[i.key],{children:f}}))},n.render=function(){var i=this.props,s=i.component,c=i.childFactory,u=g0(i,["component","childFactory"]),f=this.state.contextValue,h=Uz(this.state.children).map(c);return delete u.appear,delete u.enter,delete u.exit,s===null?En.createElement(Ih.Provider,{value:f},h):En.createElement(Ih.Provider,{value:f},En.createElement(s,u,h))},t}(En.Component);Oo.propTypes={};Oo.defaultProps=Bz;const tA=["bottom-center","bottom-left","bottom-right","top-center","top-left","top-right"];function Vz(e,t){return e.reduce((n,r)=>(n[r.position||t].push(r),n),tA.reduce((n,r)=>(n[r]=[],n),{}))}const eE={left:"translateX(-100%)",right:"translateX(100%)","top-center":"translateY(-100%)","bottom-center":"translateY(100%)"},Fz={left:"translateX(0)",right:"translateX(0)","top-center":"translateY(0)","bottom-center":"translateY(0)"};function Hz({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:eE[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:Fz[c]},h={opacity:0,maxHeight:0,transform:eE[c]};return{...u,...{entering:f,entered:f,exiting:h,exited:h}[e]}}function qz(e,t){return typeof t=="number"?t:t===!1||e===!1?!1:e}const nA=v.forwardRef(({data:e,onHide:t,autoClose:n,...r},i)=>{const{autoClose:s,message:c,...u}=e,f=qz(n,e.autoClose),h=v.useRef(-1),m=()=>window.clearTimeout(h.current),g=()=>{t(e.id),m()},y=()=>{typeof f=="number"&&(h.current=window.setTimeout(g,f))};return v.useEffect(()=>{var b;(b=e.onOpen)==null||b.call(e,e)},[]),v.useEffect(()=>(y(),m),[f]),o.jsx(D0,{...r,...u,onClose:g,ref:i,onMouseEnter:m,onMouseLeave:y,children:c})});nA.displayName="@mantine/notifications/NotificationContainer";var rA={root:"m_b37d9ac7",notification:"m_5ed0edd0"};const Gz=Xa,Qz={position:"bottom-right",autoClose:4e3,transitionDuration:250,containerWidth:440,notificationMaxHeight:200,limit:5,zIndex:Wr("overlay"),store:nl,withinPortal:!0},Wz=(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",Qz,e),{classNames:r,className:i,style:s,styles:c,unstyled:u,vars:f,position:h,autoClose:m,transitionDuration:g,containerWidth:y,notificationMaxHeight:b,limit:S,zIndex:j,store:C,portalProps:T,withinPortal:D,...E}=n,R=Sn(),A=Dz(C),k=bN(),M=hx(),I=v.useRef({}),$=v.useRef(0),Y=(R.respectReducedMotion?M:!1)?1:g,Q=Ie({name:"Notifications",classes:rA,props:n,className:i,style:s,classNames:r,styles:c,unstyled:u,vars:f,varsResolver:Wz});v.useEffect(()=>{C==null||C.updateState(Z=>({...Z,limit:S||5,defaultPosition:h}))},[S,h]),za(()=>{A.notifications.length>$.current&&setTimeout(()=>k(),0),$.current=A.notifications.length},[A.notifications]);const J=Vz(A.notifications,h),G=tA.reduce((Z,P)=>(Z[P]=J[P].map(({style:L,...z})=>o.jsx(Gz,{timeout:Y,onEnter:()=>I.current[z.id].offsetHeight,nodeRef:{current:I.current[z.id]},children:H=>o.jsx(nA,{ref:O=>{I.current[z.id]=O},data:z,onHide:O=>JD(O,C),autoClose:m,...Q("notification",{style:{...Hz({state:H,position:P,transitionDuration:Y,maxHeight:b}),...L}})})},z.id)),Z),{});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=rA;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 Yz{constructor(t,n){this.operator=t,this.child=n}toString(){return`${this.operator}(${this.child.toString()})`}}class Rd{constructor(t,n,r){this.operator=t,this.left=n,this.right=r}toString(){return`(${this.left.toString()} ${this.operator} ${this.right.toString()})`}}class Kz{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 Xz(t,this.prefixParselets,this.infixParselets)}}class Xz{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 iA{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 Dd="http://hl7.org",aA="ok",Zz="created",Jz="gone",e8="not-modified",t8="not-found",n8="unauthorized",r8="forbidden",i8="accepted",a8={resourceType:"OperationOutcome",id:aA,issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},o8={resourceType:"OperationOutcome",id:t8,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},id={resourceType:"OperationOutcome",id:n8,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},s8={...id,issue:[...id.issue,{severity:"error",code:"expired",details:{text:"Token expired"}}]},tE={...id,issue:[...id.issue,{severity:"error",code:"invalid",details:{text:"Token not issued for this audience"}}]},W0={resourceType:"OperationOutcome",id:r8,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 l8(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"exception",details:{text:"Internal server error"},diagnostics:e.toString()}]}}function c8(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 oA(e){return e.id===aA||e.id===Zz||e.id===e8||e.id===i8}function u8(e){return e.id===Jz}class dt extends Error{constructor(t,n){super(sA(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:c8(e)?e.message:qp(e)?sA(e):typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:JSON.stringify(e):"Unknown error"}function sA(e){var n;const t=((n=e.issue)==null?void 0:n.map(lA))??[];return t.length>0?t.join("; "):"Unknown error"}function lA(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 d8(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 f8(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,d8(i,s)])),constraints:[],innerTypes:[]};return t}const h8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]}}},p8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]}}},m8={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"}]}}},g8={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"}]}}},v8={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"}]}}},y8={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"}]}}},x8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},coding:{max:9007199254740991,type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},b8={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"}]}}},S8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:9007199254740991,type:[{code:"ContactPoint"}]}}},w8={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"}]}}},j8={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"}]}}},C8={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"}]}}},E8={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"}]}}},T8={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"}]}}},R8={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"}]}}},D8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},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"}]},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"]}]}}},k8={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"]}]}}},P8={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"}]}}},N8={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"}]}}},O8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},M8={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"}]}}},I8={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"}]}}},L8={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"}]}}},z8={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"}]}}},$8={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"]}]}}},U8={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"]}]}}},B8={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"}]}}},V8={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"}]}}},F8={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"}]}}},H8={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"}]}}},q8={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"]}]}}},G8={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"}]}}},Q8={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"}]}}},W8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},Y8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},K8={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"]}]}}},X8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},Z8={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"}]}}},J8={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"}]}}},e$={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"}]}}},t$={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"}]}}},n$={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"]}]}}},r$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},i$={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"}]}}},a$={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"]}]}}},o$={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"}]}}},s$={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"}]}}},l$={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"}]}}},c$={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]},highLimit:{type:[{code:"Quantity"}]}}},u$={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"}]}}},d$={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"}]}}},f$={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"}]}}},h$={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"]}]}}},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"}]},value:{type:[{code:"decimal"}]},comparator:{max:0,type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},g$={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"}]}}},v$={Element:h8,BackboneElement:p8,Address:m8,Age:g8,Annotation:v8,Attachment:y8,CodeableConcept:x8,Coding:b8,ContactDetail:S8,ContactPoint:w8,Contributor:j8,Count:C8,DataRequirement:E8,DataRequirementCodeFilter:T8,DataRequirementDateFilter:R8,DataRequirementSort:D8,Distance:A8,Dosage:_8,DosageDoseAndRate:k8,Duration:P8,ElementDefinition:N8,ElementDefinitionSlicingDiscriminator:O8,ElementDefinitionSlicing:M8,ElementDefinitionBase:I8,ElementDefinitionType:L8,ElementDefinitionExample:z8,ElementDefinitionConstraint:$8,ElementDefinitionBinding:U8,ElementDefinitionMapping:B8,Expression:V8,Extension:F8,HumanName:H8,Identifier:q8,MarketingStatus:G8,Meta:Q8,Money:W8,Narrative:Y8,ParameterDefinition:K8,Period:X8,Population:Z8,ProdCharacteristic:J8,ProductShelfLife:e$,Quantity:t$,Range:n$,Ratio:r$,Reference:i$,RelatedArtifact:a$,SampledData:o$,Signature:s$,SubstanceAmount:l$,SubstanceAmountReferenceRange:c$,Timing:u$,TimingRepeat:d$,TriggerDefinition:f$,UsageContext:h$,MoneyQuantity:p$,SimpleQuantity:m$,IdentityProvider:g$};function y$(e){return new b$(e).parse()}const Lh=f8(v$),Y0=Object.create(null),nE=Object.create(null),x$={"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 cA(e){let t;return t=nE[e],t||(t=nE[e]=Object.create(null)),t}function rE(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");dU(n);for(const i of n)uA(i)}function uA(e){var s,c;if(!(e!=null&&e.name))throw new Error("Failed loading StructureDefinition from bundle");if(e.resourceType!=="StructureDefinition")return;const t=y$(e),n=x$[e.url];let r,i;n?(r=Lh,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=Lh,i=e.type):(r=cA(e.url),i=e.type),r[i]=t;for(const u of t.innerTypes)u.parentType=t,r[u.name]=u;Y0[e.url]=t}function dA(e){return!!Lh[e]}function Gp(e,t){if(t){const n=cA(t)[e];if(n)return n}return Lh[e]}function fA(e,t){const n=Gp(e,t);if(!n)throw new dt(ra("Unknown data type: "+e));return n}function K0(e){return!!Y0[e]}function Pc(e){return Y0[e]}class b${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:j$(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=Gv(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[Gv(t,f.path)]=u;break}f=f.parent}if(!f){const h=Gv(t,this.root.path);t.isSummary&&((s=this.resourceSchema.summaryProperties)==null||s.add(h.replace("[x]",""))),u.min>0&&((c=this.resourceSchema.mandatoryProperties)==null||c.add(h.replace("[x]",""))),this.resourceSchema.elements[h]=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=fE(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;w$(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=fE(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=iE(t.max),r=(s=t.base)!=null&&s.max?iE(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:aE(gc(i,"fixed[x]")),pattern:aE(gc(i,"pattern[x]")),binding:t.binding}}}function iE(e){return e==="*"?Number.POSITIVE_INFINITY:Number.parseInt(e,10)}function Gv(e,t=""){return S$(e.path,t)}function S$(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 aE(e){return Array.isArray(e)&&e.length>0?e[0]:Rn(e)?void 0:e}function w$(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 j$(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 C$(e,t,n){if(e===void 0)return[void 0];if(t==="$this")return[e];const r=n!=null&&n.withPath?E$:gc,[i,...s]=t.split(".");let c=[r(e,i,n)];for(const u of s){const f=[];for(const h of c)if(Array.isArray(h))for(const m of h)f.push(r(m,u,n));else(n!=null&&n.withPath&&h&&h.value!==void 0||!(n!=null&&n.withPath)&&h!==void 0)&&f.push(r(h,u,n));c=f}return c}function E$(e,t,n){const r=e.path;return T$(gc(e,t,n),r,t)}function T$(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 hA={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 R$(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 J0(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}:jA(e)?{type:oe.CodeableConcept,value:e}:wA(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?pA(e,t,r):Ad(e,t)}function pA(e,t,n){const r=e.value,i=n.type;if(!i||i.length===0)return;let s,c="undefined",u;const f=n.path.lastIndexOf("."),h=n.path.substring(f+1);for(const m of i){const g=h.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]=cE(s[m],u[m])}else s=cE(s,u);if(!Rn(s))return(c==="Element"||c==="BackboneElement")&&(c=n.type[0].code),Array.isArray(s)?s.map(m=>oE(m,c)):oE(s,c)}function oE(e,t){return t==="Resource"&&fa(e)&&(t=e.resourceType),{type:t,value:e}}function Ad(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 mA(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 D$(e){return We(!ea(e))}function A$(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 _$(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(xA(n,r)):We(typeof n=="object"&&typeof r=="object"?X0(e,t):n===r)}function gA(e,t){return e.length===0&&t.length===0?We(!0):e.length!==t.length?We(!1):(e.sort(sE),t.sort(sE),We(e.every((n,r)=>ea(k$(n,t[r])))))}function k$(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(xA(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"?X0({...c,id:void 0},{...u,id:void 0}):typeof c=="string"&&typeof u=="string"?c.toLowerCase()===u.toLowerCase():c===u)}function sE(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 vA(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 P$(n);case"DateTime":return zh(n);case"Time":return typeof n=="string"&&!!/^T\d/.exec(n);case"Period":return yA(n);case"Quantity":return fi(n);default:return e.type===r||typeof n=="object"&&(n==null?void 0:n.resourceType)===r}}function P$(e){return typeof e=="string"&&!!hA.date.exec(e)}function zh(e){return typeof e=="string"&&!!hA.dateTime.exec(e)}function yA(e){return!!(e&&typeof e=="object"&&("start"in e&&zh(e.start)||"end"in e&&zh(e.end)))}function fi(e){return!!(e&&typeof e=="object"&&"value"in e&&typeof e.value=="number")}function xA(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 X0(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(lE(s)&&lE(c)){if(!X0(s,c))return!1}else if(s!==c)return!1}return!0}function lE(e){return e!==null&&typeof e=="object"}function cE(e,t){if(t){if(typeof t!="object")throw new Error("Primitive extension must be an object");return N$(e??{},t)}return e}function N$(e,t){return delete t.__proto__,delete t.constructor,Object.assign(e,t)}function O$(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(O$(e))return`${e.resourceType}/${e.id}`}function Bs(e){if(e)return Ko(e)?e.reference.split("/")[1]:e.id}function M$(e){return e.resourceType==="Patient"||e.resourceType==="Practitioner"||e.resourceType==="RelatedPerson"}function Va(e){if(M$(e)){const t=I$(e);if(t)return t}if(e.resourceType==="Device"){const t=L$(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]),jA(t))return Fo(t);if(Q$(t))return t.text}return zt(e)??""}function I$(e){const t=e.name;if(t&&t.length>0)return Nc(t[0])}function L$(e){const t=e.deviceName;if(t&&t.length>0)return t[0].name}function z$(e){if(!("photo"in e))return;const t=e.photo;if(t)if(Array.isArray(t))for(const n of t){const r=uE(n);if(r)return r}else return uE(t)}function uE(e){var t;if(e.url&&((t=e.contentType)!=null&&t.startsWith("image/")))return e.url}function bA(e,t){const n=new Date(e);n.setUTCHours(0,0,0,0);const r=t?new Date(t):new Date;r.setUTCHours(0,0,0,0);const i=n.getUTCFullYear(),s=n.getUTCMonth(),c=n.getUTCDate(),u=r.getUTCFullYear(),f=r.getUTCMonth(),h=r.getUTCDate();let m=u-i;(f<s||f===s&&h<c)&&m--;let g=u*12+f-(i*12+s);h<c&&g--;const y=Math.floor((r.getTime()-n.getTime())/(1e3*60*60*24));return{years:m,months:g,days:y}}function $$(e,t){const{years:n,months:r,days:i}=bA(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=Z0(e);return JSON.stringify(n,null,t?2:void 0)??""}function Z0(e){if(!(e==null||e===""))return typeof e=="object"?Array.isArray(e)?U$(e):B$(e):e}function U$(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=Z0(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 B$(e){let t,n=0;for(const r in e){const i=e[r],s=Z0(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)?V$(e,t):Array.isArray(e)||Array.isArray(t)?!1:sr(e)&&sr(t)?F$(e,t,n):(sr(e)||sr(t),!1)}function V$(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 F$(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 J0(e,t){return Rn(e)?!0:Rn(t)?!1:Array.isArray(e)&&Array.isArray(t)?H$(e,t):Array.isArray(e)||Array.isArray(t)?!1:sr(e)&&sr(t)?q$(e,t):sr(e)||sr(t)?!1:e===t}function H$(e,t){return t.every(n=>e.some(r=>J0(r,n)))}function q$(e,t){return Object.entries(t).every(([n,r])=>n in e&&J0(e[n],r))}function Qr(e){return e===void 0?e:JSON.parse(JSON.stringify(e))}function SA(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 G$(e){return typeof e=="string"}function wA(e){return sr(e)&&"code"in e&&typeof e.code=="string"}function jA(e){return sr(e)&&"coding"in e&&Array.isArray(e.coding)&&e.coding.every(wA)}function Q$(e){return sr(e)&&"text"in e&&typeof e.text=="string"}const CA=[];for(let e=0;e<256;e++)CA.push(e.toString(16).padStart(2,"0"));function W$(e){const t=EA(e),n=new Uint8Array(t),r=new Array(n.length);for(let i=0;i<n.length;i++)r[i]=CA[n[i]];return r.join("")}function Y$(e){const t=EA(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 EA(e){return ArrayBuffer.isView(e)?e.buffer:e}function Hn(e){return e?e.charAt(0).toUpperCase()+e.substring(1):""}function eb(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 K$(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 X$(e){if(e!==void 0)return Array.isArray(e)?e:[e]}const dE=e=>new Promise(t=>{setTimeout(t,e)});function Iy(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 Z$(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 tb(e){return e.endsWith("/")?e:e+"/"}function J$(e){return e.startsWith("/")?e.slice(1):e}function Xi(e,t){return new URL(J$(t),tb(e.toString())).toString()}function eU(e,t){return Xi(e,t).toString().replace("http://","ws://").replace("https://","wss://")}function tU(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 TA(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 nU(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 RA(e.value);case"CodeableConcept":return Fo(e.value);case"Coding":return _d(e.value);case"ContactPoint":return e.value.value;case"HumanName":return Nc(e.value);case"Quantity":return Ps(e.value);case"Reference":return rU(e.value);default:return e.value.toString()}}function rU(e){return e?e.display??e.reference??Ii(e):""}function RA(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 iU(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 aU(e,t,n){return!e||!e.start&&!e.end?"":gr(e.start,t,n)+" - "+gr(e.end,t,n)}const oU={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},sU={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},lU={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function DA(e){if(!e)return"";const t=[];return cU(t,e.repeat),e.event&&t.push(e.event.map(n=>gr(n)).join(", ")),Hn(t.join(" ").trim())}function cU(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(oU[i]):(n===1?e.push("once"):e.push(n+" times"),r===1?e.push("per "+sU[i]):e.push("per "+r+" "+lU[i])),t.dayOfWeek&&e.push("on "+t.dayOfWeek.map(Hn).join(", ")),t.timeOfDay&&e.push("at "+t.timeOfDay.map(s=>iU(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 uU(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=>_d(n)).join(", "):"")}function _d(e,t){const n=sd(e==null?void 0:e.display);return n?`${n}`:sd(e==null?void 0:e.code)??""}function AA(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=>AA(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 dU(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"&&_A(r.type)}function _A(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 fU(e){for(const t of e.base??[]){const n=_A(t);n.searchParams||(n.searchParams={}),n.searchParams[e.code]=e}}function fE(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"?hU((s=((i=e.base)==null?void 0:i.path)??e.path)==null?void 0:s.split(".")):t}function hU(e){return e.length===1?e[0]:e.map(Hn).join("")}function nb(e){var t;return(t=la.types[e])==null?void 0:t.searchParams}function pU(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 kA(t)}function kA(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(gU).join(" ").replace("_"," ").replace(/\s+/g," ")}const mU=new Set(["ID","IP","PKCE","JWKS","URI","URL","OMB","UDI"]);function gU(e){const t=e.toUpperCase();return e===t?e:mU.has(t)?t:t.charAt(0)+e.slice(1)}function Yo(e,t,n){const r=Gp(e,n);if(r)return vU(r.elements,t)}function vU(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 bh(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 mA([...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:bh(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:bh(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:bh("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 h;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=(h=i.eval(e,t)[0])==null?void 0:h.value;if(u!=="years"&&u!=="months"&&u!=="days")throw new Error("Invalid units");const f=bA(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 ld?r=n.name:n instanceof Yp&&(r=n.left.name+"."+n.right.name),r?t.map(i=>({type:oe.boolean,value:vA(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 ld&&(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,h=s?{...i,value:u}:u;return[{type:f,value:h}]}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 rb{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 ld{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 yU{eval(){return[]}toString(){return"{}"}}class xU extends Yz{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 Rd{constructor(t,n){super("as",t,n)}eval(t,n){return Tr.ofType(t,this.left.eval(t,n),this.right)}}class Nr extends Rd{}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,h=this.impl(u,f);return typeof h=="boolean"?We(h):fi(s)?[{type:oe.Quantity,value:{...s,value:h}}]:[mi(h)]}}class bU extends Rd{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 SU 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 wU 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 Yp extends Rd{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 ib extends Rd{constructor(t,n){super("|",t,n)}eval(t,n){const r=this.left.eval(t,n),i=this.right.eval(t,n);return mA([...r,...i])}}class jU 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 A$(r,i)}}class CU 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 _$(r,i)}}class EU 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 gA(r,i)}}class TU 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 D$(gA(r,i))}}class ab 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(vA(r[0],i))}}class RU 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 DU 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 AU 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 _U 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 ob{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 sb{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 kU=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"];class PU{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()===" "&&NU(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 NU(e){return!!(e&&(e.id==="String"||e.id==="Symbol"&&kU.includes(e.value)))}const OU=["true","false"],MU=["!=","!~","<=",">=","{}","->"];function IU(e){return new PU(e,OU,MU).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},LU={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}},zU={parse(e,t){const n=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new sb(t,n)},precedence:Xt.Indexer},$U={parse(e,t){if(!(t instanceof ld))throw new Error("Unexpected parentheses");const n=[];for(;!e.match(")");)n.push(e.consumeAndParse()),e.match(",");return new ob(t.name,n)},precedence:Xt.FunctionCall};function UU(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 BU(){return new Kz().registerPrefix("String",{parse:(e,t)=>new Yl({type:oe.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new Yl({type:oe.dateTime,value:bh(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new Yl({type:oe.Quantity,value:UU(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 ld(t.value)}).registerPrefix("{}",{parse:()=>new yU}).registerPrefix("(",LU).registerInfix("[",zU).registerInfix("(",$U).prefix("+",Xt.UnaryAdd,(e,t)=>new xU("+",t,n=>n)).prefix("-",Xt.UnarySubtract,(e,t)=>new Di("-",t,t,(n,r)=>-r)).infixLeft(".",Xt.Dot,(e,t,n)=>new Yp(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 ib(e,n)).infixLeft("=",Xt.Equals,(e,t,n)=>new jU(e,n)).infixLeft("!=",Xt.NotEquals,(e,t,n)=>new CU(e,n)).infixLeft("~",Xt.Equivalent,(e,t,n)=>new EU(e,n)).infixLeft("!~",Xt.NotEquivalent,(e,t,n)=>new TU(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 bU(e,n)).infixLeft("and",Xt.And,(e,t,n)=>new RU(e,n)).infixLeft("as",Xt.As,(e,t,n)=>new $h(e,n)).infixLeft("contains",Xt.Contains,(e,t,n)=>new SU(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 wU(e,n)).infixLeft("is",Xt.Is,(e,t,n)=>new ab(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 DU(e,n)).infixLeft("xor",Xt.Xor,(e,t,n)=>new AU(e,n)).infixLeft("implies",Xt.Implies,(e,t,n)=>new _U(e,n))}const VU=BU();function lb(e){return new rb(e,VU.construct(IU(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??lb(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()}})}function FU(e){var t;return(t=e.match(/^\((.+)\)\.identifier$/))==null?void 0:t[1]}function HU(e,t){return new rb(e,new Yp(t,new ld("identifier")))}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=GU(e,t)),n}function qU(e,t,n){let r=la.types[e];r||(r={},la.types[e]=r),r.searchParamsDetails||(r.searchParamsDetails={}),r.searchParamsDetails[t]=n}function GU(e,t){const n=t.code,r=t.expression,i=KU(e,r),s={elementDefinitions:[],propertyTypes:new Set,array:!1};for(const f of i){const h=Sh(f),m=Z8(()=>h.join("."));h.length===1&&h[0]instanceof Nr?s.propertyTypes.add("boolean"):t.code.endsWith(":identifier")?s.propertyTypes.add("Identifier"):m().endsWith("extension.value.code")||m().endsWith("extension.value.coding.code")?(s.array=!0,s.propertyTypes.add("code")):PA(s,h,e,1),m().endsWith("extension.valueDateTime")&&(s.array=!1)}let c;if(t.code.endsWith(":identifier")){const f=FU(r);if(f===void 0)throw new Error(`Unexpected expression for derived identifier search parameter: ${r}`);const h=hE(e,f);c=HU(r,h)}else c=hE(e,r);const u={type:YU(t,s.propertyTypes),elementDefinitions:s.elementDefinitions,parsedExpression:c,array:s.array};return qU(e,n,u),u}function PA(e,t,n,r){const i=t[r];if(i instanceof $h){e.propertyTypes.add(i.right.toString());return}if(i instanceof ob){QU(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 sb&&(u=!0,f++);const h=t[f];if(c.isArray&&!u&&(e.array=!0),f===t.length-1&&h instanceof $h){e.elementDefinitions.push(c),e.propertyTypes.add(h.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;WU(g)&&(g=c.type[0].code),PA(e,t,g,f)}}function QU(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 ab){e.propertyTypes.add(t.args[0].right.toString());return}throw new Error(`Unhandled FHIRPath function: ${t.name}`)}function WU(e){return e==="Element"||e==="BackboneElement"}function YU(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 KU(e,t){const n=[],r=lb(t);return Uh(e,r.child,n),n}function hE(e,t){const n=[],r=lb(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 ib(i,n[s]);return new rb("<original-not-available>",i)}function Uh(e,t,n){t instanceof ib?(Uh(e,t.left,n),Uh(e,t.right,n)):t.toString().includes(e+".")&&n.push(t)}function Sh(e){if(e instanceof $h||e instanceof sb)return[Sh(e.left),e].flat();if(e instanceof Nr)return[e];if(e instanceof Yp)return[Sh(e.left),Sh(e.right)].flat();if(e instanceof ob){if(e.name==="where"&&!(e.args[0]instanceof ab))return[];if(e.name==="last")return[]}return[e]}const Kp=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"},NA={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},cb={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 OA(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()),XU(i,s)}function XU(e,t){const n={resourceType:e};for(const[r,i]of t)ZU(n,r,i);return n}function ZU(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":JU(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,tB(f,i,n)):e.filters=Lu(e.filters,nB(r,i,n))}}}}function JU(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 eB=[ue.MISSING,ue.PRESENT];function tB(e,t,n){if(eB.includes(t))return{code:e.code,operator:t,value:n};switch(e.type){case"number":case"date":case"quantity":{const{operator:r,value:i}=rB(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:iB(t),value:n};default:throw new Error("Unrecognized search parameter type: "+e.type)}}function nB(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 cb&&(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 rB(e){const t=e.substring(0,2),n=cb[t];return n?{operator:n,value:e.substring(2)}:{operator:ue.EQUALS,value:e}}function iB(e){return NA[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 zh(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(aB(n))),e.sortRules&&e.sortRules.length>0&&t.push(oB(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 aB(e){const t=e.operator in NA?":"+e.operator:"",n=e.operator!==ue.EQUALS&&e.operator in cb?e.operator:"";return`${e.code}${t}=${n}${encodeURIComponent(e.value)}`}function oB(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 ub(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 sB(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters){for(const n of t.filters)if(!lB(e,t,n))return!1}return!0}function lB(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 cB(e,n,r);switch(r.type){case"reference":return uB(e,n,r);case"string":case"uri":return MA(e,n,r);case"token":return dB(e,n,r);case"date":return mB(e,n,r);default:return!1}}function cB(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 uB(e,t,n){const r=Oc(n.expression,e),i=Xp(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 ub(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 dB(e,t,n){return Mc(e.resourceType,n).type===Jn.BOOLEAN?fB(e,t,n):MA(e,t,n,!0)}function fB(e,t,n){const r=Oc(n.expression,e),i=t.value==="true",s=r.includes(i);return Xp(t.operator)?!s:s}function MA(e,t,n,r){var h,m,g,y;const s=(y=(g=(m=(h=Mc(e.resourceType,n).elementDefinitions)==null?void 0:h[0])==null?void 0:m.type)==null?void 0:g[0])==null?void 0:y.code,c=Oc(n.expression,e),u=ub(t.value),f=Xp(t.operator);for(const b of c)for(const S of u){let j;if(s===oe.Identifier?j=hB(b,t.operator,S):s===oe.CodeableConcept?j=pB(b,t.operator,S):j=Ly(b,t.operator,S,r),j)return!f}return f}function Ly(e,t,n,r){if(r&&n.includes("|")){const[s,c]=n.split("|");return Ly(e,t,s,!1)&&(!c||Ly(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 hB(e,t,n){var r,i,s,c;if(n.includes("|")){const[u,f]=n.split("|").map(h=>h.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 pB(e,t,n){var r,i,s,c;if(n.includes("|")){const[u,f]=n.split("|").map(h=>h.toLowerCase());return!u&&!f?!1:u?((i=e.coding)==null?void 0:i.some(h=>{var m,g;return((m=h.system)==null?void 0:m.toLowerCase())===u&&(!f||((g=h.code)==null?void 0:g.toLowerCase())===f)}))??!1:((r=e.coding)==null?void 0:r.some(h=>{var m;return!h.system&&((m=h.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 mB(e,t,n){const r=Oc(n.expression,e),i=ub(t.value),s=Xp(t.operator);for(const c of r)for(const u of i)if(gB(Bh(c),t.operator,Bh(u)))return!s;return s}function gB(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(G8(e))try{return new Date(e).toISOString()}catch(t){console.debug("Failed to parse date",e,t)}else if(yA(e)){if("start"in e)return Bh(e.start);if("end"in e)return Bh(e.end)}}function Xp(e){return e===ue.NOT_EQUALS||e===ue.NOT}const vB={resourceType:"*"},yB=["DomainConfiguration","JsonWebKey","Login"],xB=["PasswordChangeRequest","UserSecurityRequest","Project","ProjectMembership","User"],Ns={READ:"read",VREAD:"vread",UPDATE:"update",HISTORY:"history",SEARCH:"search"},bB=[Ns.READ,Ns.VREAD,Ns.HISTORY,Ns.SEARCH];function SB(e,t){return yB.includes(t)?!1:wB(e,Ns.UPDATE,t)}function wB(e,t,n){var r;return!!((r=e.resource)!=null&&r.some(i=>LA(i,n,t)))}function IA(e,t,n){var r;return n?(r=n.resource)==null?void 0:r.find(i=>jB(e,t,i)):vB}function jB(e,t,n){var i,s;const r=e.resourceType;return!(!LA(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&&!sB(e,OA(n.criteria)))}function LA(e,t,n){return e.resourceType!==t&&(e.resourceType!=="*"||xB.includes(t))?!1:e.interaction?e.interaction.includes(n):!e.readonly||bB.includes(n)}function CB(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 EB(e){e=e.padEnd(e.length+(4-e.length%4)%4,"=");const t=e.replace(/-/g,"+").replace(/_/g,"/");return CB(t)}function yE(){const e=new Uint32Array(28);return crypto.getRandomValues(e),W8(e.buffer)}async function TB(e){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))}function zA(){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 $A(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]=zA(),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)=>RB(s,c,t),2);return DB(JSON.parse(r))}function RB(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 DB(e){const t=_B(e),{sorted:n,cycles:r}=AB(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],h={...f,request:{...f.request,method:"PUT"}};s.push(h)}return{...e,entry:s}}const Kl={NotVisited:"NotVisited",Visiting:"Visiting",Visited:"Visited"};function AB(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 UA(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 UA(r,t)}}function _B(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&&UA(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 kB{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 Zp{constructor(){this.emitter=new kB}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 zy={"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"},PB=["Patient","Encounter","ImagingStudy","DiagnosticReport","OperationOutcome","Bundle"],db=["DiagnosticReport-update"];function NB(e){return db.includes(e)}function OB(e){if(db.includes(e))throw new dt(yn(`'context.version' is required for '${e}'.`))}const MB={"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 IB(e){return PB.includes(e)}function BA(e){return!!e.endpoint}function xE(e){if(!fb(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 BA(e)&&(s.endpoint=e.endpoint),new URLSearchParams(s).toString()}function fb(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(!zy[s])return!1;return!(BA(e)&&!(typeof e.endpoint=="string"&&e.endpoint.startsWith("ws")))}function LB(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(!IB(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 zB(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 LB(e,t.resource,n,r)}function $B(e,t){const n=new Map,r=MB[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.`));zB(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(!zy[t])throw new dt(yn(`Must provide a valid FHIRcast event name. Supported events: ${Object.keys(zy).join(", ")}`));if(typeof n!="object")throw new dt(yn("context must be a context object or array of context objects."));if(db.includes(t)&&!r)throw new dt(yn(`The '${t}' event must contain a 'context.versionId'.`));const i=Array.isArray(n)?n:[n];return $B(t,i),{timestamp:new Date().toISOString(),id:zA(),event:{"hub.topic":e,"hub.event":t,context:i,...r?{"context.versionId":r}:{}}}}class UB extends Zp{constructor(t){if(super(),this.subRequest=t,!t.endpoint)throw new dt(yn("Subscription request should contain an endpoint."));if(!fb(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 BB(e){return JSON.parse(EB(e))}function VB(e){return e.split(".").length===3}function hb(e){const[t,n,r]=e.split(".");return BB(n)}function FB(e){try{return typeof hb(e).login_id=="string"}catch{return!1}}function HB(e){try{const n=hb(e).exp;return typeof n=="number"?n*1e3:void 0}catch{return}}class qB{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 VA;VA=Symbol.toStringTag;class Ai{constructor(t){this[VA]="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 GB{constructor(t){this.storage=t??(typeof localStorage<"u"?localStorage:new QB)}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 QB{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 NU(e){return!!(e&&(e.id==="String"||e.id==="Symbol"&&kU.includes(e.value)))}const OU=["true","false"],MU=["!=","!~","<=",">=","{}","->"];function IU(e){return new PU(e,OU,MU).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},LU={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}},zU={parse(e,t){const n=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new sb(t,n)},precedence:Xt.Indexer},$U={parse(e,t){if(!(t instanceof ld))throw new Error("Unexpected parentheses");const n=[];for(;!e.match(")");)n.push(e.consumeAndParse()),e.match(",");return new ob(t.name,n)},precedence:Xt.FunctionCall};function UU(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 BU(){return new Kz().registerPrefix("String",{parse:(e,t)=>new Yl({type:oe.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new Yl({type:oe.dateTime,value:bh(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new Yl({type:oe.Quantity,value:UU(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 ld(t.value)}).registerPrefix("{}",{parse:()=>new yU}).registerPrefix("(",LU).registerInfix("[",zU).registerInfix("(",$U).prefix("+",Xt.UnaryAdd,(e,t)=>new xU("+",t,n=>n)).prefix("-",Xt.UnarySubtract,(e,t)=>new Di("-",t,t,(n,r)=>-r)).infixLeft(".",Xt.Dot,(e,t,n)=>new Yp(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 ib(e,n)).infixLeft("=",Xt.Equals,(e,t,n)=>new jU(e,n)).infixLeft("!=",Xt.NotEquals,(e,t,n)=>new CU(e,n)).infixLeft("~",Xt.Equivalent,(e,t,n)=>new EU(e,n)).infixLeft("!~",Xt.NotEquivalent,(e,t,n)=>new TU(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 bU(e,n)).infixLeft("and",Xt.And,(e,t,n)=>new RU(e,n)).infixLeft("as",Xt.As,(e,t,n)=>new $h(e,n)).infixLeft("contains",Xt.Contains,(e,t,n)=>new SU(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 wU(e,n)).infixLeft("is",Xt.Is,(e,t,n)=>new ab(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 DU(e,n)).infixLeft("xor",Xt.Xor,(e,t,n)=>new AU(e,n)).infixLeft("implies",Xt.Implies,(e,t,n)=>new _U(e,n))}const VU=BU();function lb(e){return new rb(e,VU.construct(IU(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??lb(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()}})}function FU(e){var t;return(t=e.match(/^\((.+)\)\.identifier$/))==null?void 0:t[1]}function HU(e,t){return new rb(e,new Yp(t,new ld("identifier")))}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=GU(e,t)),n}function qU(e,t,n){let r=la.types[e];r||(r={},la.types[e]=r),r.searchParamsDetails||(r.searchParamsDetails={}),r.searchParamsDetails[t]=n}function GU(e,t){const n=t.code,r=t.expression,i=KU(e,r),s={elementDefinitions:[],propertyTypes:new Set,array:!1};for(const f of i){const h=Sh(f),m=Z$(()=>h.join("."));h.length===1&&h[0]instanceof Nr?s.propertyTypes.add("boolean"):t.code.endsWith(":identifier")?s.propertyTypes.add("Identifier"):m().endsWith("extension.value.code")||m().endsWith("extension.value.coding.code")?(s.array=!0,s.propertyTypes.add("code")):PA(s,h,e,1),m().endsWith("extension.valueDateTime")&&(s.array=!1)}let c;if(t.code.endsWith(":identifier")){const f=FU(r);if(f===void 0)throw new Error(`Unexpected expression for derived identifier search parameter: ${r}`);const h=hE(e,f);c=HU(r,h)}else c=hE(e,r);const u={type:YU(t,s.propertyTypes),elementDefinitions:s.elementDefinitions,parsedExpression:c,array:s.array};return qU(e,n,u),u}function PA(e,t,n,r){const i=t[r];if(i instanceof $h){e.propertyTypes.add(i.right.toString());return}if(i instanceof ob){QU(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 sb&&(u=!0,f++);const h=t[f];if(c.isArray&&!u&&(e.array=!0),f===t.length-1&&h instanceof $h){e.elementDefinitions.push(c),e.propertyTypes.add(h.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;WU(g)&&(g=c.type[0].code),PA(e,t,g,f)}}function QU(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 ab){e.propertyTypes.add(t.args[0].right.toString());return}throw new Error(`Unhandled FHIRPath function: ${t.name}`)}function WU(e){return e==="Element"||e==="BackboneElement"}function YU(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 KU(e,t){const n=[],r=lb(t);return Uh(e,r.child,n),n}function hE(e,t){const n=[],r=lb(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 ib(i,n[s]);return new rb("<original-not-available>",i)}function Uh(e,t,n){t instanceof ib?(Uh(e,t.left,n),Uh(e,t.right,n)):t.toString().includes(e+".")&&n.push(t)}function Sh(e){if(e instanceof $h||e instanceof sb)return[Sh(e.left),e].flat();if(e instanceof Nr)return[e];if(e instanceof Yp)return[Sh(e.left),Sh(e.right)].flat();if(e instanceof ob){if(e.name==="where"&&!(e.args[0]instanceof ab))return[];if(e.name==="last")return[]}return[e]}const Kp=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"},NA={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},cb={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 OA(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()),XU(i,s)}function XU(e,t){const n={resourceType:e};for(const[r,i]of t)ZU(n,r,i);return n}function ZU(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":JU(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,tB(f,i,n)):e.filters=Lu(e.filters,nB(r,i,n))}}}}function JU(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 eB=[ue.MISSING,ue.PRESENT];function tB(e,t,n){if(eB.includes(t))return{code:e.code,operator:t,value:n};switch(e.type){case"number":case"date":case"quantity":{const{operator:r,value:i}=rB(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:iB(t),value:n};default:throw new Error("Unrecognized search parameter type: "+e.type)}}function nB(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 cb&&(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 rB(e){const t=e.substring(0,2),n=cb[t];return n?{operator:n,value:e.substring(2)}:{operator:ue.EQUALS,value:e}}function iB(e){return NA[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 zh(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(aB(n))),e.sortRules&&e.sortRules.length>0&&t.push(oB(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 aB(e){const t=e.operator in NA?":"+e.operator:"",n=e.operator!==ue.EQUALS&&e.operator in cb?e.operator:"";return`${e.code}${t}=${n}${encodeURIComponent(e.value)}`}function oB(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 ub(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 sB(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters){for(const n of t.filters)if(!lB(e,t,n))return!1}return!0}function lB(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 cB(e,n,r);switch(r.type){case"reference":return uB(e,n,r);case"string":case"uri":return MA(e,n,r);case"token":return dB(e,n,r);case"date":return mB(e,n,r);default:return!1}}function cB(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 uB(e,t,n){const r=Oc(n.expression,e),i=Xp(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 ub(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 dB(e,t,n){return Mc(e.resourceType,n).type===Jn.BOOLEAN?fB(e,t,n):MA(e,t,n,!0)}function fB(e,t,n){const r=Oc(n.expression,e),i=t.value==="true",s=r.includes(i);return Xp(t.operator)?!s:s}function MA(e,t,n,r){var h,m,g,y;const s=(y=(g=(m=(h=Mc(e.resourceType,n).elementDefinitions)==null?void 0:h[0])==null?void 0:m.type)==null?void 0:g[0])==null?void 0:y.code,c=Oc(n.expression,e),u=ub(t.value),f=Xp(t.operator);for(const b of c)for(const S of u){let j;if(s===oe.Identifier?j=hB(b,t.operator,S):s===oe.CodeableConcept?j=pB(b,t.operator,S):j=Ly(b,t.operator,S,r),j)return!f}return f}function Ly(e,t,n,r){if(r&&n.includes("|")){const[s,c]=n.split("|");return Ly(e,t,s,!1)&&(!c||Ly(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 hB(e,t,n){var r,i,s,c;if(n.includes("|")){const[u,f]=n.split("|").map(h=>h.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 pB(e,t,n){var r,i,s,c;if(n.includes("|")){const[u,f]=n.split("|").map(h=>h.toLowerCase());return!u&&!f?!1:u?((i=e.coding)==null?void 0:i.some(h=>{var m,g;return((m=h.system)==null?void 0:m.toLowerCase())===u&&(!f||((g=h.code)==null?void 0:g.toLowerCase())===f)}))??!1:((r=e.coding)==null?void 0:r.some(h=>{var m;return!h.system&&((m=h.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 mB(e,t,n){const r=Oc(n.expression,e),i=ub(t.value),s=Xp(t.operator);for(const c of r)for(const u of i)if(gB(Bh(c),t.operator,Bh(u)))return!s;return s}function gB(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(G$(e))try{return new Date(e).toISOString()}catch(t){console.debug("Failed to parse date",e,t)}else if(yA(e)){if("start"in e)return Bh(e.start);if("end"in e)return Bh(e.end)}}function Xp(e){return e===ue.NOT_EQUALS||e===ue.NOT}const vB={resourceType:"*"},yB=["DomainConfiguration","JsonWebKey","Login"],xB=["PasswordChangeRequest","UserSecurityRequest","Project","ProjectMembership","User"],Ns={READ:"read",VREAD:"vread",UPDATE:"update",HISTORY:"history",SEARCH:"search"},bB=[Ns.READ,Ns.VREAD,Ns.HISTORY,Ns.SEARCH];function SB(e,t){return yB.includes(t)?!1:wB(e,Ns.UPDATE,t)}function wB(e,t,n){var r;return!!((r=e.resource)!=null&&r.some(i=>LA(i,n,t)))}function IA(e,t,n){var r;return n?(r=n.resource)==null?void 0:r.find(i=>jB(e,t,i)):vB}function jB(e,t,n){var i,s;const r=e.resourceType;return!(!LA(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&&!sB(e,OA(n.criteria)))}function LA(e,t,n){return e.resourceType!==t&&(e.resourceType!=="*"||xB.includes(t))?!1:e.interaction?e.interaction.includes(n):!e.readonly||bB.includes(n)}function CB(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 EB(e){e=e.padEnd(e.length+(4-e.length%4)%4,"=");const t=e.replace(/-/g,"+").replace(/_/g,"/");return CB(t)}function yE(){const e=new Uint32Array(28);return crypto.getRandomValues(e),W$(e.buffer)}async function TB(e){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))}function zA(){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 $A(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]=zA(),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)=>RB(s,c,t),2);return DB(JSON.parse(r))}function RB(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 DB(e){const t=_B(e),{sorted:n,cycles:r}=AB(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],h={...f,request:{...f.request,method:"PUT"}};s.push(h)}return{...e,entry:s}}const Kl={NotVisited:"NotVisited",Visiting:"Visiting",Visited:"Visited"};function AB(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 UA(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 UA(r,t)}}function _B(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&&UA(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 kB{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 Zp{constructor(){this.emitter=new kB}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 zy={"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"},PB=["Patient","Encounter","ImagingStudy","DiagnosticReport","OperationOutcome","Bundle"],db=["DiagnosticReport-update"];function NB(e){return db.includes(e)}function OB(e){if(db.includes(e))throw new dt(yn(`'context.version' is required for '${e}'.`))}const MB={"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 IB(e){return PB.includes(e)}function BA(e){return!!e.endpoint}function xE(e){if(!fb(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 BA(e)&&(s.endpoint=e.endpoint),new URLSearchParams(s).toString()}function fb(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(!zy[s])return!1;return!(BA(e)&&!(typeof e.endpoint=="string"&&e.endpoint.startsWith("ws")))}function LB(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(!IB(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 zB(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 LB(e,t.resource,n,r)}function $B(e,t){const n=new Map,r=MB[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.`));zB(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(!zy[t])throw new dt(yn(`Must provide a valid FHIRcast event name. Supported events: ${Object.keys(zy).join(", ")}`));if(typeof n!="object")throw new dt(yn("context must be a context object or array of context objects."));if(db.includes(t)&&!r)throw new dt(yn(`The '${t}' event must contain a 'context.versionId'.`));const i=Array.isArray(n)?n:[n];return $B(t,i),{timestamp:new Date().toISOString(),id:zA(),event:{"hub.topic":e,"hub.event":t,context:i,...r?{"context.versionId":r}:{}}}}class UB extends Zp{constructor(t){if(super(),this.subRequest=t,!t.endpoint)throw new dt(yn("Subscription request should contain an endpoint."));if(!fb(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 BB(e){return JSON.parse(EB(e))}function VB(e){return e.split(".").length===3}function hb(e){const[t,n,r]=e.split(".");return BB(n)}function FB(e){try{return typeof hb(e).login_id=="string"}catch{return!1}}function HB(e){try{const n=hb(e).exp;return typeof n=="number"?n*1e3:void 0}catch{return}}class qB{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 VA;VA=Symbol.toStringTag;class Ai{constructor(t){this[VA]="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 GB{constructor(t){this.storage=t??(typeof localStorage<"u"?localStorage:new QB)}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 QB{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 f3(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 WB(){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 YB(e,t){if(!e)throw new Error(t)}function oh(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 Zp{constructor(t,n,r={}){SE||(WB(),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),YB(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(oh(i))},this._handleMessage=i=>{this._debug("message event"),this.onmessage&&this.onmessage(i),this.dispatchEvent(oh(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(oh(i)),this._connect()},this._handleClose=i=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(i),this.dispatchEvent(oh(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 KB=5e3;class $y extends Zp{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 XB{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new $y(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class ZB{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof HA))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 $y,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??KB,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,i,s,c,u,f;try{const h=JSON.parse(n.data);if(h.type==="pong"){this.waitingForPong=!1;return}const m=h,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(h){console.error(h);const m={type:"error",payload:h};(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(l$(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 h=f.subscriptionProps;return!sa(r,h)}):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 XB(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 $y(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const FA="4.1.13-651e0907f",JB=hn.FHIR_JSON+", */*; q=0.1",eV="https://api.medplum.com/",tV=1e3,nV=6e4,rV=0,iV=3e5,aV="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"},oV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},sV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class HA extends Zp{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)??lV(),this.storage=(t==null?void 0:t.storage)??new GB,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=tb((t==null?void 0:t.baseUrl)??eV),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)??iV,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?rV:nV),this.cacheTime>0?this.requestCache=new iA((t==null?void 0:t.resourceCacheSize)??tV):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:oV.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=tU(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 h,m;return(m=(h=f.entry)==null?void 0:h[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),h=(s=f.link)==null?void 0:s.find(m=>m.relation==="next");if(!((c=f.entry)!=null&&c.length)&&!h)break;yield TE(f),i=h!=null&&h.url?new URL(h.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(dA(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 WB(){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 YB(e,t){if(!e)throw new Error(t)}function oh(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 Zp{constructor(t,n,r={}){SE||(WB(),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),YB(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(oh(i))},this._handleMessage=i=>{this._debug("message event"),this.onmessage&&this.onmessage(i),this.dispatchEvent(oh(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(oh(i)),this._connect()},this._handleClose=i=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(i),this.dispatchEvent(oh(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 KB=5e3;class $y extends Zp{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 XB{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new $y(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class ZB{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof HA))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 $y,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??KB,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,i,s,c,u,f;try{const h=JSON.parse(n.data);if(h.type==="pong"){this.waitingForPong=!1;return}const m=h,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(h){console.error(h);const m={type:"error",payload:h};(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(l8(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 h=f.subscriptionProps;return!sa(r,h)}):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 XB(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 $y(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const FA="4.1.14-8896f73",JB=hn.FHIR_JSON+", */*; q=0.1",eV="https://api.medplum.com/",tV=1e3,nV=6e4,rV=0,iV=3e5,aV="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"},oV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},sV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class HA extends Zp{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)??lV(),this.storage=(t==null?void 0:t.storage)??new GB,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=tb((t==null?void 0:t.baseUrl)??eV),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)??iV,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?rV:nV),this.cacheTime>0?this.requestCache=new iA((t==null?void 0:t.resourceCacheSize)??tV):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:oV.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=tU(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 h,m;return(m=(h=f.entry)==null?void 0:h[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),h=(s=f.link)==null?void 0:s.find(m=>m.relation==="next");if(!((c=f.entry)!=null&&c.length)&&!h)break;yield TE(f),i=h!=null&&h.url?new URL(h.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(dA(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,
|
|
@@ -123,7 +123,7 @@ function f3(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
|
|
|
123
123
|
expression,
|
|
124
124
|
target
|
|
125
125
|
}
|
|
126
|
-
}`.replace(/\s+/g," "),c=await this.graphql(s);rE(c.data.StructureDefinitionList);for(const u of c.data.SearchParameterList)fU(u)})());return this.setCacheEntry(n,i),i}requestProfileSchema(t,n){if(!(n!=null&&n.expandProfile)&&K0(t))return Promise.resolve();const r=t+"-requestSchema"+(n!=null&&n.expandProfile?"-nested":""),i=this.getCacheEntry(r,void 0);if(i)return i.value;const s=new Ai((async()=>{if(n!=null&&n.expandProfile){const c=this.fhirUrl("StructureDefinition","$expand-profile");c.search=new URLSearchParams({url:t}).toString();const u=await this.post(c.toString(),{});rE(u)}else{const c=await this.searchOne("StructureDefinition",{url:t,_sort:"-_lastUpdated"});if(!c){console.warn(`No StructureDefinition found for ${t}!`);return}uA(c)}})());return this.setCacheEntry(r,s),s}readHistory(t,n,r){return this.get(this.fhirUrl(t,n,"_history"),r)}readVersion(t,n,r,i){return this.get(this.fhirUrl(t,n,"_history",r),i)}readPatientEverything(t,n){return this.getBundle(this.fhirUrl("Patient",t,"$everything"),n)}readPatientSummary(t,n){return this.getBundle(this.fhirUrl("Patient",t,"$summary"),n)}createResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(t.resourceType),this.post(this.fhirUrl(t.resourceType),t,void 0,n)}async createResourceIfNoneExist(t,n,r){const i=this.fhirUrl(t.resourceType);r?r.headers?Array.isArray(r.headers)?r.headers.push(["If-None-Exist",n]):r.headers instanceof Headers?r.headers.set("If-None-Exist",n):r.headers["If-None-Exist"]=n:r.headers={"If-None-Exist":n}:r={headers:{"If-None-Exist":n}};const s=await this.post(i,t,void 0,r);return this.cacheResource(s),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),s}async upsertResource(t,n,r){const i=this.fhirSearchUrl(t.resourceType,n);let s=await this.put(i,t,void 0,r);return s||(s=t),this.cacheResource(s),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),s}async createAttachment(t,n,r,i,s){let c=RE(t,n,r,i);if(c.contentType===hn.XML){const h=c.data;let m;h instanceof Blob?m=await new Promise((g,y)=>{const b=new FileReader;b.onload=()=>{if(!b.result){y(new Error("Failed to load file"));return}g(b.result)},b.readAsText(h,"utf-8")}):ArrayBuffer.isView(h)?m=new TextDecoder().decode(h):m=h,m.includes("<ClinicalDocument")&&m.includes("urn:hl7-org:v3")&&(c={...c,contentType:hn.CDA_XML})}const u=s??(typeof n=="object"?n:{}),f=await this.createBinary(c,u);return{contentType:c.contentType,url:f.url,title:c.filename}}createBinary(t,n,r,i,s){const c=RE(t,n,r,i),u=s??(typeof n=="object"?n:{}),{data:f,contentType:h,filename:m,securityContext:g,onProgress:y}=c,b=this.fhirUrl("Binary");return m&&b.searchParams.set("_filename",m),g!=null&&g.reference&&this.setRequestHeader(u,"X-Security-Context",g.reference),y?this.uploadwithProgress(b,f,h,y,u):this.post(b,f,h,u)}uploadwithProgress(t,n,r,i,s){return new Promise((c,u)=>{var g;const f=new XMLHttpRequest,h=()=>f.abort();(g=s==null?void 0:s.signal)==null||g.addEventListener("abort",h);const m=y=>{var b;(b=s==null?void 0:s.signal)==null||b.removeEventListener("abort",h),y instanceof Error?u(y):c(y)};if(f.responseType="json",f.onabort=()=>m(new DOMException("Request aborted","AbortError")),f.onerror=()=>m(new Error("Request error")),i&&(f.upload.onprogress=y=>i(y),f.upload.onload=y=>i(y)),f.onload=()=>{f.status>=200&&f.status<300?m(f.response):m(new dt(Zt(f.response||f.statusText)))},f.open("POST",t),f.withCredentials=!0,f.setRequestHeader("Authorization","Bearer "+this.accessToken),f.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),f.setRequestHeader("Content-Type",r),this.options.extendedMode!==!1&&f.setRequestHeader("X-Medplum","extended"),s!=null&&s.headers){const y=s.headers;for(const[b,S]of Object.entries(y))f.setRequestHeader(b,S)}f.send(n)})}async createPdf(t,n,r,i){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");const s=dV(t,n,r,i),c=typeof n=="object"?n:{},{docDefinition:u,tableLayouts:f,fonts:h,...m}=s,g=await this.createPdfImpl(u,f,h),y={...m,data:g,contentType:"application/pdf"};return this.createBinary(y,c)}createComment(t,n,r){const i=this.getProfile();let s,c;return t.resourceType==="Encounter"&&(s=on(t),c=t.subject),t.resourceType==="ServiceRequest"&&(s=t.encounter,c=t.subject),t.resourceType==="Patient"&&(c=on(t)),this.createResource({resourceType:"Communication",status:"completed",basedOn:[on(t)],encounter:s,subject:c,sender:i?on(i):void 0,sent:new Date().toISOString(),payload:[{contentString:n}]},r)}async updateResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");if(!t.id)throw new Error("Missing id");let r=await this.put(this.fhirUrl(t.resourceType,t.id),t,void 0,n);return r||(r=t),this.cacheResource(r),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),r}async patchResource(t,n,r,i){const s=await this.patch(this.fhirUrl(t,n),r,i);return this.cacheResource(s),this.invalidateUrl(this.fhirUrl(t,n,"_history")),this.invalidateSearches(t),s}deleteResource(t,n,r){return this.deleteCacheEntry(this.fhirUrl(t,n).toString()),this.invalidateSearches(t),this.delete(this.fhirUrl(t,n),r)}validateResource(t,n){return this.post(this.fhirUrl(t.resourceType,"$validate"),t,void 0,n)}executeBot(t,n,r,i){let s;if(typeof t=="string"){const c=t;s=this.fhirUrl("Bot",c,"$execute")}else{const c=t;s=this.fhirUrl("Bot","$execute"),s.searchParams.set("identifier",c.system+"|"+c.value)}return this.post(s,n,r,i)}executeBatch(t,n){return this.post(this.fhirBaseUrl,t,void 0,n)}sendEmail(t,n){return this.post("email/v1/send",t,hn.JSON,n)}graphql(t,n,r,i){return this.post(this.fhirUrl("$graphql"),{query:t,operationName:n,variables:r},hn.JSON,i)}readResourceGraph(t,n,r,i){return this.get(`${this.fhirUrl(t,n)}/$graph?graph=${r}`,i)}pushToAgent(t,n,r,i,s,c){return this.post(this.fhirUrl("Agent",Bs(t),"$push"),{destination:typeof n=="string"?n:zt(n),body:r,contentType:i,waitForResponse:s},hn.FHIR_JSON,c)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(t){var n,r;(!((n=this.sessionDetails)!=null&&n.profile)||zt(this.sessionDetails.profile)!==((r=t.profile)==null?void 0:r.reference))&&this.clearActiveLogin(),this.setAccessToken(t.accessToken,t.refreshToken),this.storage.setObject("activeLogin",t),this.addLogin(t),this.refreshPromise=void 0,await this.refreshProfile()}getAccessToken(){return this.accessToken}isAuthenticated(t){return this.accessTokenExpires!==void 0&&Date.now()<this.accessTokenExpires-(t??this.refreshGracePeriod)}setAccessToken(t,n){this.accessToken=t,this.refreshToken=n,this.accessTokenExpires=HB(t),this.medplumServer=FB(t)}getLogins(){return this.storage.getObject("logins")??[]}addLogin(t){const n=this.getLogins().filter(r=>{var i,s;return((i=r.profile)==null?void 0:i.reference)!==((s=t.profile)==null?void 0:s.reference)});n.push(t),this.storage.setObject("logins",n)}async refreshProfile(){return this.medplumServer?(this.profilePromise=new Promise((t,n)=>{this.get("auth/me",{cache:"no-cache"}).then(r=>{var s,c;this.profilePromise=void 0;const i=((c=(s=this.sessionDetails)==null?void 0:s.profile)==null?void 0:c.id)!==r.profile.id;this.sessionDetails=r,i&&this.dispatchEvent({type:"change"}),t(r.profile),this.dispatchEvent({type:"profileRefreshed"})}).catch(n)}),this.dispatchEvent({type:"profileRefreshing"}),this.profilePromise):Promise.resolve(void 0)}isLoading(){var t;return!this.isInitialized||!!this.profilePromise&&!((t=this.sessionDetails)!=null&&t.profile)}isSuperAdmin(){var t;return!!((t=this.sessionDetails)!=null&&t.project.superAdmin)}isProjectAdmin(){var t;return!!((t=this.sessionDetails)!=null&&t.membership.admin)}getProject(){var t;return(t=this.sessionDetails)==null?void 0:t.project}getProjectMembership(){var t;return(t=this.sessionDetails)==null?void 0:t.membership}getProfile(){var t;return(t=this.sessionDetails)==null?void 0:t.profile}async getProfileAsync(){return this.profilePromise?this.profilePromise:this.sessionDetails?this.sessionDetails.profile:this.refreshProfile()}getUserConfiguration(){var t;return(t=this.sessionDetails)==null?void 0:t.config}getAccessPolicy(){var t;return(t=this.sessionDetails)==null?void 0:t.accessPolicy}async download(t,n={}){this.refreshPromise&&await this.refreshPromise;const r=t.toString();r.startsWith(aV)&&(t=this.fhirUrl(r));let i=n.headers;return i||(i={},n.headers=i),i.Accept||(i.Accept="*/*"),this.addFetchOptionsDefaults(n),(await this.fetchWithRetry(t.toString(),n)).blob()}async createMedia(t,n){const{additionalFields:r,...i}=t,s=await this.createResource({resourceType:"Media",status:"preparation",content:{contentType:t.contentType},...r});i.securityContext||(i.securityContext=on(s));const c=await this.createAttachment(i,n);return this.updateResource({...s,status:"completed",content:c})}async uploadMedia(t,n,r,i,s){return this.createMedia({data:t,contentType:n,filename:r,additionalFields:i},s)}async createDocumentReference(t,n){const{additionalFields:r,...i}=t,s=await this.createResource({resourceType:"DocumentReference",status:"current",content:[{attachment:{contentType:t.contentType}}],...r});i.securityContext||(i.securityContext=on(s));const c=await this.createAttachment(i,n);return this.updateResource({...s,content:[{attachment:c}]})}async bulkExport(t="",n,r,i){const s=t&&`${t}/`,c=this.fhirUrl(`${s}$export`);return n&&c.searchParams.set("_type",n),r&&c.searchParams.set("_since",r),this.startAsyncRequest(c.toString(),i)}async startAsyncRequest(t,n={}){this.addFetchOptionsDefaults(n);const r=n.headers;return r.Prefer="respond-async",this.request("POST",t,n)}get keyValue(){return this.keyValueClient||(this.keyValueClient=new qB(this)),this.keyValueClient}getBundle(t,n){return new Ai((async()=>{const r=await this.get(t,n);if(r.entry)for(const i of r.entry)this.cacheResource(i.resource);return r})())}getCacheEntry(t,n){if(!this.requestCache||(n==null?void 0:n.cache)==="no-cache"||(n==null?void 0:n.cache)==="reload")return;const r=this.requestCache.get(t);if(!(!r||r.requestTime+this.cacheTime<Date.now()))return r}setCacheEntry(t,n){this.requestCache&&this.requestCache.set(t,{requestTime:Date.now(),value:n})}cacheResource(t){var n,r;t!=null&&t.id&&!((r=(n=t.meta)==null?void 0:n.tag)!=null&&r.some(i=>i.code==="SUBSETTED"))&&this.setCacheEntry(this.fhirUrl(t.resourceType,t.id).toString(),new Ai(Promise.resolve(t)))}deleteCacheEntry(t){this.requestCache&&this.requestCache.delete(t)}async request(t,n,r={},i={}){await this.refreshIfExpired(),r.method=t,this.addFetchOptionsDefaults(r);const s=await this.fetchWithRetry(n,r);if(s.status===401)return this.handleUnauthenticated(t,n,r);if(s.status===204||s.status===304)return;const c=s.headers.get("content-type"),u=c==null?void 0:c.includes("json");if(s.status===404&&!u)throw new dt(o$);const f=await this.parseBody(s,u);if(s.status===200&&r.followRedirectOnOk||s.status===201&&r.followRedirectOnCreated){const h=await EE(s,f);if(h)return this.request("GET",h,{...r,body:void 0})}if(s.status===202&&r.pollStatusOnAccepted){const m=await EE(s,f)??i.statusUrl;if(m)return this.pollStatus(m,r,i)}if(s.status>=400)throw new dt(Zt(f));return f}async parseBody(t,n){let r;if(t.headers.get("content-length")!=="0"){if(n)try{r=await t.json()}catch(i){throw console.error("Error parsing response",t.status,i),i}else r=await t.text();return r}}async fetchWithRetry(t,n){t.startsWith("http")||(t=Xi(this.baseUrl,t));const r=(n==null?void 0:n.maxRetries)??2;for(let i=0;i<=r;i++)try{this.options.verbose&&this.logRequest(t,n);const s=await this.fetch(t,n);if(this.options.verbose&&this.logResponse(s),this.setCurrentRateLimit(s),i>=r||!fV(s))return s;const c=this.getRetryDelay(i),u=n.maxRetryTime??2e3;if(c>u)return s;await dE(c)}catch(s){if(s.message==="Failed to fetch"&&i===0&&this.dispatchEvent({type:"offline"}),s.name==="AbortError"||i===r)throw s}throw new Error("Unreachable")}logRequest(t,n){if(console.log(`> ${n.method} ${t}`),n.headers){const r=n.headers;for(const i of ad(Object.keys(r)))console.log(`> ${i}: ${r[i]}`)}}logResponse(t){console.log(`< ${t.status} ${t.statusText}`),t.headers&&t.headers.forEach((n,r)=>console.log(`< ${r}: ${n}`))}setCurrentRateLimit(t){var r;const n=(r=t.headers)==null?void 0:r.get("ratelimit");n&&(this.currentRateLimits=n)}rateLimitStatus(){if(!this.currentRateLimits)return[];const t=this.currentRateLimits;return t.split(/\s*;\s*/g).map(n=>{const r=n.split(/\s*,\s*/g);if(r.length!==3)throw new Error("Could not parse RateLimit header: "+t);const i=r[0].substring(1,r[0].length-1),s=r.find(h=>h.startsWith("r=")),c=s?parseInt(s.substring(2),10):NaN,u=r.find(h=>h.startsWith("t=")),f=u?parseInt(u.substring(2),10):NaN;if(!i||Number.isNaN(c)||Number.isNaN(f))throw new Error("Could not parse RateLimit header: "+t);return{name:i,remainingUnits:c,secondsUntilReset:f}})}getRetryDelay(t){const n=this.rateLimitStatus();let r=500*Math.pow(1.5,t);for(const i of n)i.remainingUnits||(r=Math.max(r,i.secondsUntilReset*1e3));return r}async pollStatus(t,n,r){const i={...n,method:"GET",body:void 0,redirect:"follow"};if(r.pollCount===void 0)n.headers&&typeof n.headers=="object"&&"Prefer"in n.headers&&(i.headers={...n.headers},delete i.headers.Prefer),r.statusUrl=t,r.pollCount=1;else{const s=n.pollStatusPeriod??1e3;await dE(s),r.pollCount++}return this.request("GET",t,i,r)}async executeAutoBatch(){var i,s;if(this.autoBatchQueue===void 0)return;const t=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,t.length===1){const c=t[0];try{c.resolve(await this.request(c.method,Xi(this.fhirBaseUrl,c.url),c.options))}catch(u){c.reject(new dt(Zt(u)))}return}const n={resourceType:"Bundle",type:"batch",entry:t.map(c=>({request:{method:c.method,url:c.url},resource:c.options.body?JSON.parse(c.options.body):void 0}))},r=await this.post(this.fhirBaseUrl,n);for(let c=0;c<t.length;c++){const u=t[c],f=(i=r.entry)==null?void 0:i[c];(s=f==null?void 0:f.response)!=null&&s.outcome&&!oA(f.response.outcome)?u.reject(new dt(f.response.outcome)):u.resolve(f==null?void 0:f.resource)}}addFetchOptionsDefaults(t){Object.entries(this.defaultHeaders).forEach(([n,r])=>{this.setRequestHeader(t,n,r)}),this.setRequestHeader(t,"Accept",JB,!0),this.options.extendedMode!==!1&&this.setRequestHeader(t,"X-Medplum","extended"),t.body&&this.setRequestHeader(t,"Content-Type",hn.FHIR_JSON,!0),this.accessToken?this.setRequestHeader(t,"Authorization","Bearer "+this.accessToken):this.basicAuth&&this.setRequestHeader(t,"Authorization","Basic "+this.basicAuth),t.cache||(t.cache="no-cache"),t.credentials||(t.credentials="include")}setRequestContentType(t,n){this.setRequestHeader(t,"Content-Type",n)}setRequestHeader(t,n,r,i=!1){t.headers||(t.headers={});const s=t.headers;i&&s[n]||(s[n]=r)}setRequestBody(t,n){typeof n=="string"||typeof Blob<"u"&&(n instanceof Blob||(n==null?void 0:n.constructor.name)==="Blob")||typeof File<"u"&&(n instanceof File||(n==null?void 0:n.constructor.name)==="File")||typeof Uint8Array<"u"&&(n instanceof Uint8Array||(n==null?void 0:n.constructor.name)==="Uint8Array")?t.body=n:n&&(t.body=JSON.stringify(n))}handleUnauthenticated(t,n,r){return this.refresh()?this.request(t,n,r):(this.clear(),this.onUnauthenticated&&this.onUnauthenticated(),Promise.reject(new dt(id)))}async startPkce(){const t=yE();sessionStorage.setItem("pkceState",t);const n=yE().slice(0,128);sessionStorage.setItem("codeVerifier",n);const r=await TB(n),i=Y8(r).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return sessionStorage.setItem("codeChallenge",i),{codeChallengeMethod:"S256",codeChallenge:i}}async requestAuthorization(t){const n=await this.ensureCodeChallenge(t??{}),r=new URL(this.authorizeUrl);r.searchParams.set("response_type","code"),r.searchParams.set("state",sessionStorage.getItem("pkceState")),r.searchParams.set("client_id",n.clientId??this.clientId),r.searchParams.set("redirect_uri",n.redirectUri??CE()),r.searchParams.set("code_challenge_method",n.codeChallengeMethod),r.searchParams.set("code_challenge",n.codeChallenge),r.searchParams.set("scope",n.scope??"openid profile"),window.location.assign(r.toString())}processCode(t,n){const r={grant_type:Xl.AuthorizationCode,code:t,client_id:(n==null?void 0:n.clientId)??this.clientId??"",redirect_uri:(n==null?void 0:n.redirectUri)??CE()};if(typeof sessionStorage<"u"){const i=sessionStorage.getItem("codeVerifier");i&&(r.code_verifier=i)}return this.fetchTokens(r)}refreshIfExpired(t){return!this.refreshPromise&&this.accessTokenExpires!==void 0&&!this.isAuthenticated(t)&&this.refresh(),this.refreshPromise??Promise.resolve()}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken)return this.refreshPromise=this.fetchTokens({grant_type:Xl.RefreshToken,client_id:this.clientId??"",refresh_token:this.refreshToken}),this.refreshPromise;if(this.clientId&&this.clientSecret)return this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise}async startClientLogin(t,n){return this.clientId=t,this.clientSecret=n,this.fetchTokens({grant_type:Xl.ClientCredentials,client_id:t,client_secret:n})}async startJwtBearerLogin(t,n,r){return this.clientId=t,this.fetchTokens({grant_type:Xl.JwtBearer,client_id:t,assertion:n,scope:r})}async startJwtAssertionLogin(t){return this.fetchTokens({grant_type:Xl.ClientCredentials,client_assertion_type:sV.JwtBearer,client_assertion:t})}setBasicAuth(t,n){this.clientId=t,this.clientSecret=n,this.basicAuth=vE(t+":"+n)}async fhircastSubscribe(t,n){if(!(typeof t=="string"&&t!==""))throw new dt(yn("Invalid topic provided. Topic must be a valid string."));if(!(typeof n=="object"&&Array.isArray(n)&&n.length>0))throw new dt(yn("Invalid events provided. Events must be an array of event names containing at least one event."));const r={channelType:"websocket",mode:"subscribe",topic:t,events:n},s=(await this.post(this.fhircastHubUrl,xE(r),hn.FORM_URL_ENCODED))["hub.channel.endpoint"];if(!s)throw new Error("Invalid response!");return r.endpoint=s,r}async fhircastUnsubscribe(t){if(!fb(t))throw new dt(yn("Invalid topic or subscriptionRequest. SubscriptionRequest must be an object."));if(!(t.endpoint&&typeof t.endpoint=="string"&&t.endpoint.startsWith("ws")))throw new dt(yn("Provided subscription request must have an endpoint in order to unsubscribe."));t.mode="unsubscribe",await this.post(this.fhircastHubUrl,xE(t),hn.FORM_URL_ENCODED)}fhircastConnect(t){return new UB(t)}async fhircastPublish(t,n,r,i){return NB(n)?this.post(this.fhircastHubUrl,bE(t,n,r,i),hn.JSON):(OB(n),this.post(this.fhircastHubUrl,bE(t,n,r),hn.JSON))}async fhircastGetContext(t){return this.get(`${this.fhircastHubUrl}/${t}`,{cache:"no-cache"})}async invite(t,n){return this.post("admin/projects/"+t+"/invite",n)}async fetchTokens(t){const n=new URLSearchParams(t),r={...this.defaultHeaders,"Content-Type":hn.FORM_URL_ENCODED};this.basicAuth&&(r.Authorization=`Basic ${this.basicAuth}`),this.credentialsInHeader&&(n.delete("client_id"),n.delete("client_secret"),!this.basicAuth&&t.client_id&&t.client_secret&&(r.Authorization=`Basic ${vE(t.client_id+":"+t.client_secret)}`));const i={method:"POST",headers:r,body:n.toString(),credentials:"include"};let s;try{s=await this.fetchWithRetry(this.tokenUrl,i)}catch(u){throw this.refreshPromise=void 0,u}if(!s.ok){this.clearActiveLogin();try{const u=await s.json();throw new dt(ra(u.error_description))}catch(u){throw new dt(ra("Failed to fetch tokens"),u)}}const c=await s.json();return await this.verifyTokens(c),this.getProfile()}async verifyTokens(t){const n=t.access_token;if(VB(n)){const r=hb(n);if(Date.now()>=r.exp*1e3)throw this.clearActiveLogin(),new dt(s$);if(r.cid){if(r.cid!==this.clientId)throw this.clearActiveLogin(),new dt(tE)}else if(this.clientId&&r.client_id!==this.clientId)throw this.clearActiveLogin(),new dt(tE)}return this.setActiveLogin({accessToken:n,refreshToken:t.refresh_token,project:t.project,profile:t.profile})}checkSessionDetailsMatchLogin(t){var n,r;return this.sessionDetails&&t?((r=(n=t.profile)==null?void 0:n.reference)==null?void 0:r.endsWith(this.sessionDetails.profile.id))??!1:!0}setupStorageListener(){try{window.addEventListener("storage",t=>{if(t.key===null)window.location.reload();else if(t.key==="activeLogin"){const n=t.oldValue?JSON.parse(t.oldValue):void 0,r=t.newValue?JSON.parse(t.newValue):void 0;(n==null?void 0:n.profile.reference)!==(r==null?void 0:r.profile.reference)||!this.checkSessionDetailsMatchLogin(r)?window.location.reload():r?this.setAccessToken(r.accessToken,r.refreshToken):this.clear()}})}catch{}}getSubscriptionManager(){return this.subscriptionManager||(this.subscriptionManager=new ZB(this,eU(this.baseUrl,"/ws/subscriptions-r4"))),this.subscriptionManager}subscribeToCriteria(t,n){return this.getSubscriptionManager().addCriteria(t,n)}unsubscribeFromCriteria(t,n){this.subscriptionManager&&(this.subscriptionManager.removeCriteria(t,n),this.subscriptionManager.getCriteriaCount()===0&&this.subscriptionManager.closeWebSocket())}getMasterSubscriptionEmitter(){return this.getSubscriptionManager().getMasterEmitter()}}function lV(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}function CE(){return typeof window>"u"?"":window.location.protocol+"//"+window.location.host+"/"}async function EE(e,t){var i,s;const n=e.headers.get("content-location");if(n)return n;const r=e.headers.get("location");if(r)return r;if(qp(t)&&((s=(i=t.issue)==null?void 0:i[0])!=null&&s.diagnostics))return t.issue[0].diagnostics}function TE(e){var n;const t=((n=e.entry)==null?void 0:n.map(r=>r.resource))??[];return Object.assign(t,{bundle:e})}function cV(e){return sr(e)&&"data"in e&&"contentType"in e}function RE(e,t,n,r){return cV(e)?e:{data:e,filename:t,contentType:n,onProgress:r}}function uV(e){return sr(e)&&"docDefinition"in e}function dV(e,t,n,r){return uV(e)?e:{docDefinition:e,filename:t,tableLayouts:n,fonts:r}}function fV(e){return e.status===429||e.status>=500}function yc({parentContext:e,path:t,elements:n,profileUrl:r,debugMode:i,accessPolicyResource:s}){if(t===(e==null?void 0:e.path))return;i??(i=(e==null?void 0:e.debugMode)??!1),s??(s=e==null?void 0:e.accessPolicyResource);let c=hV(t,n,e,!!i);const u=Iy(t,".",2)[1];c=pV(c,s,u),c=mV(c,s,u);const f=Object.create(null);for(const[m,g]of Object.entries(c))f[t+"."+m]=g;let h;if(e&&!e.isDefaultContext)h=e.getExtendedProps;else{const m=Object.create(null);h=g=>{const y=Iy(g,".",2)[1];if(y){if(!m[y]){const b=Vh(y,s==null?void 0:s.hiddenFields);m[y]={hidden:b,readonly:b||Vh(y,s==null?void 0:s.readonlyFields)}}return m[y]}}}return{path:t,elements:c,elementsByPath:f,profileUrl:r??(e==null?void 0:e.profileUrl),debugMode:i,getExtendedProps:h,accessPolicyResource:s}}function hV(e,t,n,r){const i=Object.create(null);if(n)for(const[c,u]of Object.entries(n.elementsByPath)){const f=ks(e,c);f!==void 0&&(i[f]=u)}let s=!1;if(t)for(const[c,u]of Object.entries(t))c in i||(i[c]=u,s=!0);return r&&console.assert(s,"Unnecessary ElementsContext; not using any newly provided elements"),i}function pV(e,t,n){var i;if(!((i=t==null?void 0:t.hiddenFields)!=null&&i.length))return e;const r=n?n+".":"";return Object.fromEntries(Object.entries(e).filter(([s])=>!Vh(r+s,t.hiddenFields)))}function mV(e,t,n){var s;if(!((s=t==null?void 0:t.readonlyFields)!=null&&s.length))return e;const r=Object.create(null),i=n?n+".":"";for(const[c,u]of Object.entries(e))Vh(i+c,t.readonlyFields)?r[c]={...u,readonly:!0}:r[c]=u;return r}function Vh(e,t){if(!(t!=null&&t.length))return!1;const n=e.split(".");for(let r=1;r<=n.length;r++){const i=n.slice(0,r).join(".");if(t.includes(i))return!0}return!1}function qA(e){return e.type!==void 0&&e.type.length>0}function gV(e,t,n,r){var s;const i=C8(e,t.path,{profileUrl:r});if(i){const c=((s=n.typeSchema)==null?void 0:s.elements)??n.elements;return i.some(u=>R8(u,t,n,c))??!1}return console.assert(!1,"getNestedProperty[%s] in isDiscriminatorComponentMatch missed",t.path),!1}function GA(e,t,n,r){var i,s;if(e)for(const c of t){const u={value:e,type:((i=c.typeSchema)==null?void 0:i.type)??((s=c.type)==null?void 0:s[0].code)};if(n.every(f=>{var h;return gV(u,f,c,((h=c.typeSchema)==null?void 0:h.url)??r)}))return c.name}}class vV{constructor(t,n,r){if(t.type===void 0)throw new Error("schema must include a type");this.rootSchema=t;const i=yc({parentContext:void 0,path:this.rootSchema.type,elements:r??this.rootSchema.elements,profileUrl:this.rootSchema.name===this.rootSchema.type?void 0:this.rootSchema.url});if(i===void 0)throw new Error("Could not create root elements context");this.elementsContextStack=[i],this.visitor=n}get elementsContext(){return this.elementsContextStack[this.elementsContextStack.length-1]}crawlElement(t,n,r){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema);const i=Object.fromEntries(Object.entries(this.elementsContext.elements).filter(([s])=>s.startsWith(n)));this.crawlElementsImpl(i,r),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlSlice(t,n,r){const i=this.prepareSlices(r.slices,r);if(!Tn(i.slices))throw new Error(`cannot crawl slice ${n.name} since it has no type information`);this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.sliceAllowList=[n],this.crawlSliceImpl(i.slices[0],n.path,i),this.sliceAllowList=void 0,this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlResource(){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.crawlElementsImpl(this.rootSchema.elements,this.rootSchema.type),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlElementsImpl(t,n){const r=yV(t);for(const i of r)this.crawlElementNode(i,n)}crawlElementNode(t,n){var i,s;const r=n+"."+t.key;this.visitor.onEnterElement&&this.visitor.onEnterElement(r,t.element,this.elementsContext);for(const c of t.children)this.crawlElementNode(c,n);Tn((s=(i=t.element)==null?void 0:i.slicing)==null?void 0:s.slices)&&this.crawlSlicingImpl(t.element.slicing,r),this.visitor.onExitElement&&this.visitor.onExitElement(r,t.element,this.elementsContext)}prepareSlices(t,n){var s,c;const r=[];for(const u of t){if(!qA(u))continue;const f=(c=(s=u.type.find(h=>Tn(h.profile)))==null?void 0:s.profile)==null?void 0:c[0];if(Tn(f)){const h=Pc(f);h&&(u.typeSchema=h)}r.push(u)}return{...n,slices:r}}crawlSlicingImpl(t,n){const r=this.prepareSlices(t.slices,t);for(const i of r.slices)(this.sliceAllowList===void 0||this.sliceAllowList.includes(i))&&this.crawlSliceImpl(i,n,r)}crawlSliceImpl(t,n,r){const i=t.typeSchema;i&&this.visitor.onEnterSchema&&this.visitor.onEnterSchema(i),this.visitor.onEnterSlice&&this.visitor.onEnterSlice(n,t,r);let s;const c=(i==null?void 0:i.elements)??t.elements;Tn(c)&&(s=yc({path:n,parentContext:this.elementsContext,elements:c})),s&&this.elementsContextStack.push(s),this.crawlElementsImpl(c,n),s&&this.elementsContextStack.pop(),this.visitor.onExitSlice&&this.visitor.onExitSlice(n,t,r),i&&this.visitor.onExitSchema&&this.visitor.onExitSchema(i)}}function yV(e){const t=[];function n(s,c){return c.startsWith(s+".")}function r(s,c){for(const u of s.children)if(n(u.key,c.key)){r(u,c);return}s.children.push(c)}const i=Object.entries(e);i.sort((s,c)=>s[0].localeCompare(c[0]));for(const[s,c]of i){const u={key:s,element:c,children:[]};let f=!1;for(const h of t)if(n(h.key,s)){r(h,u),f=!0;break}f||t.push(u)}return t}const Qv="__sliceName";function xV(e,t){const n=new bV(e,e.resourceType,"resource");return new vV(t,n).crawlResource(),n.getDefaultValue()}function DE(e,t,n){for(const[r,i]of Object.entries(t)){if(n===void 0||n===r){Fh(e,r,i,t);continue}const s=ks(n,r);s!==void 0&&Fh(e,s,i,t)}return e}class bV{constructor(t,n,r){this.schemaStack=[],this.valueStack=[],this.rootValue=Qr(t),this.valueStack.splice(0,this.valueStack.length,{type:r,path:n,values:[this.rootValue]})}get schema(){return this.schemaStack[this.schemaStack.length-1]}get value(){return this.valueStack[this.valueStack.length-1]}onEnterSchema(t){this.schemaStack.push(t)}onExitSchema(){this.schemaStack.pop()}onEnterElement(t,n,r){const i=this.value.values,s=this.value.path,c=ks(s,t);if(c===void 0)throw new Error(`Expected ${t} to be prefixed by ${s}`);const u=[];for(const f of i){if(f===void 0)continue;const h=ks(r.path,s),m=Array.isArray(f)?f:[f];for(const g of m){SV(g,c,n,r.elements,h),Fh(g,c,n,r.elements);const y=By(g,c,r.elements,h);y!==void 0&&u.push(y)}}this.valueStack.push({type:"element",path:t,values:u})}onExitElement(t,n,r){if(!this.valueStack.pop())throw new Error("Expected value context to exist when exiting element");const s=ks(this.value.path,t);if(s===void 0)throw new Error(`Expected ${t} to be prefixed by ${this.value.path}`);const c=ks(r.path,this.value.path);for(const u of this.value.values){const f=By(u,s,r.elements,c);if(Array.isArray(f))for(let h=f.length-1;h>=0;h--){const m=f[h];Tn(m)||f.splice(h,1)}Rn(f)&&Uy(u,void 0,s,n)}}onEnterSlice(t,n,r){const i=this.value.values,s=[];for(const c of i)if(c!==void 0){const u=Array.isArray(c)?c:[c],f=this.getMatchingSliceValues(u,n,r);s.push(f)}this.valueStack.push({type:"slice",path:t,values:s})}getMatchingSliceValues(t,n,r){const i=[];for(const s of t)(s[Qv]??GA(s,[n],r.discriminator,this.schema.url))===n.name&&i.push(s);for(let s=i.length;s<n.min;s++)if(eb(n.type[0].code)){const c=Object.create(null);i.push(c),t.push(c)}return i}onExitSlice(){const t=this.valueStack.pop();if(!t)throw new Error("Expected value context to exist in onExitSlice");for(const n of t.values)for(let r=n.length-1;r>=0;r--){const i=n[r];Qv in i&&delete i[Qv]}}getDefaultValue(){return this.rootValue}}function SV(e,t,n,r,i){const s=By(e,t,r,i);n.min>0&&s===void 0&&eb(n.type[0].code)&&(n.isArray?Uy(e,[Object.create(null)],t,n):Uy(e,Object.create(null),t,n))}function Uy(e,t,n,r){if(n.includes("."))throw new Error("key cannot be nested");let i=n;if(n.includes("[x]")){const s=r.type[0].code;i=n.replace("[x]",Hn(s))}t===void 0?delete e[i]:e[i]=t}function By(e,t,n,r){const i=t.split(".");let s=e,c;for(let u=0;u<i.length;u++){let f=i[u];if(f.includes("[x]")){const h=(r?r+".":"")+i.slice(0,u+1).join("."),g=n[h].type[0].code;f=f.replace("[x]",Hn(g))}if(u===i.length-1){Array.isArray(s)?c=s.map(h=>h[f]):c=s[f];continue}if(Array.isArray(s))s=s.map(h=>h[f]);else if(sr(s)){if(s[f]===void 0)return;s=s[f]}else return}return c}function Fh(e,t,n,r){if(!(n.fixed||n.pattern))return e;if(Array.isArray(e))return e.map(u=>Fh(u,t,n,r));e==null&&(e=Object.create(null));const i=e,s=t.split(".");let c=i;for(let u=0;u<s.length;u++){let f=s[u];if(f.includes("[x]")){const m=r[s.slice(0,u+1).join(".")].type[0].code;f=f.replace("[x]",Hn(m))}if(u===s.length-1){const h=Array.isArray(c)?c:[c];for(const m of h)n.fixed?m[f]??(m[f]=n.fixed.value):n.pattern&&(m[f]=QA(m[f],n.pattern.value))}else{if(!(f in c)){const h=s.slice(0,u+1).join(".");c[f]=r[h].isArray?[Object.create(null)]:Object.create(null)}c=c[f]}}return i}function QA(e,t){if(Array.isArray(t)&&(Array.isArray(e)||e===void 0))return((e==null?void 0:e.length)??0)>0?e:Qr(t);if(sr(t)&&(sr(e)&&!Array.isArray(e)||e===void 0)){const n=Qr(e)??Object.create(null);for(const r of Object.keys(t))n[r]=QA(n[r],t[r]);return n}return e}const wV="https://meta.medplum.com/releases",Wv=new Map;function jV(e){const t=e;if(!t.tag_name)throw new Error("Manifest missing tag_name");const n=t.assets;if(!(n!=null&&n.length))throw new Error("Manifest missing assets list");for(const r of n){if(!r.browser_download_url)throw new Error("Asset missing browser download URL");if(!r.name)throw new Error("Asset missing name")}}async function CV(e,t,n){let r=Wv.get("latest");if(!r){const i="latest",s=new URL(`${wV}/${i}.json`);s.searchParams.set("a",e),s.searchParams.set("c",FA);const c=await fetch(s.toString());if(c.status!==200){let f;try{f=(await c.json()).message}catch(h){console.error(`Failed to parse message from body: ${Ye(h)}`)}throw new Error(`Received status code ${c.status} while fetching manifest for version 'latest'. Message: ${f}`)}const u=await c.json();jV(u),r=u,Wv.set("latest",r),Wv.set(r.tag_name.slice(1),r)}return r}async function EV(e){const t=await CV(e);if(!t.tag_name.startsWith("v"))throw new Error(`Invalid release name found. Release tag '${t.tag_name}' did not start with 'v'`);return t.tag_name.slice(1)}const WA=v.createContext(void 0);function Jp(){return v.useContext(WA)}function _e(){return Jp().medplum}function em(){return Jp().navigate}function tm(){return Jp().profile}const AE=["change","storageInitialized","storageInitFailed","profileRefreshing","profileRefreshed"];function TV(e){const t=e.medplum,n=e.navigate??RV,[r,i]=v.useState({profile:t.getProfile(),loading:t.isLoading()});v.useEffect(()=>{function c(){i(u=>({...u,profile:t.getProfile(),loading:t.isLoading()}))}for(const u of AE)t.addEventListener(u,c);return()=>{for(const u of AE)t.removeEventListener(u,c)}},[t]);const s=v.useMemo(()=>({...r,medplum:t,navigate:n}),[r,t,n]);return o.jsx(WA.Provider,{value:s,children:e.children})}function RV(e){window.location.assign(e)}const _E=new Map,YA=e=>v.useMemo(()=>{if(!e)return;const t=e.split("?")[0];if(!t)return e;let n;try{n=new URLSearchParams(new URL(e).search)}catch{return e}if(!n.has("Key-Pair-Id")||!n.has("Signature"))return e;const r=n.get("Expires");if(!r||r.length>13)return e;const i=_E.get(t);if(i){const c=new URLSearchParams(new URL(i).search).get("Expires");if(c&&parseInt(c,10)*1e3-5e3>Date.now())return i}return _E.set(t,e),e},[e]);function DV(e){const t=v.useRef(void 0);return v.useEffect(()=>{t.current=e}),t.current}function Qt(e,t){const n=_e(),[r,i]=v.useState(()=>kE(n,e)),s=v.useCallback(c=>{sa(c,r)||i(c)},[r]);return v.useEffect(()=>{let c=!0;const u=kE(n,e);return!u&&Ko(e)?n.readReference(e).then(f=>{c&&s(f)}).catch(f=>{c&&(s(void 0),t&&t(Zt(f)))}):s(u),()=>c=!1},[n,e,s,t]),r}function kE(e,t){if(t){if(fa(t))return t;if(Ko(t))return e.getCachedReference(t)}}function AV(e,t,n={leading:!1}){const[r,i]=v.useState(e),s=v.useRef(!1),c=v.useRef(void 0),u=v.useRef(!1),f=v.useCallback(()=>window.clearTimeout(c.current),[]);return v.useEffect(()=>{s.current&&(!u.current&&n.leading?(u.current=!0,i(e)):(f(),c.current=setTimeout(()=>{u.current=!1,i(e)},t)))},[e,n.leading,t,f]),v.useEffect(()=>(s.current=!0,f),[f]),[r,f]}const _V=250;function kV(e,t,n){return KA("searchOne",e,t)}function xc(e,t,n){return KA("searchResources",e,t)}function KA(e,t,n,r){const i=_e(),[s,c]=v.useState(),[u,f]=v.useState(!0),[h,m]=v.useState(),[g,y]=v.useState(),b=i.fhirSearchUrl(t,n).toString(),[S]=AV(b,_V,{leading:!0});return v.useEffect(()=>{S!==s&&(c(S),i[e](t,n).then(j=>{f(!1),m(j),y(a$)}).catch(j=>{f(!1),m(void 0),y(Zt(j))}))},[i,e,t,n,s,S]),[h,u,g]}function PV(e){const t=e.value;return t?o.jsx(o.Fragment,{children:RA(t)}):null}const XA=["meta","implicitRules","contained","extension","modifierExtension"],ZA=["language","text"],cn=v.createContext({path:"",profileUrl:void 0,elements:Object.create(null),elementsByPath:Object.create(null),getExtendedProps:()=>({readonly:!1,hidden:!1}),accessPolicyResource:void 0,debugMode:!1,isDefaultContext:!0});cn.displayName="ElementsContext";const pb=["extension","modifierExtension"],NV=["id",...XA].filter(e=>!pb.includes(e));function OV(e){return Object.entries(e).filter(([n,r])=>{var i;return!Tn(r.type)||r.max===0||r.path.toLowerCase().endsWith("extension.url")&&r.fixed||pb.includes(n)&&!Tn((i=r.slicing)==null?void 0:i.slices)||NV.includes(n)?!1:!(ZA.includes(n)&&r.path.split(".").length===2||n.includes("."))})}function PE(e,t){return e.line&&e.line.length>t?e.line[t]:""}function NE(e,t,n){const r=e.line||[];for(;r.length<=t;)r.push("");return r[t]=n,{...e,line:r}}function MV(e){const[t,n]=v.useState(e.defaultValue||{}),r=v.useRef(t);r.current=t;const{getExtendedProps:i}=v.useContext(cn),[s,c,u,f,h,m,g]=v.useMemo(()=>["use","type","line1","line2","city","state","postalCode"].map(R=>i(e.path+"."+R)),[i,e.path]);function y(R){n(R),e.onChange&&e.onChange(R)}function b(R){y({...r.current,use:R})}function S(R){y({...r.current,type:R})}function j(R){y(NE(r.current||{},0,R))}function C(R){y(NE(r.current||{},1,R))}function T(R){y({...r.current,city:R})}function D(R){y({...r.current,state:R})}function E(R){y({...r.current,postalCode:R})}return o.jsxs(Ce,{gap:"xs",wrap:"nowrap",grow:!0,children:[o.jsx(ln,{disabled:e.disabled||(s==null?void 0:s.readonly),"data-testid":"address-use",defaultValue:t.use,onChange:R=>b(R.currentTarget.value),data:["","home","work","temp","old","billing"]}),o.jsx(ln,{disabled:e.disabled||(c==null?void 0:c.readonly),"data-testid":"address-type",defaultValue:t.type,onChange:R=>S(R.currentTarget.value),data:["","postal","physical","both"]}),o.jsx(ze,{disabled:e.disabled||(u==null?void 0:u.readonly),placeholder:"Line 1",defaultValue:PE(t,0),onChange:R=>j(R.currentTarget.value)}),o.jsx(ze,{disabled:e.disabled||(f==null?void 0:f.readonly),placeholder:"Line 2",defaultValue:PE(t,1),onChange:R=>C(R.currentTarget.value)}),o.jsx(ze,{disabled:e.disabled||(h==null?void 0:h.readonly),placeholder:"City",defaultValue:t.city,onChange:R=>T(R.currentTarget.value)}),o.jsx(ze,{disabled:e.disabled||(m==null?void 0:m.readonly),placeholder:"State",defaultValue:t.state,onChange:R=>D(R.currentTarget.value)}),o.jsx(ze,{disabled:e.disabled||(g==null?void 0:g.readonly),placeholder:"Postal Code",defaultValue:t.postalCode,onChange:R=>E(R.currentTarget.value)})]})}function IV(e){const t=tm(),[n,r]=v.useState(e.defaultValue||{});function i(s){const c=s?{text:s,authorReference:t&&on(t),time:new Date().toISOString()}:{};r(c),e.onChange&&e.onChange(c)}return o.jsx(ze,{disabled:e.disabled,name:e.name,placeholder:"Annotation text",defaultValue:n.text,onChange:s=>i(s.currentTarget.value)})}/**
|
|
126
|
+
}`.replace(/\s+/g," "),c=await this.graphql(s);rE(c.data.StructureDefinitionList);for(const u of c.data.SearchParameterList)fU(u)})());return this.setCacheEntry(n,i),i}requestProfileSchema(t,n){if(!(n!=null&&n.expandProfile)&&K0(t))return Promise.resolve();const r=t+"-requestSchema"+(n!=null&&n.expandProfile?"-nested":""),i=this.getCacheEntry(r,void 0);if(i)return i.value;const s=new Ai((async()=>{if(n!=null&&n.expandProfile){const c=this.fhirUrl("StructureDefinition","$expand-profile");c.search=new URLSearchParams({url:t}).toString();const u=await this.post(c.toString(),{});rE(u)}else{const c=await this.searchOne("StructureDefinition",{url:t,_sort:"-_lastUpdated"});if(!c){console.warn(`No StructureDefinition found for ${t}!`);return}uA(c)}})());return this.setCacheEntry(r,s),s}readHistory(t,n,r){return this.get(this.fhirUrl(t,n,"_history"),r)}readVersion(t,n,r,i){return this.get(this.fhirUrl(t,n,"_history",r),i)}readPatientEverything(t,n){return this.getBundle(this.fhirUrl("Patient",t,"$everything"),n)}readPatientSummary(t,n){return this.getBundle(this.fhirUrl("Patient",t,"$summary"),n)}createResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(t.resourceType),this.post(this.fhirUrl(t.resourceType),t,void 0,n)}async createResourceIfNoneExist(t,n,r){const i=this.fhirUrl(t.resourceType);r?r.headers?Array.isArray(r.headers)?r.headers.push(["If-None-Exist",n]):r.headers instanceof Headers?r.headers.set("If-None-Exist",n):r.headers["If-None-Exist"]=n:r.headers={"If-None-Exist":n}:r={headers:{"If-None-Exist":n}};const s=await this.post(i,t,void 0,r);return this.cacheResource(s),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),s}async upsertResource(t,n,r){const i=this.fhirSearchUrl(t.resourceType,n);let s=await this.put(i,t,void 0,r);return s||(s=t),this.cacheResource(s),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),s}async createAttachment(t,n,r,i,s){let c=RE(t,n,r,i);if(c.contentType===hn.XML){const h=c.data;let m;h instanceof Blob?m=await new Promise((g,y)=>{const b=new FileReader;b.onload=()=>{if(!b.result){y(new Error("Failed to load file"));return}g(b.result)},b.readAsText(h,"utf-8")}):ArrayBuffer.isView(h)?m=new TextDecoder().decode(h):m=h,m.includes("<ClinicalDocument")&&m.includes("urn:hl7-org:v3")&&(c={...c,contentType:hn.CDA_XML})}const u=s??(typeof n=="object"?n:{}),f=await this.createBinary(c,u);return{contentType:c.contentType,url:f.url,title:c.filename}}createBinary(t,n,r,i,s){const c=RE(t,n,r,i),u=s??(typeof n=="object"?n:{}),{data:f,contentType:h,filename:m,securityContext:g,onProgress:y}=c,b=this.fhirUrl("Binary");return m&&b.searchParams.set("_filename",m),g!=null&&g.reference&&this.setRequestHeader(u,"X-Security-Context",g.reference),y?this.uploadwithProgress(b,f,h,y,u):this.post(b,f,h,u)}uploadwithProgress(t,n,r,i,s){return new Promise((c,u)=>{var g;const f=new XMLHttpRequest,h=()=>f.abort();(g=s==null?void 0:s.signal)==null||g.addEventListener("abort",h);const m=y=>{var b;(b=s==null?void 0:s.signal)==null||b.removeEventListener("abort",h),y instanceof Error?u(y):c(y)};if(f.responseType="json",f.onabort=()=>m(new DOMException("Request aborted","AbortError")),f.onerror=()=>m(new Error("Request error")),i&&(f.upload.onprogress=y=>i(y),f.upload.onload=y=>i(y)),f.onload=()=>{f.status>=200&&f.status<300?m(f.response):m(new dt(Zt(f.response||f.statusText)))},f.open("POST",t),f.withCredentials=!0,f.setRequestHeader("Authorization","Bearer "+this.accessToken),f.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),f.setRequestHeader("Content-Type",r),this.options.extendedMode!==!1&&f.setRequestHeader("X-Medplum","extended"),s!=null&&s.headers){const y=s.headers;for(const[b,S]of Object.entries(y))f.setRequestHeader(b,S)}f.send(n)})}async createPdf(t,n,r,i){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");const s=dV(t,n,r,i),c=typeof n=="object"?n:{},{docDefinition:u,tableLayouts:f,fonts:h,...m}=s,g=await this.createPdfImpl(u,f,h),y={...m,data:g,contentType:"application/pdf"};return this.createBinary(y,c)}createComment(t,n,r){const i=this.getProfile();let s,c;return t.resourceType==="Encounter"&&(s=on(t),c=t.subject),t.resourceType==="ServiceRequest"&&(s=t.encounter,c=t.subject),t.resourceType==="Patient"&&(c=on(t)),this.createResource({resourceType:"Communication",status:"completed",basedOn:[on(t)],encounter:s,subject:c,sender:i?on(i):void 0,sent:new Date().toISOString(),payload:[{contentString:n}]},r)}async updateResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");if(!t.id)throw new Error("Missing id");let r=await this.put(this.fhirUrl(t.resourceType,t.id),t,void 0,n);return r||(r=t),this.cacheResource(r),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),r}async patchResource(t,n,r,i){const s=await this.patch(this.fhirUrl(t,n),r,i);return this.cacheResource(s),this.invalidateUrl(this.fhirUrl(t,n,"_history")),this.invalidateSearches(t),s}deleteResource(t,n,r){return this.deleteCacheEntry(this.fhirUrl(t,n).toString()),this.invalidateSearches(t),this.delete(this.fhirUrl(t,n),r)}validateResource(t,n){return this.post(this.fhirUrl(t.resourceType,"$validate"),t,void 0,n)}executeBot(t,n,r,i){let s;if(typeof t=="string"){const c=t;s=this.fhirUrl("Bot",c,"$execute")}else{const c=t;s=this.fhirUrl("Bot","$execute"),s.searchParams.set("identifier",c.system+"|"+c.value)}return this.post(s,n,r,i)}executeBatch(t,n){return this.post(this.fhirBaseUrl,t,void 0,n)}sendEmail(t,n){return this.post("email/v1/send",t,hn.JSON,n)}graphql(t,n,r,i){return this.post(this.fhirUrl("$graphql"),{query:t,operationName:n,variables:r},hn.JSON,i)}readResourceGraph(t,n,r,i){return this.get(`${this.fhirUrl(t,n)}/$graph?graph=${r}`,i)}pushToAgent(t,n,r,i,s,c){return this.post(this.fhirUrl("Agent",Bs(t),"$push"),{destination:typeof n=="string"?n:zt(n),body:r,contentType:i,waitForResponse:s},hn.FHIR_JSON,c)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(t){var n,r;(!((n=this.sessionDetails)!=null&&n.profile)||zt(this.sessionDetails.profile)!==((r=t.profile)==null?void 0:r.reference))&&this.clearActiveLogin(),this.setAccessToken(t.accessToken,t.refreshToken),this.storage.setObject("activeLogin",t),this.addLogin(t),this.refreshPromise=void 0,await this.refreshProfile()}getAccessToken(){return this.accessToken}isAuthenticated(t){return this.accessTokenExpires!==void 0&&Date.now()<this.accessTokenExpires-(t??this.refreshGracePeriod)}setAccessToken(t,n){this.accessToken=t,this.refreshToken=n,this.accessTokenExpires=HB(t),this.medplumServer=FB(t)}getLogins(){return this.storage.getObject("logins")??[]}addLogin(t){const n=this.getLogins().filter(r=>{var i,s;return((i=r.profile)==null?void 0:i.reference)!==((s=t.profile)==null?void 0:s.reference)});n.push(t),this.storage.setObject("logins",n)}async refreshProfile(){return this.medplumServer?(this.profilePromise=new Promise((t,n)=>{this.get("auth/me",{cache:"no-cache"}).then(r=>{var s,c;this.profilePromise=void 0;const i=((c=(s=this.sessionDetails)==null?void 0:s.profile)==null?void 0:c.id)!==r.profile.id;this.sessionDetails=r,i&&this.dispatchEvent({type:"change"}),t(r.profile),this.dispatchEvent({type:"profileRefreshed"})}).catch(n)}),this.dispatchEvent({type:"profileRefreshing"}),this.profilePromise):Promise.resolve(void 0)}isLoading(){var t;return!this.isInitialized||!!this.profilePromise&&!((t=this.sessionDetails)!=null&&t.profile)}isSuperAdmin(){var t;return!!((t=this.sessionDetails)!=null&&t.project.superAdmin)}isProjectAdmin(){var t;return!!((t=this.sessionDetails)!=null&&t.membership.admin)}getProject(){var t;return(t=this.sessionDetails)==null?void 0:t.project}getProjectMembership(){var t;return(t=this.sessionDetails)==null?void 0:t.membership}getProfile(){var t;return(t=this.sessionDetails)==null?void 0:t.profile}async getProfileAsync(){return this.profilePromise?this.profilePromise:this.sessionDetails?this.sessionDetails.profile:this.refreshProfile()}getUserConfiguration(){var t;return(t=this.sessionDetails)==null?void 0:t.config}getAccessPolicy(){var t;return(t=this.sessionDetails)==null?void 0:t.accessPolicy}async download(t,n={}){this.refreshPromise&&await this.refreshPromise;const r=t.toString();r.startsWith(aV)&&(t=this.fhirUrl(r));let i=n.headers;return i||(i={},n.headers=i),i.Accept||(i.Accept="*/*"),this.addFetchOptionsDefaults(n),(await this.fetchWithRetry(t.toString(),n)).blob()}async createMedia(t,n){const{additionalFields:r,...i}=t,s=await this.createResource({resourceType:"Media",status:"preparation",content:{contentType:t.contentType},...r});i.securityContext||(i.securityContext=on(s));const c=await this.createAttachment(i,n);return this.updateResource({...s,status:"completed",content:c})}async uploadMedia(t,n,r,i,s){return this.createMedia({data:t,contentType:n,filename:r,additionalFields:i},s)}async createDocumentReference(t,n){const{additionalFields:r,...i}=t,s=await this.createResource({resourceType:"DocumentReference",status:"current",content:[{attachment:{contentType:t.contentType}}],...r});i.securityContext||(i.securityContext=on(s));const c=await this.createAttachment(i,n);return this.updateResource({...s,content:[{attachment:c}]})}async bulkExport(t="",n,r,i){const s=t&&`${t}/`,c=this.fhirUrl(`${s}$export`);return n&&c.searchParams.set("_type",n),r&&c.searchParams.set("_since",r),this.startAsyncRequest(c.toString(),i)}async startAsyncRequest(t,n={}){this.addFetchOptionsDefaults(n);const r=n.headers;return r.Prefer="respond-async",this.request("POST",t,n)}get keyValue(){return this.keyValueClient||(this.keyValueClient=new qB(this)),this.keyValueClient}getBundle(t,n){return new Ai((async()=>{const r=await this.get(t,n);if(r.entry)for(const i of r.entry)this.cacheResource(i.resource);return r})())}getCacheEntry(t,n){if(!this.requestCache||(n==null?void 0:n.cache)==="no-cache"||(n==null?void 0:n.cache)==="reload")return;const r=this.requestCache.get(t);if(!(!r||r.requestTime+this.cacheTime<Date.now()))return r}setCacheEntry(t,n){this.requestCache&&this.requestCache.set(t,{requestTime:Date.now(),value:n})}cacheResource(t){var n,r;t!=null&&t.id&&!((r=(n=t.meta)==null?void 0:n.tag)!=null&&r.some(i=>i.code==="SUBSETTED"))&&this.setCacheEntry(this.fhirUrl(t.resourceType,t.id).toString(),new Ai(Promise.resolve(t)))}deleteCacheEntry(t){this.requestCache&&this.requestCache.delete(t)}async request(t,n,r={},i={}){await this.refreshIfExpired(),r.method=t,this.addFetchOptionsDefaults(r);const s=await this.fetchWithRetry(n,r);if(s.status===401)return this.handleUnauthenticated(t,n,r);if(s.status===204||s.status===304)return;const c=s.headers.get("content-type"),u=c==null?void 0:c.includes("json");if(s.status===404&&!u)throw new dt(o8);const f=await this.parseBody(s,u);if(s.status===200&&r.followRedirectOnOk||s.status===201&&r.followRedirectOnCreated){const h=await EE(s,f);if(h)return this.request("GET",h,{...r,body:void 0})}if(s.status===202&&r.pollStatusOnAccepted){const m=await EE(s,f)??i.statusUrl;if(m)return this.pollStatus(m,r,i)}if(s.status>=400)throw new dt(Zt(f));return f}async parseBody(t,n){let r;if(t.headers.get("content-length")!=="0"){if(n)try{r=await t.json()}catch(i){throw console.error("Error parsing response",t.status,i),i}else r=await t.text();return r}}async fetchWithRetry(t,n){t.startsWith("http")||(t=Xi(this.baseUrl,t));const r=(n==null?void 0:n.maxRetries)??2;for(let i=0;i<=r;i++)try{this.options.verbose&&this.logRequest(t,n);const s=await this.fetch(t,n);if(this.options.verbose&&this.logResponse(s),this.setCurrentRateLimit(s),i>=r||!fV(s))return s;const c=this.getRetryDelay(i),u=n.maxRetryTime??2e3;if(c>u)return s;await dE(c)}catch(s){if(s.message==="Failed to fetch"&&i===0&&this.dispatchEvent({type:"offline"}),s.name==="AbortError"||i===r)throw s}throw new Error("Unreachable")}logRequest(t,n){if(console.log(`> ${n.method} ${t}`),n.headers){const r=n.headers;for(const i of ad(Object.keys(r)))console.log(`> ${i}: ${r[i]}`)}}logResponse(t){console.log(`< ${t.status} ${t.statusText}`),t.headers&&t.headers.forEach((n,r)=>console.log(`< ${r}: ${n}`))}setCurrentRateLimit(t){var r;const n=(r=t.headers)==null?void 0:r.get("ratelimit");n&&(this.currentRateLimits=n)}rateLimitStatus(){if(!this.currentRateLimits)return[];const t=this.currentRateLimits;return t.split(/\s*;\s*/g).map(n=>{const r=n.split(/\s*,\s*/g);if(r.length!==3)throw new Error("Could not parse RateLimit header: "+t);const i=r[0].substring(1,r[0].length-1),s=r.find(h=>h.startsWith("r=")),c=s?parseInt(s.substring(2),10):NaN,u=r.find(h=>h.startsWith("t=")),f=u?parseInt(u.substring(2),10):NaN;if(!i||Number.isNaN(c)||Number.isNaN(f))throw new Error("Could not parse RateLimit header: "+t);return{name:i,remainingUnits:c,secondsUntilReset:f}})}getRetryDelay(t){const n=this.rateLimitStatus();let r=500*Math.pow(1.5,t);for(const i of n)i.remainingUnits||(r=Math.max(r,i.secondsUntilReset*1e3));return r}async pollStatus(t,n,r){const i={...n,method:"GET",body:void 0,redirect:"follow"};if(r.pollCount===void 0)n.headers&&typeof n.headers=="object"&&"Prefer"in n.headers&&(i.headers={...n.headers},delete i.headers.Prefer),r.statusUrl=t,r.pollCount=1;else{const s=n.pollStatusPeriod??1e3;await dE(s),r.pollCount++}return this.request("GET",t,i,r)}async executeAutoBatch(){var i,s;if(this.autoBatchQueue===void 0)return;const t=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,t.length===1){const c=t[0];try{c.resolve(await this.request(c.method,Xi(this.fhirBaseUrl,c.url),c.options))}catch(u){c.reject(new dt(Zt(u)))}return}const n={resourceType:"Bundle",type:"batch",entry:t.map(c=>({request:{method:c.method,url:c.url},resource:c.options.body?JSON.parse(c.options.body):void 0}))},r=await this.post(this.fhirBaseUrl,n);for(let c=0;c<t.length;c++){const u=t[c],f=(i=r.entry)==null?void 0:i[c];(s=f==null?void 0:f.response)!=null&&s.outcome&&!oA(f.response.outcome)?u.reject(new dt(f.response.outcome)):u.resolve(f==null?void 0:f.resource)}}addFetchOptionsDefaults(t){Object.entries(this.defaultHeaders).forEach(([n,r])=>{this.setRequestHeader(t,n,r)}),this.setRequestHeader(t,"Accept",JB,!0),this.options.extendedMode!==!1&&this.setRequestHeader(t,"X-Medplum","extended"),t.body&&this.setRequestHeader(t,"Content-Type",hn.FHIR_JSON,!0),this.accessToken?this.setRequestHeader(t,"Authorization","Bearer "+this.accessToken):this.basicAuth&&this.setRequestHeader(t,"Authorization","Basic "+this.basicAuth),t.cache||(t.cache="no-cache"),t.credentials||(t.credentials="include")}setRequestContentType(t,n){this.setRequestHeader(t,"Content-Type",n)}setRequestHeader(t,n,r,i=!1){t.headers||(t.headers={});const s=t.headers;i&&s[n]||(s[n]=r)}setRequestBody(t,n){typeof n=="string"||typeof Blob<"u"&&(n instanceof Blob||(n==null?void 0:n.constructor.name)==="Blob")||typeof File<"u"&&(n instanceof File||(n==null?void 0:n.constructor.name)==="File")||typeof Uint8Array<"u"&&(n instanceof Uint8Array||(n==null?void 0:n.constructor.name)==="Uint8Array")?t.body=n:n&&(t.body=JSON.stringify(n))}handleUnauthenticated(t,n,r){return this.refresh()?this.request(t,n,r):(this.clear(),this.onUnauthenticated&&this.onUnauthenticated(),Promise.reject(new dt(id)))}async startPkce(){const t=yE();sessionStorage.setItem("pkceState",t);const n=yE().slice(0,128);sessionStorage.setItem("codeVerifier",n);const r=await TB(n),i=Y$(r).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return sessionStorage.setItem("codeChallenge",i),{codeChallengeMethod:"S256",codeChallenge:i}}async requestAuthorization(t){const n=await this.ensureCodeChallenge(t??{}),r=new URL(this.authorizeUrl);r.searchParams.set("response_type","code"),r.searchParams.set("state",sessionStorage.getItem("pkceState")),r.searchParams.set("client_id",n.clientId??this.clientId),r.searchParams.set("redirect_uri",n.redirectUri??CE()),r.searchParams.set("code_challenge_method",n.codeChallengeMethod),r.searchParams.set("code_challenge",n.codeChallenge),r.searchParams.set("scope",n.scope??"openid profile"),window.location.assign(r.toString())}processCode(t,n){const r={grant_type:Xl.AuthorizationCode,code:t,client_id:(n==null?void 0:n.clientId)??this.clientId??"",redirect_uri:(n==null?void 0:n.redirectUri)??CE()};if(typeof sessionStorage<"u"){const i=sessionStorage.getItem("codeVerifier");i&&(r.code_verifier=i)}return this.fetchTokens(r)}refreshIfExpired(t){return!this.refreshPromise&&this.accessTokenExpires!==void 0&&!this.isAuthenticated(t)&&this.refresh(),this.refreshPromise??Promise.resolve()}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken)return this.refreshPromise=this.fetchTokens({grant_type:Xl.RefreshToken,client_id:this.clientId??"",refresh_token:this.refreshToken}),this.refreshPromise;if(this.clientId&&this.clientSecret)return this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise}async startClientLogin(t,n){return this.clientId=t,this.clientSecret=n,this.fetchTokens({grant_type:Xl.ClientCredentials,client_id:t,client_secret:n})}async startJwtBearerLogin(t,n,r){return this.clientId=t,this.fetchTokens({grant_type:Xl.JwtBearer,client_id:t,assertion:n,scope:r})}async startJwtAssertionLogin(t){return this.fetchTokens({grant_type:Xl.ClientCredentials,client_assertion_type:sV.JwtBearer,client_assertion:t})}setBasicAuth(t,n){this.clientId=t,this.clientSecret=n,this.basicAuth=vE(t+":"+n)}async fhircastSubscribe(t,n){if(!(typeof t=="string"&&t!==""))throw new dt(yn("Invalid topic provided. Topic must be a valid string."));if(!(typeof n=="object"&&Array.isArray(n)&&n.length>0))throw new dt(yn("Invalid events provided. Events must be an array of event names containing at least one event."));const r={channelType:"websocket",mode:"subscribe",topic:t,events:n},s=(await this.post(this.fhircastHubUrl,xE(r),hn.FORM_URL_ENCODED))["hub.channel.endpoint"];if(!s)throw new Error("Invalid response!");return r.endpoint=s,r}async fhircastUnsubscribe(t){if(!fb(t))throw new dt(yn("Invalid topic or subscriptionRequest. SubscriptionRequest must be an object."));if(!(t.endpoint&&typeof t.endpoint=="string"&&t.endpoint.startsWith("ws")))throw new dt(yn("Provided subscription request must have an endpoint in order to unsubscribe."));t.mode="unsubscribe",await this.post(this.fhircastHubUrl,xE(t),hn.FORM_URL_ENCODED)}fhircastConnect(t){return new UB(t)}async fhircastPublish(t,n,r,i){return NB(n)?this.post(this.fhircastHubUrl,bE(t,n,r,i),hn.JSON):(OB(n),this.post(this.fhircastHubUrl,bE(t,n,r),hn.JSON))}async fhircastGetContext(t){return this.get(`${this.fhircastHubUrl}/${t}`,{cache:"no-cache"})}async invite(t,n){return this.post("admin/projects/"+t+"/invite",n)}async fetchTokens(t){const n=new URLSearchParams(t),r={...this.defaultHeaders,"Content-Type":hn.FORM_URL_ENCODED};this.basicAuth&&(r.Authorization=`Basic ${this.basicAuth}`),this.credentialsInHeader&&(n.delete("client_id"),n.delete("client_secret"),!this.basicAuth&&t.client_id&&t.client_secret&&(r.Authorization=`Basic ${vE(t.client_id+":"+t.client_secret)}`));const i={method:"POST",headers:r,body:n.toString(),credentials:"include"};let s;try{s=await this.fetchWithRetry(this.tokenUrl,i)}catch(u){throw this.refreshPromise=void 0,u}if(!s.ok){this.clearActiveLogin();try{const u=await s.json();throw new dt(ra(u.error_description))}catch(u){throw new dt(ra("Failed to fetch tokens"),u)}}const c=await s.json();return await this.verifyTokens(c),this.getProfile()}async verifyTokens(t){const n=t.access_token;if(VB(n)){const r=hb(n);if(Date.now()>=r.exp*1e3)throw this.clearActiveLogin(),new dt(s8);if(r.cid){if(r.cid!==this.clientId)throw this.clearActiveLogin(),new dt(tE)}else if(this.clientId&&r.client_id!==this.clientId)throw this.clearActiveLogin(),new dt(tE)}return this.setActiveLogin({accessToken:n,refreshToken:t.refresh_token,project:t.project,profile:t.profile})}checkSessionDetailsMatchLogin(t){var n,r;return this.sessionDetails&&t?((r=(n=t.profile)==null?void 0:n.reference)==null?void 0:r.endsWith(this.sessionDetails.profile.id))??!1:!0}setupStorageListener(){try{window.addEventListener("storage",t=>{if(t.key===null)window.location.reload();else if(t.key==="activeLogin"){const n=t.oldValue?JSON.parse(t.oldValue):void 0,r=t.newValue?JSON.parse(t.newValue):void 0;(n==null?void 0:n.profile.reference)!==(r==null?void 0:r.profile.reference)||!this.checkSessionDetailsMatchLogin(r)?window.location.reload():r?this.setAccessToken(r.accessToken,r.refreshToken):this.clear()}})}catch{}}getSubscriptionManager(){return this.subscriptionManager||(this.subscriptionManager=new ZB(this,eU(this.baseUrl,"/ws/subscriptions-r4"))),this.subscriptionManager}subscribeToCriteria(t,n){return this.getSubscriptionManager().addCriteria(t,n)}unsubscribeFromCriteria(t,n){this.subscriptionManager&&(this.subscriptionManager.removeCriteria(t,n),this.subscriptionManager.getCriteriaCount()===0&&this.subscriptionManager.closeWebSocket())}getMasterSubscriptionEmitter(){return this.getSubscriptionManager().getMasterEmitter()}}function lV(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}function CE(){return typeof window>"u"?"":window.location.protocol+"//"+window.location.host+"/"}async function EE(e,t){var i,s;const n=e.headers.get("content-location");if(n)return n;const r=e.headers.get("location");if(r)return r;if(qp(t)&&((s=(i=t.issue)==null?void 0:i[0])!=null&&s.diagnostics))return t.issue[0].diagnostics}function TE(e){var n;const t=((n=e.entry)==null?void 0:n.map(r=>r.resource))??[];return Object.assign(t,{bundle:e})}function cV(e){return sr(e)&&"data"in e&&"contentType"in e}function RE(e,t,n,r){return cV(e)?e:{data:e,filename:t,contentType:n,onProgress:r}}function uV(e){return sr(e)&&"docDefinition"in e}function dV(e,t,n,r){return uV(e)?e:{docDefinition:e,filename:t,tableLayouts:n,fonts:r}}function fV(e){return e.status===429||e.status>=500}function yc({parentContext:e,path:t,elements:n,profileUrl:r,debugMode:i,accessPolicyResource:s}){if(t===(e==null?void 0:e.path))return;i??(i=(e==null?void 0:e.debugMode)??!1),s??(s=e==null?void 0:e.accessPolicyResource);let c=hV(t,n,e,!!i);const u=Iy(t,".",2)[1];c=pV(c,s,u),c=mV(c,s,u);const f=Object.create(null);for(const[m,g]of Object.entries(c))f[t+"."+m]=g;let h;if(e&&!e.isDefaultContext)h=e.getExtendedProps;else{const m=Object.create(null);h=g=>{const y=Iy(g,".",2)[1];if(y){if(!m[y]){const b=Vh(y,s==null?void 0:s.hiddenFields);m[y]={hidden:b,readonly:b||Vh(y,s==null?void 0:s.readonlyFields)}}return m[y]}}}return{path:t,elements:c,elementsByPath:f,profileUrl:r??(e==null?void 0:e.profileUrl),debugMode:i,getExtendedProps:h,accessPolicyResource:s}}function hV(e,t,n,r){const i=Object.create(null);if(n)for(const[c,u]of Object.entries(n.elementsByPath)){const f=ks(e,c);f!==void 0&&(i[f]=u)}let s=!1;if(t)for(const[c,u]of Object.entries(t))c in i||(i[c]=u,s=!0);return r&&console.assert(s,"Unnecessary ElementsContext; not using any newly provided elements"),i}function pV(e,t,n){var i;if(!((i=t==null?void 0:t.hiddenFields)!=null&&i.length))return e;const r=n?n+".":"";return Object.fromEntries(Object.entries(e).filter(([s])=>!Vh(r+s,t.hiddenFields)))}function mV(e,t,n){var s;if(!((s=t==null?void 0:t.readonlyFields)!=null&&s.length))return e;const r=Object.create(null),i=n?n+".":"";for(const[c,u]of Object.entries(e))Vh(i+c,t.readonlyFields)?r[c]={...u,readonly:!0}:r[c]=u;return r}function Vh(e,t){if(!(t!=null&&t.length))return!1;const n=e.split(".");for(let r=1;r<=n.length;r++){const i=n.slice(0,r).join(".");if(t.includes(i))return!0}return!1}function qA(e){return e.type!==void 0&&e.type.length>0}function gV(e,t,n,r){var s;const i=C$(e,t.path,{profileUrl:r});if(i){const c=((s=n.typeSchema)==null?void 0:s.elements)??n.elements;return i.some(u=>R$(u,t,n,c))??!1}return console.assert(!1,"getNestedProperty[%s] in isDiscriminatorComponentMatch missed",t.path),!1}function GA(e,t,n,r){var i,s;if(e)for(const c of t){const u={value:e,type:((i=c.typeSchema)==null?void 0:i.type)??((s=c.type)==null?void 0:s[0].code)};if(n.every(f=>{var h;return gV(u,f,c,((h=c.typeSchema)==null?void 0:h.url)??r)}))return c.name}}class vV{constructor(t,n,r){if(t.type===void 0)throw new Error("schema must include a type");this.rootSchema=t;const i=yc({parentContext:void 0,path:this.rootSchema.type,elements:r??this.rootSchema.elements,profileUrl:this.rootSchema.name===this.rootSchema.type?void 0:this.rootSchema.url});if(i===void 0)throw new Error("Could not create root elements context");this.elementsContextStack=[i],this.visitor=n}get elementsContext(){return this.elementsContextStack[this.elementsContextStack.length-1]}crawlElement(t,n,r){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema);const i=Object.fromEntries(Object.entries(this.elementsContext.elements).filter(([s])=>s.startsWith(n)));this.crawlElementsImpl(i,r),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlSlice(t,n,r){const i=this.prepareSlices(r.slices,r);if(!Tn(i.slices))throw new Error(`cannot crawl slice ${n.name} since it has no type information`);this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.sliceAllowList=[n],this.crawlSliceImpl(i.slices[0],n.path,i),this.sliceAllowList=void 0,this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlResource(){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.crawlElementsImpl(this.rootSchema.elements,this.rootSchema.type),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlElementsImpl(t,n){const r=yV(t);for(const i of r)this.crawlElementNode(i,n)}crawlElementNode(t,n){var i,s;const r=n+"."+t.key;this.visitor.onEnterElement&&this.visitor.onEnterElement(r,t.element,this.elementsContext);for(const c of t.children)this.crawlElementNode(c,n);Tn((s=(i=t.element)==null?void 0:i.slicing)==null?void 0:s.slices)&&this.crawlSlicingImpl(t.element.slicing,r),this.visitor.onExitElement&&this.visitor.onExitElement(r,t.element,this.elementsContext)}prepareSlices(t,n){var s,c;const r=[];for(const u of t){if(!qA(u))continue;const f=(c=(s=u.type.find(h=>Tn(h.profile)))==null?void 0:s.profile)==null?void 0:c[0];if(Tn(f)){const h=Pc(f);h&&(u.typeSchema=h)}r.push(u)}return{...n,slices:r}}crawlSlicingImpl(t,n){const r=this.prepareSlices(t.slices,t);for(const i of r.slices)(this.sliceAllowList===void 0||this.sliceAllowList.includes(i))&&this.crawlSliceImpl(i,n,r)}crawlSliceImpl(t,n,r){const i=t.typeSchema;i&&this.visitor.onEnterSchema&&this.visitor.onEnterSchema(i),this.visitor.onEnterSlice&&this.visitor.onEnterSlice(n,t,r);let s;const c=(i==null?void 0:i.elements)??t.elements;Tn(c)&&(s=yc({path:n,parentContext:this.elementsContext,elements:c})),s&&this.elementsContextStack.push(s),this.crawlElementsImpl(c,n),s&&this.elementsContextStack.pop(),this.visitor.onExitSlice&&this.visitor.onExitSlice(n,t,r),i&&this.visitor.onExitSchema&&this.visitor.onExitSchema(i)}}function yV(e){const t=[];function n(s,c){return c.startsWith(s+".")}function r(s,c){for(const u of s.children)if(n(u.key,c.key)){r(u,c);return}s.children.push(c)}const i=Object.entries(e);i.sort((s,c)=>s[0].localeCompare(c[0]));for(const[s,c]of i){const u={key:s,element:c,children:[]};let f=!1;for(const h of t)if(n(h.key,s)){r(h,u),f=!0;break}f||t.push(u)}return t}const Qv="__sliceName";function xV(e,t){const n=new bV(e,e.resourceType,"resource");return new vV(t,n).crawlResource(),n.getDefaultValue()}function DE(e,t,n){for(const[r,i]of Object.entries(t)){if(n===void 0||n===r){Fh(e,r,i,t);continue}const s=ks(n,r);s!==void 0&&Fh(e,s,i,t)}return e}class bV{constructor(t,n,r){this.schemaStack=[],this.valueStack=[],this.rootValue=Qr(t),this.valueStack.splice(0,this.valueStack.length,{type:r,path:n,values:[this.rootValue]})}get schema(){return this.schemaStack[this.schemaStack.length-1]}get value(){return this.valueStack[this.valueStack.length-1]}onEnterSchema(t){this.schemaStack.push(t)}onExitSchema(){this.schemaStack.pop()}onEnterElement(t,n,r){const i=this.value.values,s=this.value.path,c=ks(s,t);if(c===void 0)throw new Error(`Expected ${t} to be prefixed by ${s}`);const u=[];for(const f of i){if(f===void 0)continue;const h=ks(r.path,s),m=Array.isArray(f)?f:[f];for(const g of m){SV(g,c,n,r.elements,h),Fh(g,c,n,r.elements);const y=By(g,c,r.elements,h);y!==void 0&&u.push(y)}}this.valueStack.push({type:"element",path:t,values:u})}onExitElement(t,n,r){if(!this.valueStack.pop())throw new Error("Expected value context to exist when exiting element");const s=ks(this.value.path,t);if(s===void 0)throw new Error(`Expected ${t} to be prefixed by ${this.value.path}`);const c=ks(r.path,this.value.path);for(const u of this.value.values){const f=By(u,s,r.elements,c);if(Array.isArray(f))for(let h=f.length-1;h>=0;h--){const m=f[h];Tn(m)||f.splice(h,1)}Rn(f)&&Uy(u,void 0,s,n)}}onEnterSlice(t,n,r){const i=this.value.values,s=[];for(const c of i)if(c!==void 0){const u=Array.isArray(c)?c:[c],f=this.getMatchingSliceValues(u,n,r);s.push(f)}this.valueStack.push({type:"slice",path:t,values:s})}getMatchingSliceValues(t,n,r){const i=[];for(const s of t)(s[Qv]??GA(s,[n],r.discriminator,this.schema.url))===n.name&&i.push(s);for(let s=i.length;s<n.min;s++)if(eb(n.type[0].code)){const c=Object.create(null);i.push(c),t.push(c)}return i}onExitSlice(){const t=this.valueStack.pop();if(!t)throw new Error("Expected value context to exist in onExitSlice");for(const n of t.values)for(let r=n.length-1;r>=0;r--){const i=n[r];Qv in i&&delete i[Qv]}}getDefaultValue(){return this.rootValue}}function SV(e,t,n,r,i){const s=By(e,t,r,i);n.min>0&&s===void 0&&eb(n.type[0].code)&&(n.isArray?Uy(e,[Object.create(null)],t,n):Uy(e,Object.create(null),t,n))}function Uy(e,t,n,r){if(n.includes("."))throw new Error("key cannot be nested");let i=n;if(n.includes("[x]")){const s=r.type[0].code;i=n.replace("[x]",Hn(s))}t===void 0?delete e[i]:e[i]=t}function By(e,t,n,r){const i=t.split(".");let s=e,c;for(let u=0;u<i.length;u++){let f=i[u];if(f.includes("[x]")){const h=(r?r+".":"")+i.slice(0,u+1).join("."),g=n[h].type[0].code;f=f.replace("[x]",Hn(g))}if(u===i.length-1){Array.isArray(s)?c=s.map(h=>h[f]):c=s[f];continue}if(Array.isArray(s))s=s.map(h=>h[f]);else if(sr(s)){if(s[f]===void 0)return;s=s[f]}else return}return c}function Fh(e,t,n,r){if(!(n.fixed||n.pattern))return e;if(Array.isArray(e))return e.map(u=>Fh(u,t,n,r));e==null&&(e=Object.create(null));const i=e,s=t.split(".");let c=i;for(let u=0;u<s.length;u++){let f=s[u];if(f.includes("[x]")){const m=r[s.slice(0,u+1).join(".")].type[0].code;f=f.replace("[x]",Hn(m))}if(u===s.length-1){const h=Array.isArray(c)?c:[c];for(const m of h)n.fixed?m[f]??(m[f]=n.fixed.value):n.pattern&&(m[f]=QA(m[f],n.pattern.value))}else{if(!(f in c)){const h=s.slice(0,u+1).join(".");c[f]=r[h].isArray?[Object.create(null)]:Object.create(null)}c=c[f]}}return i}function QA(e,t){if(Array.isArray(t)&&(Array.isArray(e)||e===void 0))return((e==null?void 0:e.length)??0)>0?e:Qr(t);if(sr(t)&&(sr(e)&&!Array.isArray(e)||e===void 0)){const n=Qr(e)??Object.create(null);for(const r of Object.keys(t))n[r]=QA(n[r],t[r]);return n}return e}const wV="https://meta.medplum.com/releases",Wv=new Map;function jV(e){const t=e;if(!t.tag_name)throw new Error("Manifest missing tag_name");const n=t.assets;if(!(n!=null&&n.length))throw new Error("Manifest missing assets list");for(const r of n){if(!r.browser_download_url)throw new Error("Asset missing browser download URL");if(!r.name)throw new Error("Asset missing name")}}async function CV(e,t,n){let r=Wv.get("latest");if(!r){const i="latest",s=new URL(`${wV}/${i}.json`);s.searchParams.set("a",e),s.searchParams.set("c",FA);const c=await fetch(s.toString());if(c.status!==200){let f;try{f=(await c.json()).message}catch(h){console.error(`Failed to parse message from body: ${Ye(h)}`)}throw new Error(`Received status code ${c.status} while fetching manifest for version 'latest'. Message: ${f}`)}const u=await c.json();jV(u),r=u,Wv.set("latest",r),Wv.set(r.tag_name.slice(1),r)}return r}async function EV(e){const t=await CV(e);if(!t.tag_name.startsWith("v"))throw new Error(`Invalid release name found. Release tag '${t.tag_name}' did not start with 'v'`);return t.tag_name.slice(1)}const WA=v.createContext(void 0);function Jp(){return v.useContext(WA)}function _e(){return Jp().medplum}function em(){return Jp().navigate}function tm(){return Jp().profile}const AE=["change","storageInitialized","storageInitFailed","profileRefreshing","profileRefreshed"];function TV(e){const t=e.medplum,n=e.navigate??RV,[r,i]=v.useState({profile:t.getProfile(),loading:t.isLoading()});v.useEffect(()=>{function c(){i(u=>({...u,profile:t.getProfile(),loading:t.isLoading()}))}for(const u of AE)t.addEventListener(u,c);return()=>{for(const u of AE)t.removeEventListener(u,c)}},[t]);const s=v.useMemo(()=>({...r,medplum:t,navigate:n}),[r,t,n]);return o.jsx(WA.Provider,{value:s,children:e.children})}function RV(e){window.location.assign(e)}const _E=new Map,YA=e=>v.useMemo(()=>{if(!e)return;const t=e.split("?")[0];if(!t)return e;let n;try{n=new URLSearchParams(new URL(e).search)}catch{return e}if(!n.has("Key-Pair-Id")||!n.has("Signature"))return e;const r=n.get("Expires");if(!r||r.length>13)return e;const i=_E.get(t);if(i){const c=new URLSearchParams(new URL(i).search).get("Expires");if(c&&parseInt(c,10)*1e3-5e3>Date.now())return i}return _E.set(t,e),e},[e]);function DV(e){const t=v.useRef(void 0);return v.useEffect(()=>{t.current=e}),t.current}function Qt(e,t){const n=_e(),[r,i]=v.useState(()=>kE(n,e)),s=v.useCallback(c=>{sa(c,r)||i(c)},[r]);return v.useEffect(()=>{let c=!0;const u=kE(n,e);return!u&&Ko(e)?n.readReference(e).then(f=>{c&&s(f)}).catch(f=>{c&&(s(void 0),t&&t(Zt(f)))}):s(u),()=>c=!1},[n,e,s,t]),r}function kE(e,t){if(t){if(fa(t))return t;if(Ko(t))return e.getCachedReference(t)}}function AV(e,t,n={leading:!1}){const[r,i]=v.useState(e),s=v.useRef(!1),c=v.useRef(void 0),u=v.useRef(!1),f=v.useCallback(()=>window.clearTimeout(c.current),[]);return v.useEffect(()=>{s.current&&(!u.current&&n.leading?(u.current=!0,i(e)):(f(),c.current=setTimeout(()=>{u.current=!1,i(e)},t)))},[e,n.leading,t,f]),v.useEffect(()=>(s.current=!0,f),[f]),[r,f]}const _V=250;function kV(e,t,n){return KA("searchOne",e,t)}function xc(e,t,n){return KA("searchResources",e,t)}function KA(e,t,n,r){const i=_e(),[s,c]=v.useState(),[u,f]=v.useState(!0),[h,m]=v.useState(),[g,y]=v.useState(),b=i.fhirSearchUrl(t,n).toString(),[S]=AV(b,_V,{leading:!0});return v.useEffect(()=>{S!==s&&(c(S),i[e](t,n).then(j=>{f(!1),m(j),y(a8)}).catch(j=>{f(!1),m(void 0),y(Zt(j))}))},[i,e,t,n,s,S]),[h,u,g]}function PV(e){const t=e.value;return t?o.jsx(o.Fragment,{children:RA(t)}):null}const XA=["meta","implicitRules","contained","extension","modifierExtension"],ZA=["language","text"],cn=v.createContext({path:"",profileUrl:void 0,elements:Object.create(null),elementsByPath:Object.create(null),getExtendedProps:()=>({readonly:!1,hidden:!1}),accessPolicyResource:void 0,debugMode:!1,isDefaultContext:!0});cn.displayName="ElementsContext";const pb=["extension","modifierExtension"],NV=["id",...XA].filter(e=>!pb.includes(e));function OV(e){return Object.entries(e).filter(([n,r])=>{var i;return!Tn(r.type)||r.max===0||r.path.toLowerCase().endsWith("extension.url")&&r.fixed||pb.includes(n)&&!Tn((i=r.slicing)==null?void 0:i.slices)||NV.includes(n)?!1:!(ZA.includes(n)&&r.path.split(".").length===2||n.includes("."))})}function PE(e,t){return e.line&&e.line.length>t?e.line[t]:""}function NE(e,t,n){const r=e.line||[];for(;r.length<=t;)r.push("");return r[t]=n,{...e,line:r}}function MV(e){const[t,n]=v.useState(e.defaultValue||{}),r=v.useRef(t);r.current=t;const{getExtendedProps:i}=v.useContext(cn),[s,c,u,f,h,m,g]=v.useMemo(()=>["use","type","line1","line2","city","state","postalCode"].map(R=>i(e.path+"."+R)),[i,e.path]);function y(R){n(R),e.onChange&&e.onChange(R)}function b(R){y({...r.current,use:R})}function S(R){y({...r.current,type:R})}function j(R){y(NE(r.current||{},0,R))}function C(R){y(NE(r.current||{},1,R))}function T(R){y({...r.current,city:R})}function D(R){y({...r.current,state:R})}function E(R){y({...r.current,postalCode:R})}return o.jsxs(Ce,{gap:"xs",wrap:"nowrap",grow:!0,children:[o.jsx(ln,{disabled:e.disabled||(s==null?void 0:s.readonly),"data-testid":"address-use",defaultValue:t.use,onChange:R=>b(R.currentTarget.value),data:["","home","work","temp","old","billing"]}),o.jsx(ln,{disabled:e.disabled||(c==null?void 0:c.readonly),"data-testid":"address-type",defaultValue:t.type,onChange:R=>S(R.currentTarget.value),data:["","postal","physical","both"]}),o.jsx(ze,{disabled:e.disabled||(u==null?void 0:u.readonly),placeholder:"Line 1",defaultValue:PE(t,0),onChange:R=>j(R.currentTarget.value)}),o.jsx(ze,{disabled:e.disabled||(f==null?void 0:f.readonly),placeholder:"Line 2",defaultValue:PE(t,1),onChange:R=>C(R.currentTarget.value)}),o.jsx(ze,{disabled:e.disabled||(h==null?void 0:h.readonly),placeholder:"City",defaultValue:t.city,onChange:R=>T(R.currentTarget.value)}),o.jsx(ze,{disabled:e.disabled||(m==null?void 0:m.readonly),placeholder:"State",defaultValue:t.state,onChange:R=>D(R.currentTarget.value)}),o.jsx(ze,{disabled:e.disabled||(g==null?void 0:g.readonly),placeholder:"Postal Code",defaultValue:t.postalCode,onChange:R=>E(R.currentTarget.value)})]})}function IV(e){const t=tm(),[n,r]=v.useState(e.defaultValue||{});function i(s){const c=s?{text:s,authorReference:t&&on(t),time:new Date().toISOString()}:{};r(c),e.onChange&&e.onChange(c)}return o.jsx(ze,{disabled:e.disabled,name:e.name,placeholder:"Annotation text",defaultValue:n.text,onChange:s=>i(s.currentTarget.value)})}/**
|
|
127
127
|
* @license @tabler/icons-react v3.17.0 - MIT
|
|
128
128
|
*
|
|
129
129
|
* This source code is licensed under the MIT license.
|
|
@@ -463,7 +463,7 @@ function f3(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
|
|
|
463
463
|
*
|
|
464
464
|
* This source code is licensed under the MIT license.
|
|
465
465
|
* See the LICENSE file in the root directory of this source tree.
|
|
466
|
-
*/var TF=Ve("filled","circle-filled","IconCircleFilled",[["path",{d:"M7 3.34a10 10 0 1 1 -4.995 8.984l-.005 -.324l.005 -.324a10 10 0 0 1 4.995 -8.336z",key:"svg-0"}]]);class a_ extends v.Component{constructor(t){super(t),this.state={lastLocation:window.location.toString()}}static getDerivedStateFromError(t){return{error:t,lastLocation:window.location.toString()}}componentDidUpdate(t,n){window.location.toString()!==this.state.lastLocation&&this.setState({lastLocation:window.location.toString(),error:void 0})}shouldComponentUpdate(t,n){return!!(this.props.children!==t.children||n.error&&!this.state.error||this.state.lastLocation!==window.location.toString())}componentDidCatch(t,n){console.error("Uncaught error:",t,n)}render(){return this.state.error?o.jsx(Ya,{icon:o.jsx(rl,{size:16}),title:"Something went wrong",color:"red",children:Ye(this.state.error)}):this.props.children}}function gi(){return o.jsx(er,{style:{width:"100%",height:"100vh"},children:o.jsx(_r,{})})}const RF="_main_6f7o5_1",DF={main:RF};function pn(e){e.preventDefault(),e.stopPropagation()}function o_(e){return e.button===1||e.ctrlKey||e.metaKey}function s_(e){if(LE(e))return!0;if(e instanceof HTMLTableCellElement){const t=e.children;if(t.length===1&&LE(t[0]))return!0}return!1}function LE(e){return e instanceof HTMLInputElement&&e.type==="checkbox"}async function Yu(e,t){return new Promise((n,r)=>{var s;const i=new MessageChannel;i.port1.onmessage=({data:c})=>{i.port1.close(),c.error?r(c.error):n(c.result)},(s=e.contentWindow)==null||s.postMessage(t,new URL(e.src).origin,[i.port2])})}function l_(e,t){const n=new Blob([e],{type:hn.JSON}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r;const s=t??new Date().toISOString().replace(/\D/g,"");i.download=`${s}.json`,document.body.appendChild(i),i.click(),URL.revokeObjectURL(r)}function mt(e){const t=em(),{to:n,suffix:r,label:i,onClick:s,children:c,...u}=e;let f=AF(n);return r&&(f+="/"+r),o.jsx(Nt,{href:f,"aria-label":i,onAuxClick:h=>{h.stopPropagation()},onClick:h=>{h.stopPropagation(),s?(h.preventDefault(),s(h)):n&&(o_(h)||(h.preventDefault(),t(f)))},...u,children:c})}function AF(e){if(e){if(typeof e=="string")return _F(e);if(fa(e))return kF(e);if(Ko(e))return PF(e)}return"#"}function _F(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:"/"+e}function kF(e){return`/${e.resourceType}/${e.id}`}function PF(e){return`/${e.reference}`}function NF(e){const t=e.split(" ").filter(Boolean);return t.length>1?t[0][0]+t[t.length-1][0]:t.length===1?t[0][0]:""}function Xo(e){const t=Qt(e.value),n=t?Va(t):e.alt??"",r=NF(n),i=(t&&
|
|
466
|
+
*/var TF=Ve("filled","circle-filled","IconCircleFilled",[["path",{d:"M7 3.34a10 10 0 1 1 -4.995 8.984l-.005 -.324l.005 -.324a10 10 0 0 1 4.995 -8.336z",key:"svg-0"}]]);class a_ extends v.Component{constructor(t){super(t),this.state={lastLocation:window.location.toString()}}static getDerivedStateFromError(t){return{error:t,lastLocation:window.location.toString()}}componentDidUpdate(t,n){window.location.toString()!==this.state.lastLocation&&this.setState({lastLocation:window.location.toString(),error:void 0})}shouldComponentUpdate(t,n){return!!(this.props.children!==t.children||n.error&&!this.state.error||this.state.lastLocation!==window.location.toString())}componentDidCatch(t,n){console.error("Uncaught error:",t,n)}render(){return this.state.error?o.jsx(Ya,{icon:o.jsx(rl,{size:16}),title:"Something went wrong",color:"red",children:Ye(this.state.error)}):this.props.children}}function gi(){return o.jsx(er,{style:{width:"100%",height:"100vh"},children:o.jsx(_r,{})})}const RF="_main_6f7o5_1",DF={main:RF};function pn(e){e.preventDefault(),e.stopPropagation()}function o_(e){return e.button===1||e.ctrlKey||e.metaKey}function s_(e){if(LE(e))return!0;if(e instanceof HTMLTableCellElement){const t=e.children;if(t.length===1&&LE(t[0]))return!0}return!1}function LE(e){return e instanceof HTMLInputElement&&e.type==="checkbox"}async function Yu(e,t){return new Promise((n,r)=>{var s;const i=new MessageChannel;i.port1.onmessage=({data:c})=>{i.port1.close(),c.error?r(c.error):n(c.result)},(s=e.contentWindow)==null||s.postMessage(t,new URL(e.src).origin,[i.port2])})}function l_(e,t){const n=new Blob([e],{type:hn.JSON}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r;const s=t??new Date().toISOString().replace(/\D/g,"");i.download=`${s}.json`,document.body.appendChild(i),i.click(),URL.revokeObjectURL(r)}function mt(e){const t=em(),{to:n,suffix:r,label:i,onClick:s,children:c,...u}=e;let f=AF(n);return r&&(f+="/"+r),o.jsx(Nt,{href:f,"aria-label":i,onAuxClick:h=>{h.stopPropagation()},onClick:h=>{h.stopPropagation(),s?(h.preventDefault(),s(h)):n&&(o_(h)||(h.preventDefault(),t(f)))},...u,children:c})}function AF(e){if(e){if(typeof e=="string")return _F(e);if(fa(e))return kF(e);if(Ko(e))return PF(e)}return"#"}function _F(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:"/"+e}function kF(e){return`/${e.resourceType}/${e.id}`}function PF(e){return`/${e.reference}`}function NF(e){const t=e.split(" ").filter(Boolean);return t.length>1?t[0][0]+t[t.length-1][0]:t.length===1?t[0][0]:""}function Xo(e){const t=Qt(e.value),n=t?Va(t):e.alt??"",r=NF(n),i=(t&&z$(t))??e.src,s=YA(i??void 0),c=e.radius??"xl",u={...e,value:void 0,link:void 0};return e.link?o.jsx(mt,{to:t,children:o.jsx(zs,{src:s,alt:n,radius:c,...u,children:r})}):o.jsx(zs,{src:s,alt:n,radius:c,...u,children:r})}const OF="_logoButton_189g3_1",MF="_user_189g3_11",IF="_userName_189g3_21",LF="_userActive_189g3_31",sh={logoButton:OF,user:MF,userName:IF,userActive:LF};function bb(e){const t=e.value;return t?o.jsx(o.Fragment,{children:Nc(t,e.options)}):null}function zF(e){var f,h,m;const t=Jp(),{medplum:n,profile:r,navigate:i}=t,s=n.getLogins(),{colorScheme:c,setColorScheme:u}=SO();return o.jsxs(o.Fragment,{children:[o.jsxs(Ge,{align:"center",p:"xl",children:[o.jsx(Xo,{size:"xl",radius:100,value:t.profile}),o.jsx(bb,{value:(h=(f=t.profile)==null?void 0:f.name)==null?void 0:h[0]}),o.jsx(Ae,{c:"dimmed",size:"xs",children:(m=n.getActiveLogin())==null?void 0:m.project.display})]}),s.length>1&&o.jsx(je.Divider,{}),s.map(g=>g.profile.reference!==zt(t.profile)&&o.jsx(je.Item,{onClick:()=>{n.setActiveLogin(g).then(()=>window.location.reload()).catch(console.log)},children:o.jsxs(Ce,{children:[o.jsx(zs,{radius:"xl"}),o.jsxs("div",{style:{flex:1},children:[o.jsx(Ae,{size:"sm",fw:500,children:g.profile.display}),o.jsx(Ae,{c:"dimmed",size:"xs",children:g.project.display})]})]})},g.profile.reference)),o.jsx(je.Divider,{}),o.jsx(Ce,{justify:"center",children:o.jsx(Fp,{size:"xs",value:c,onChange:g=>u(g),data:[{label:"Light",value:"light"},{label:"Dark",value:"dark"},{label:"Auto",value:"auto"}]})}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(wF,{size:14,stroke:1.5}),onClick:()=>i("/signin"),children:"Add another account"}),o.jsx(je.Item,{leftSection:o.jsx(Vy,{size:14,stroke:1.5}),onClick:()=>i(`/${zt(r)}`),children:"Account settings"}),o.jsx(je.Item,{leftSection:o.jsx(sF,{size:14,stroke:1.5}),onClick:async()=>{await n.signOut(),i("/signin")},children:"Sign out"}),o.jsx(Ae,{size:"xs",c:"dimmed",ta:"center",children:e.version})]})}const zE={selectedItems:"selected-items",options:"options"};function Sb(e){const t=xd({onDropdownClose:()=>t.resetSelectedOption(),onDropdownOpen:()=>t.updateSelectedOptionIndex("active")}),{name:n,label:r,description:i,error:s,defaultValue:c,toOption:u,loadOptions:f,itemComponent:h,pillComponent:m,emptyComponent:g,onChange:y,onCreate:b,creatable:S,clearable:j,required:C,placeholder:T,leftSection:D,maxValues:E,optionsDropdownMaxHeight:R=320,minInputLength:A=0,...k}=e,M=k.disabled,I=$F(c),[$,V]=v.useState(""),[Y,Q]=v.useState(),[J,G]=v.useState(),[Z,P]=v.useState(),[L,z]=v.useState(I.map(u)),[H,O]=v.useState([]),U=h??UF,K=m??BF,ee=g??VF,Se=v.useRef($);Se.current=$;const be=v.useRef(void 0),xe=v.useRef(void 0),qe=v.useRef(Y);qe.current=Y;const Me=v.useRef(J);Me.current=J;const tt=v.useRef(Z);tt.current=Z;const ke=v.useRef(H);ke.current=H;const vt=v.useCallback(()=>{var me;if(Q(void 0),Se.current===xe.current&&f===be.current||(((me=Se.current)==null?void 0:me.length)??0)<A)return;xe.current=Se.current,be.current=f;const Re=new AbortController;G(Re),f(Se.current??"",Re.signal).then(ge=>{Re.signal.aborted||(O(ge.map(u)),tt.current?(ge.length>0&&y(ge.slice(0,1)),P(!1)):ge.length>0&&t.openDropdown())}).catch(ge=>{Re.signal.aborted||ge.message.includes("aborted")||Oe({color:"red",message:Ye(ge)})}).finally(()=>{Re.signal.aborted||G(void 0)})},[t,f,y,u,A]),It=v.useCallback(Re=>{(H&&H.length>0||S)&&t.openDropdown(),t.updateSelectedOptionIndex(),V(Re.currentTarget.value),Me.current&&(Me.current.abort(),G(void 0)),qe.current!==void 0&&window.clearTimeout(qe.current);const me=window.setTimeout(()=>vt(),100);Q(me)},[t,H,S,vt]),Lt=v.useCallback(Re=>{const me=L.some(we=>we.value===Re),ge=me?L.filter(we=>we.value!==Re):[...L];let Pe=H==null?void 0:H.find(we=>we.value===Re);if(!Pe&&S!==!1&&b){const we=b(Re);Pe=u(we)}if(Pe){if(E===0){y([Pe.resource]),L.length>0&&z([]);return}me||ge.push(Pe)}if(E!==void 0)for(;ge.length>E;)ge.shift();y(ge.map(we=>we.resource)),z(ge)},[S,H,L,E,y,b,u]),gt=v.useMemo(()=>{if(!M)return Re=>{M||(E===1&&(V(""),O([]),t.closeDropdown()),xe.current=void 0,Re==="$create"?(V(""),Lt($)):Lt(Re))}},[Lt,t,M,E,$]),At=v.useCallback(Re=>{const me=L.filter(ge=>ge.value!==Re.value);y(me.map(ge=>ge.resource)),z(me)},[L,y]),nn=v.useCallback(Re=>{Re.key==="Enter"?(Y||J)&&P(!0):Re.key==="Backspace"&&$.length===0&&(pn(Re),At(L[L.length-1]))},[J,At,$.length,L,Y]);v.useEffect(()=>()=>{Me.current&&Me.current.abort()},[]);const Ee=!M&&j&&L.length>0&&o.jsx(ct.ClearButton,{title:"Clear all",size:"sm",onClear:()=>{V(""),z([]),y([]),t.closeDropdown()}}),De=S&&$.trim().length>0,Qe=H.length>0||De;return o.jsxs(ct,{store:t,onOptionSubmit:gt,withinPortal:!0,shadow:"xl",...k,children:[o.jsx(ct.DropdownTarget,{children:o.jsx(pc,{label:r,description:i,error:s,className:e.className,leftSection:D,rightSection:J?o.jsx(_r,{size:16}):Ee,required:C,disabled:M,children:o.jsxs($s.Group,{"data-testid":zE.selectedItems,children:[L.map(Re=>o.jsx(K,{item:Re,disabled:M,onRemove:()=>At(Re)},Re.value)),!M&&(E===void 0||E===0||L.length<E)&&o.jsx(ct.EventsTarget,{children:o.jsx(pc.Field,{role:"searchbox",name:n,value:$,placeholder:T,onFocus:It,onBlur:()=>{t.closeDropdown(),V("")},onKeyDown:nn,onChange:It})})]})})}),o.jsx(ct.Dropdown,{hidden:!Qe,"data-testid":zE.options,children:o.jsx(ct.Options,{children:o.jsxs(gp,{type:"scroll",mah:R,children:[H.map(Re=>{const me=L.some(ge=>ge.value===Re.value);return o.jsx(ct.Option,{value:Re.value,active:me,children:o.jsx(U,{...Re,active:me})},Re.value)}),De&&o.jsxs(ct.Option,{value:"$create",children:["+ Create ",$]}),!S&&$.trim().length>0&&H.length===0&&o.jsx(ee,{search:$})]})})})]})}function $F(e){return e?Array.isArray(e)?e:[e]:[]}function UF(e){return o.jsxs(Ce,{gap:"xs",children:[e.active&&o.jsx(eo,{size:12}),o.jsx("span",{children:e.label})]})}function BF({item:e,disabled:t,onRemove:n}){return o.jsx($s,{withRemoveButton:!t,onRemove:n,children:e.label})}function VF(){return o.jsx(ct.Empty,{children:"Nothing found"})}const FF="_searchInput_dick8_1",HF={searchInput:FF};function qF(e){return{value:e.id,label:Va(e),resource:e}}function GF(e){const t=em(),n=_e(),r=v.useCallback(async(s,c)=>{const u=WF(s),f={signal:c},h=await n.graphql(u,void 0,void 0,f);return YF(h,s)},[n]),i=v.useCallback(s=>{s.length>0&&t(`/${zt(s[0])}`)},[t]);return o.jsx(Sb,{size:"sm",radius:"md",className:HF.searchInput,leftSection:o.jsx(xF,{size:16}),placeholder:"Search",itemComponent:QF,toOption:qF,onChange:i,loadOptions:r,maxValues:0,clearable:!1},`${e.pathname}?${e.searchParams}`)}const QF=v.forwardRef(({resource:e,active:t,...n},r)=>{var s;let i;return e.resourceType==="Patient"?i=e.birthDate:e.resourceType==="ServiceRequest"&&(i=(s=e.subject)==null?void 0:s.display),o.jsx("div",{ref:r,...n,children:o.jsxs(Ce,{wrap:"nowrap",children:[o.jsx(Xo,{value:e}),o.jsxs("div",{children:[o.jsx(Ae,{children:Va(e)}),o.jsx(Ae,{size:"xs",c:"dimmed",children:i})]})]})})});function WF(e){const t=JSON.stringify(e);return SA(e)?`{
|
|
467
467
|
Patients1: PatientList(_id: ${t}, _count: 1) {
|
|
468
468
|
resourceType
|
|
469
469
|
id
|
|
@@ -533,7 +533,7 @@ function f3(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
|
|
|
533
533
|
name,
|
|
534
534
|
title,
|
|
535
535
|
}
|
|
536
|
-
}`.replace(/\s+/g," ");return(await e.graphql(r)).data.StructureDefinitionList[0]}function Mq(e){return e.type==="profile"&&!(e!=null&&e.error)&&Rn(e.resourceType)}function Iq(e,t,n){return t===void 0?e:n===void 0?t:`${t}[${n}]`}const Lq="_indented_ldk1d_1",A_={indented:Lq};function Ab({propertyDisplayName:e,onClick:t,testId:n}){const r=e?`Add ${e}`:"Add";return e?o.jsx(Ne,{title:r,size:"sm",color:"green.6",variant:"subtle","data-testid":n,leftSection:o.jsx(qh,{size:"1.25rem"}),onClick:t,children:r}):o.jsx(_n,{title:r,color:"green.6","data-testid":n,onClick:t,children:o.jsx(qh,{size:"1.25rem"})})}function __({propertyDisplayName:e,onClick:t,testId:n}){return o.jsx(_n,{title:e?`Remove ${e}`:"Remove",color:"red.5","data-testid":n,variant:"subtle",onClick:t,children:o.jsx(Hh,{size:"1.25rem"})})}function zq(e){var b,S;const{slice:t,property:n}=e,[r,i]=v.useState(e.defaultValue),s=((b=t.typeSchema)==null?void 0:b.elements)??t.elements,c=v.useContext(cn),u=v.useMemo(()=>{var j;if(Tn(s))return yc({parentContext:c,elements:s,path:e.path,profileUrl:(j=t.typeSchema)==null?void 0:j.url})},[c,e.path,(S=t.typeSchema)==null?void 0:S.url,s]);function f(j){i(j),e.onChange&&e.onChange(j)}const h=t.min>0,m=Rn(t.elements),g=kA(t.name),y=e.property.readonly&&r.length===0;return am(cn.Provider,u,o.jsx($t,{title:g,description:t.definition,withAsterisk:h,fhirPath:`${n.path}:${t.name}`,testId:e.testId,readonly:e.property.readonly,children:y?o.jsx(Ae,{c:"dimmed",children:"(empty)"}):o.jsxs(Ge,{className:m?A_.indented:void 0,children:[r.map((j,C)=>o.jsxs(Ce,{wrap:"nowrap",children:[o.jsx("div",{style:{flexGrow:1},"data-testid":e.testId&&`${e.testId}-elements-${C}`,children:o.jsx(_b,{elementDefinitionType:t.type[0],name:t.name,defaultValue:j,onChange:T=>{const D=[...r];D[C]=T,f(D)},outcome:e.outcome,min:t.min,max:t.max,binding:t.binding,path:e.path,valuePath:void 0,readOnly:e.property.readonly})}),!e.property.readonly&&r.length>t.min&&o.jsx(__,{propertyDisplayName:g,testId:e.testId&&`${e.testId}-remove-${C}`,onClick:T=>{pn(T);const D=[...r];D.splice(C,1),f(D)}})]},`${C}-${r.length}`)),!e.property.readonly&&r.length<t.max&&o.jsx(Ce,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:o.jsx(Ab,{propertyDisplayName:g,onClick:j=>{pn(j);const C=[...r,void 0];f(C)},testId:e.testId&&`${e.testId}-add`})})]})}))}function $q(e){var D;const{property:t}=e,n=_e(),[r,i]=v.useState(!0),[s,c]=v.useState([]),[u]=v.useState(()=>Array.isArray(e.defaultValue)?e.defaultValue:[]),[f,h]=v.useState(()=>[u]),m=v.useContext(cn),g=(D=t.type[0])==null?void 0:D.code;v.useEffect(()=>{j_({medplum:n,property:t}).then(E=>{c(E);const R=w_(u,E,t.slicing,m.profileUrl);Uq(R,E),h(R),i(!1)}).catch(E=>{console.error(E),i(!1)})},[n,t,u,m.profileUrl,h]);function y(E,R){const A=[...f];if(A[R]=E,h(A),e.onChange){const k=A.flat().filter(M=>M!==void 0);e.onChange(k)}}if(r)return o.jsx("div",{children:"Loading..."});const b=s.length,S=f[b],j=!(e.hideNonSliceValues??(g==="Extension"&&s.length>0)),C=Vs(t.path),T=e.property.readonly&&s.length===0&&u.length===0;return o.jsxs(Ge,{className:e.indent?A_.indented:void 0,children:[T&&o.jsx(Ae,{c:"dimmed",children:"(empty)"}),s.map((E,R)=>o.jsx(zq,{slice:E,path:e.path,valuePath:e.valuePath,property:t,defaultValue:f[R],onChange:A=>{y(A,R)},testId:`slice-${E.name}`},E.name)),j&&S.map((E,R)=>o.jsxs(Ce,{wrap:"nowrap",style:{flexGrow:1},children:[o.jsx("div",{style:{flexGrow:1},children:o.jsx(Id,{arrayElement:!0,property:e.property,name:e.name+"."+R,path:e.path,valuePath:Iq(e.path,e.valuePath,R),defaultValue:E,onChange:A=>{const k=[...S];k[R]=A,y(k,b)},defaultPropertyType:void 0,outcome:e.outcome})}),!e.property.readonly&&o.jsx(__,{propertyDisplayName:C,testId:`nonsliced-remove-${R}`,onClick:A=>{pn(A);const k=[...S];k.splice(R,1),y(k,b)}})]},`${R}-${S.length}`)),!e.property.readonly&&j&&f.flat().length<t.max&&o.jsx(Ce,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:o.jsx(Ab,{propertyDisplayName:C,onClick:E=>{pn(E);const R=[...S];R.push(void 0),y(R,b)},testId:"nonsliced-add"})})]})}function Uq(e,t){for(let n=0;n<t.length;n++){const r=t[n],i=e[n];for(;i.length<r.min;)i.push(void 0)}}function Bq(e){const[t,n]=v.useState(!1),r=pR(),i=v.useRef(null),s={...e.styles};return t||(s.input||(s.input={}),s.input.WebkitTextSecurity="disc"),o.jsxs(Vo,{gap:"xs",children:[o.jsx(Js,{...e,styles:{...s,root:{...s.root??{},flexGrow:1}},ref:i,autosize:!0,minRows:1,onFocus:()=>n(!0),onBlur:()=>n(!1)}),o.jsx(_n,{title:"Copy secret",onClick:()=>{var c;r.copy((c=i.current)==null?void 0:c.value),Oe({color:"green",message:"Copied"})},children:o.jsx(JA,{})})]})}const Vq=["sun","mon","tue","wed","thu","fri","sat"];function Fq(e){const[t,n]=v.useState(e.defaultValue),[r,i]=v.useState(!e.disabled&&(e.defaultModalOpen??!1)),s=v.useRef(t);return s.current=t,o.jsxs(o.Fragment,{children:[o.jsxs(Ce,{gap:"xs",grow:!0,wrap:"nowrap",children:[o.jsx("span",{children:DA(s.current)||"No repeat"}),o.jsx(Ne,{disabled:e.disabled,onClick:()=>i(!0),children:"Edit"})]}),!e.disabled&&o.jsx(Hq,{path:e.path,visible:r,defaultValue:s.current,onOk:c=>{e.onChange&&e.onChange(c),n(c),i(!1)},onCancel:()=>i(!1)})]})}const HE={repeat:{period:1,periodUnit:"d"}};function Hq(e){const[t,n]=v.useState(e.defaultValue||HE),{getExtendedProps:r}=v.useContext(cn),[i,s,c,u,f]=v.useMemo(()=>["event","repeat","repeat.period","repeat.periodUnit","repeat.dayOfWeek"].map(j=>r(e.path+"."+j)),[r,e.path]),h=v.useRef(t);h.current=t;function m(j){n({...h.current,event:[j]})}function g(j){n({...h.current,repeat:j})}function y(j){var C;g({...(C=h.current)==null?void 0:C.repeat,period:j})}function b(j){var C;g({...(C=h.current)==null?void 0:C.repeat,periodUnit:j})}function S(j){var C;g({...(C=h.current)==null?void 0:C.repeat,dayOfWeek:j})}return o.jsx($n,{title:"Timing",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:()=>e.onCancel(),children:o.jsxs(Ge,{children:[o.jsx($t,{title:"Starts on",htmlFor:"timing-dialog-start",children:o.jsx(aa,{disabled:i==null?void 0:i.readonly,name:"timing-dialog-start",onChange:j=>m(j)})}),o.jsx(Cd,{disabled:s==null?void 0:s.readonly,label:"Repeat",checked:!!t.repeat,onChange:j=>g(j.currentTarget.checked?HE.repeat:void 0)}),t.repeat&&o.jsxs(o.Fragment,{children:[o.jsx($t,{title:"Repeat every",htmlFor:"timing-dialog-period",children:o.jsxs(Ce,{gap:"xs",grow:!0,wrap:"nowrap",children:[o.jsx(ze,{disabled:c==null?void 0:c.readonly,type:"number",step:1,id:"timing-dialog-period",name:"timing-dialog-period",defaultValue:t.repeat.period||1,onChange:j=>y(parseInt(j.currentTarget.value,10)||1)}),o.jsx(ln,{disabled:u==null?void 0:u.readonly,id:"timing-dialog-periodUnit",name:"timing-dialog-periodUnit",defaultValue:t.repeat.periodUnit,onChange:j=>b(j.currentTarget.value),data:[{label:"second",value:"s"},{label:"minute",value:"min"},{label:"hour",value:"h"},{label:"day",value:"d"},{label:"week",value:"wk"},{label:"month",value:"mo"},{label:"year",value:"a"}]})]})}),t.repeat.periodUnit==="wk"&&o.jsx($t,{title:"Repeat on",children:o.jsx(td.Group,{multiple:!0,onChange:S,children:o.jsx(Ce,{justify:"space-between",mt:"md",gap:"xs",children:Vq.map(j=>o.jsx(td,{value:j,size:"xs",radius:"xl",disabled:f==null?void 0:f.readonly,children:j.charAt(0).toUpperCase()},j))})})})]}),o.jsx(Ce,{justify:"flex-end",children:o.jsx(Ne,{onClick:()=>e.onOk(t),children:"OK"})})]})})}function Id(e){var u;const{property:t,name:n,onChange:r,defaultValue:i}=e,s=e.defaultPropertyType&&e.defaultPropertyType!=="undefined"?e.defaultPropertyType:t.type[0].code,c=t.type;if((t.isArray||t.max>1)&&!e.arrayElement){if(s===oe.Attachment)return o.jsx(TH,{name:n,defaultValue:i,onChange:r,disabled:t.readonly});const f=((u=c[0])==null?void 0:u.code)!==oe.Extension;return o.jsx($q,{property:t,name:n,path:e.path,valuePath:e.valuePath,defaultValue:i,indent:f,onChange:r,outcome:e.outcome})}else return c.length>1?o.jsx(qq,{elementDefinitionTypes:c,...e}):o.jsx(_b,{name:n,defaultValue:i,onChange:f=>{if(e.onChange){const h=e.name.replace("[x]",Hn(c[0].code));e.onChange(f,h)}},outcome:e.outcome,elementDefinitionType:c[0],min:t.min,max:t.min,binding:t.binding,path:e.path,valuePath:e.valuePath,readOnly:t.readonly})}function qq(e){const t=e.elementDefinitionTypes;let n;e.defaultPropertyType&&(n=t.find(s=>s.code===e.defaultPropertyType)),n||(n=t[0]);const[r,i]=v.useState(n);return o.jsxs(Ce,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[o.jsx(ln,{disabled:e.property.readonly,style:{width:"200px"},defaultValue:r.code,"data-testid":e.name&&e.name+"-selector",onChange:s=>{i(t.find(c=>c.code===s.currentTarget.value))},data:t.map(s=>({value:s.code,label:s.code}))}),o.jsx(_b,{name:e.name,defaultValue:e.defaultValue,outcome:e.outcome,elementDefinitionType:r,onChange:s=>{e.onChange&&e.onChange(s,e.name.replace("[x]",Hn(r.code)))},min:e.property.min,max:e.property.max,binding:e.property.binding,path:e.property.path,valuePath:e.valuePath,readOnly:e.property.readonly})]})}function _b(e){const{name:t,onChange:n,outcome:r,binding:i,path:s,valuePath:c,readOnly:u}=e,f=e.min!==void 0&&e.min>0,h=e.elementDefinitionType.code,m=v.useContext(cn),g=v.useMemo(()=>{if(!eb(h)||!Rn(e.defaultValue))return e.defaultValue;const S=Object.create(null);if(m.path===e.path)DE(S,m.elements);else{const j=ks(m.path,e.path);if(j===void 0)return e.defaultValue;DE(S,m.elements,j)}return Tn(S)?S:e.defaultValue},[h,m.path,m.elements,e.path,e.defaultValue]);if(!h)return o.jsx("div",{children:"Property type not specified "});function y(){return{name:t,defaultValue:g,onChange:n,outcome:r,path:s,valuePath:c,disabled:u}}function b(){const S=Ot(e.outcome,c??s);return{id:t,name:t,"data-testid":t,defaultValue:g,required:f,error:S,disabled:u}}switch(h){case oe.SystemString:case oe.canonical:case oe.string:case oe.time:case oe.uri:case oe.url:return e.path==="Project.secret.value[x]"?o.jsx(Bq,{...b(),onChange:S=>{e.onChange&&e.onChange(S.currentTarget.value)}}):o.jsx(ze,{...b(),onChange:S=>{n&&n(S.currentTarget.value)}});case oe.date:return o.jsx(ze,{...b(),type:"date",onChange:S=>{n&&n(S.currentTarget.value)}});case oe.dateTime:case oe.instant:return o.jsx(aa,{...b(),onChange:n,outcome:r});case oe.decimal:case oe.integer:case oe.positiveInt:case oe.unsignedInt:return o.jsx(ze,{...b(),type:"number",step:h===oe.decimal?"any":"1",onChange:S=>{if(n){const j=S.currentTarget.valueAsNumber;n(Number.isNaN(j)?void 0:j)}}});case oe.code:return o.jsx(u_,{...b(),error:void 0,onChange:n,binding:i==null?void 0:i.valueSet,creatable:!0,maxValues:1});case oe.boolean:return o.jsx(Fn,{...b(),defaultChecked:!!g,onChange:S=>{n&&n(S.currentTarget.checked)}});case oe.base64Binary:case oe.markdown:return o.jsx(Js,{...b(),spellCheck:h!==oe.base64Binary,onChange:S=>{n&&n(S.currentTarget.value)}});case oe.Address:return o.jsx(MV,{...y()});case oe.Annotation:return o.jsx(IV,{...y()});case oe.Attachment:return o.jsx(d_,{...y()});case oe.CodeableConcept:return o.jsx(uq,{binding:i==null?void 0:i.valueSet,...y()});case oe.Coding:return o.jsx(hq,{binding:i==null?void 0:i.valueSet,...y()});case oe.ContactDetail:return o.jsx(gq,{...y()});case oe.ContactPoint:return o.jsx(D_,{...y()});case oe.Extension:return o.jsx(xq,{...y(),propertyType:e.elementDefinitionType});case oe.HumanName:return o.jsx(bq,{...y()});case oe.Identifier:return o.jsx(Sq,{...y()});case oe.Money:return o.jsx(jq,{...y()});case oe.Period:return o.jsx(Cq,{...y()});case oe.Duration:case oe.Quantity:return o.jsx(qs,{...y()});case oe.Range:return o.jsx(Db,{...y()});case oe.Ratio:return o.jsx(Tq,{...y()});case oe.Reference:return o.jsx(Md,{...y(),targetTypes:Qq(e.elementDefinitionType)});case oe.Timing:return o.jsx(Fq,{...y()});case oe.Dosage:case oe.UsageContext:default:return o.jsx(kb,{...y(),typeName:h})}}const Gq=[`${Dd}/fhir/StructureDefinition/`,"https://medplum.com/fhir/StructureDefinition/"];function Qq(e){var t;return(t=e==null?void 0:e.targetProfile)==null?void 0:t.map(n=>{const r=Gq.find(i=>n.startsWith(i));return r?n.slice(r.length):n})}function Wq(e){const[t,n]=v.useState(e.defaultValue??{}),r=v.useContext(cn),i=v.useMemo(()=>OV(r.elements),[r.elements]);function s(u){n(u),e.onChange&&e.onChange(u)}const c={type:e.type,value:t};return o.jsx(Ge,{style:{flexGrow:1},"data-testid":e.testId,children:i.map(([u,f])=>{const[h,m]=ZH(c,u,f),g=f.min!==void 0&&f.min>0,y=e.valuePath?e.valuePath+"."+u:void 0,b=o.jsx(Id,{property:f,name:u,path:e.path+"."+u,valuePath:y,defaultValue:h,defaultPropertyType:m,onChange:(S,j)=>{s(lq({...t},u,j??u,f,S))},outcome:e.outcome},u);return e.type==="Extension"||pb.includes(u)?b:f.type.length===1&&f.type[0].code==="boolean"?o.jsx(R_,{title:Vs(u),description:f.description,htmlFor:u,fhirPath:f.path,withAsterisk:g,readonly:f.readonly,children:b},u):o.jsx($t,{title:Vs(u),description:f.description,withAsterisk:g,htmlFor:u,outcome:e.outcome,fhirPath:f.path,errorExpression:y,readonly:f.readonly,children:b},u)})})}function kb(e){const[t]=v.useState(()=>e.defaultValue??{}),n=v.useContext(cn),r=e.profileUrl??(n==null?void 0:n.profileUrl),i=v.useMemo(()=>Gp(e.typeName,r),[e.typeName,r]),s=(i==null?void 0:i.type)??e.typeName,c=v.useMemo(()=>{if(i)return yc({parentContext:n,elements:i.elements,path:e.path,profileUrl:i.url,accessPolicyResource:e.accessPolicyResource})},[i,n,e.path,e.accessPolicyResource]);return i?am(cn.Provider,c,o.jsx(Wq,{path:e.path,valuePath:e.valuePath,type:s,defaultValue:t,onChange:e.onChange,outcome:e.outcome})):o.jsxs("div",{children:[s," not implemented"]})}const Yq="_noteCite_10swh_5",Kq="_noteRoot_10swh_10",qE={noteCite:Yq,noteRoot:Kq};function k_({value:e}){return e?o.jsx(Ge,{justify:"flex-start",gap:"xs",children:e.map(t=>{var n;return t.text&&o.jsx(c0,{classNames:{cite:qE.noteCite,root:qE.noteRoot},cite:((n=t.authorReference)==null?void 0:n.display)||t.authorString,icon:null,children:t.text},`note-${t.text}`)})}):null}function Lc(e){const{value:t,link:n,...r}=e,[i,s]=v.useState(),c=Qt(t,s);let u;if(i&&!oA(i))u=`[${Ye(i)}]`;else if(c)u=Va(c);else return null;return n?o.jsx(mt,{to:t,...r,children:u}):o.jsx(Ae,{component:"span",...r,children:u})}function oc(e){return o.jsxs(Ce,{gap:"xs",children:[o.jsx(Xo,{size:24,radius:12,value:e.value,link:e.link}),o.jsx(Lc,{value:e.value,link:e.link})]})}const Xq={draft:"blue",active:"blue","on-hold":"yellow",revoked:"red",completed:"green","entered-in-error":"red",unknown:"gray",retired:"gray",registered:"blue",preliminary:"blue",final:"green",amended:"yellow",corrected:"yellow",cancelled:"red",requested:"blue",received:"blue",accepted:"blue",rejected:"red",ready:"blue","in-progress":"blue",failed:"red",proposed:"blue",pending:"blue",booked:"blue",arrived:"blue",fulfilled:"green",noshow:"red","checked-in":"blue",waitlist:"gray",routine:"gray",urgent:"red",asap:"red",stat:"red","not-done":"red",connected:"green",disconnected:"red",finished:"green",planned:"gray"};function om(e){const{status:t,...n}=e;return o.jsx(Cp,{color:e.color||Xq[t],...n,children:t.replace(/-/g," ")})}const Zq="_table_pe9td_1",Jq="_criticalRow_pe9td_12",P_={table:Zq,criticalRow:Jq};Pb.defaultProps={hideObservationNotes:!1,hideSpecimenInfo:!1,hideSubject:!1};function Pb(e){var c;const t=_e(),n=Qt(e.value),[r,i]=v.useState();if(v.useEffect(()=>{n!=null&&n.specimen&&Promise.allSettled(n.specimen.map(u=>t.readReference(u))).then(u=>u.filter(f=>f.status==="fulfilled").map(f=>f.value)).then(i).catch(console.error)},[t,n]),!n)return null;const s=(r==null?void 0:r.flatMap(u=>u.note||[]))||[];if(n.presentedForm&&n.presentedForm.length>0){const u=n.presentedForm[0];(c=u.contentType)!=null&&c.startsWith("text/plain")&&u.data&&s.push({text:window.atob(u.data)})}return o.jsxs(Ge,{children:[o.jsx(Le,{children:"Diagnostic Report"}),o.jsx(eG,{value:n,hideSubject:e.hideSubject}),r&&!e.hideSpecimenInfo&&tG(r),n.result&&o.jsx(nG,{hideObservationNotes:e.hideObservationNotes,value:n.result}),s.length>0&&o.jsx(k_,{value:s})]})}function eG({value:e,hideSubject:t=!1}){var n,r;return o.jsxs(Ce,{mt:"md",gap:30,children:[e.subject&&!t&&o.jsxs("div",{children:[o.jsx(Ae,{size:"xs",tt:"uppercase",c:"dimmed",children:"Subject"}),o.jsx(oc,{value:e.subject,link:!0})]}),(n=e.resultsInterpreter)==null?void 0:n.map(i=>o.jsxs("div",{children:[o.jsx(Ae,{size:"xs",tt:"uppercase",c:"dimmed",children:"Interpreter"}),o.jsx(oc,{value:i,link:!0})]},i.reference)),(r=e.performer)==null?void 0:r.map(i=>o.jsxs("div",{children:[o.jsx(Ae,{size:"xs",tt:"uppercase",c:"dimmed",children:"Performer"}),o.jsx(oc,{value:i,link:!0})]},i.reference)),e.issued&&o.jsxs("div",{children:[o.jsx(Ae,{size:"xs",tt:"uppercase",c:"dimmed",children:"Issued"}),o.jsx(Ae,{children:gr(e.issued)})]}),e.status&&o.jsxs("div",{children:[o.jsx(Ae,{size:"xs",tt:"uppercase",c:"dimmed",children:"Status"}),o.jsx(om,{status:e.status})]})]})}function tG(e){return o.jsxs(Ge,{gap:"xs",children:[o.jsx(Le,{order:2,size:"h6",children:"Specimens"}),o.jsx(pr,{type:"ordered",children:e==null?void 0:e.map(t=>{var n;return o.jsx(pr.Item,{ml:"sm",children:o.jsxs(Ce,{gap:20,children:[o.jsxs(Ce,{gap:5,children:[o.jsx(Ae,{fw:500,children:"Collected:"})," ",gr((n=t.collection)==null?void 0:n.collectedDateTime)]}),o.jsxs(Ce,{gap:5,children:[o.jsx(Ae,{fw:500,children:"Received:"})," ",gr(t.receivedTime)]})]})},`specimen-${t.id}`)})})]})}function nG(e){return o.jsxs("table",{className:P_.table,children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Test"}),o.jsx("th",{children:"Value"}),o.jsx("th",{children:"Reference Range"}),o.jsx("th",{children:"Interpretation"}),o.jsx("th",{children:"Category"}),o.jsx("th",{children:"Performer"}),o.jsx("th",{children:"Status"})]})}),o.jsx("tbody",{children:o.jsx(N_,{value:e.value,ancestorIds:e.ancestorIds,hideObservationNotes:e.hideObservationNotes})})]})}function N_(e){var t;return o.jsx(o.Fragment,{children:(t=e.value)==null?void 0:t.map(n=>o.jsx(rG,{value:n,ancestorIds:e.ancestorIds,hideObservationNotes:e.hideObservationNotes},`obs-${Ko(n)?n.reference:n.id}`))})}function rG(e){var i,s;const t=Qt(e.value);if(!t||(i=e.ancestorIds)!=null&&i.includes(t.id))return null;const n=!e.hideObservationNotes&&t.note,r=oG(t);return o.jsxs(o.Fragment,{children:[o.jsxs("tr",{className:Ut({[P_.criticalRow]:r}),children:[o.jsx("td",{rowSpan:n?2:1,children:o.jsx(mt,{to:t,children:o.jsx(ia,{value:t.code})})}),o.jsx("td",{children:o.jsx(iG,{value:t})}),o.jsx("td",{children:o.jsx(aG,{value:t.referenceRange})}),o.jsx("td",{children:t.interpretation&&t.interpretation.length>0&&o.jsx(ia,{value:t.interpretation[0]})}),o.jsx("td",{children:t.category&&t.category.length>0&&o.jsx(o.Fragment,{children:t.category.map(c=>o.jsx("div",{children:o.jsx(ia,{value:c})},`category-${Fo(c)}`))})}),o.jsx("td",{children:(s=t.performer)==null?void 0:s.map(c=>o.jsx(Hy,{value:c},c.reference))}),o.jsx("td",{children:t.status&&o.jsx(om,{status:t.status})})]}),t.hasMember&&o.jsx(N_,{value:t.hasMember,ancestorIds:e.ancestorIds?[...e.ancestorIds,t.id]:[t.id],hideObservationNotes:e.hideObservationNotes}),n&&o.jsx("tr",{children:o.jsx("td",{colSpan:6,children:o.jsx(k_,{value:t.note})})})]})}function iG(e){const t=e.value;return o.jsx(o.Fragment,{children:AA(t)})}function aG(e){const t=e.value&&e.value.length>0&&e.value[0];return t?t.text?o.jsx(o.Fragment,{children:t.text}):o.jsx(Tb,{value:t}):null}function oG(e){var n,r,i,s;const t=(s=(i=(r=(n=e.interpretation)==null?void 0:n[0])==null?void 0:r.coding)==null?void 0:i[0])==null?void 0:s.code;return t==="AA"||t==="LL"||t==="HH"||t==="A"}var Yv={},Na={},GE;function O_(){if(GE)return Na;GE=1,Object.defineProperty(Na,"__esModule",{value:!0}),Na.Pointer=Na.escapeToken=Na.unescapeToken=void 0;function e(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}Na.unescapeToken=e;function t(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}Na.escapeToken=t;var n=function(){function r(i){i===void 0&&(i=[""]),this.tokens=i}return r.fromJSON=function(i){var s=i.split("/").map(e);if(s[0]!=="")throw new Error("Invalid JSON Pointer: ".concat(i));return new r(s)},r.prototype.toString=function(){return this.tokens.map(t).join("/")},r.prototype.evaluate=function(i){for(var s=null,c="",u=i,f=1,h=this.tokens.length;f<h;f++)s=u,c=this.tokens[f],!(c=="__proto__"||c=="constructor"||c=="prototype")&&(u=(s||{})[c]);return{parent:s,key:c,value:u}},r.prototype.get=function(i){return this.evaluate(i).value},r.prototype.set=function(i,s){var c=this.evaluate(i);c.parent&&(c.parent[c.key]=s)},r.prototype.push=function(i){this.tokens.push(i)},r.prototype.add=function(i){var s=this.tokens.concat(String(i));return new r(s)},r}();return Na.Pointer=n,Na}var gn={},Kv={},QE;function M_(){return QE||(QE=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.clone=e.objectType=e.hasOwnProperty=void 0,e.hasOwnProperty=Object.prototype.hasOwnProperty;function t(i){return i===void 0?"undefined":i===null?"null":Array.isArray(i)?"array":typeof i}e.objectType=t;function n(i){return i!=null&&typeof i=="object"}function r(i){if(!n(i))return i;if(i.constructor==Array){for(var s=i.length,c=new Array(s),u=0;u<s;u++)c[u]=r(i[u]);return c}if(i.constructor==Date){var f=new Date(+i);return f}var h={};for(var m in i)e.hasOwnProperty.call(i,m)&&(h[m]=r(i[m]));return h}e.clone=r}(Kv)),Kv}var fr={},WE;function I_(){if(WE)return fr;WE=1,Object.defineProperty(fr,"__esModule",{value:!0}),fr.diffAny=fr.diffObjects=fr.diffArrays=fr.intersection=fr.subtract=fr.isDestructive=void 0;var e=M_();function t(m){var g=m.op;return g==="remove"||g==="replace"||g==="copy"||g==="move"}fr.isDestructive=t;function n(m,g){var y={};for(var b in m)e.hasOwnProperty.call(m,b)&&m[b]!==void 0&&(y[b]=1);for(var S in g)e.hasOwnProperty.call(g,S)&&g[S]!==void 0&&delete y[S];return Object.keys(y)}fr.subtract=n;function r(m){for(var g=m.length,y={},b=0;b<g;b++){var S=m[b];for(var j in S)e.hasOwnProperty.call(S,j)&&S[j]!==void 0&&(y[j]=(y[j]||0)+1)}for(var j in y)y[j]<g&&delete y[j];return Object.keys(y)}fr.intersection=r;function i(m){return m.op==="add"}function s(m){return m.op==="remove"}function c(m,g){return{operations:m.operations.concat(g),cost:m.cost+1}}function u(m,g,y,b){b===void 0&&(b=h);var S={"0,0":{operations:[],cost:0}};function j(R,A){var k="".concat(R,",").concat(A),M=S[k];if(M===void 0){if(R>0&&A>0&&!b(m[R-1],g[A-1],y.add(String(R-1))).length)M=j(R-1,A-1);else{var I=[];if(R>0){var $=j(R-1,A),V={op:"remove",index:R-1};I.push(c($,V))}if(A>0){var Y=j(R,A-1),Q={op:"add",index:R-1,value:g[A-1]};I.push(c(Y,Q))}if(R>0&&A>0){var J=j(R-1,A-1),G={op:"replace",index:R-1,original:m[R-1],value:g[A-1]};I.push(c(J,G))}var Z=I.sort(function(P,L){return P.cost-L.cost})[0];M=Z}S[k]=M}return M}var C=isNaN(m.length)||m.length<=0?0:m.length,T=isNaN(g.length)||g.length<=0?0:g.length,D=j(C,T).operations,E=D.reduce(function(R,A){var k=R[0],M=R[1];if(i(A)){var I=A.index+1+M,$=I<C+M?String(I):"-",V={op:A.op,path:y.add($).toString(),value:A.value};return[k.concat(V),M+1]}else if(s(A)){var V={op:A.op,path:y.add(String(A.index+M)).toString()};return[k.concat(V),M-1]}else{var Y=y.add(String(A.index+M)),Q=b(A.original,A.value,Y);return[k.concat.apply(k,Q),M]}},[[],0])[0];return E}fr.diffArrays=u;function f(m,g,y,b){b===void 0&&(b=h);var S=[];return n(m,g).forEach(function(j){S.push({op:"remove",path:y.add(j).toString()})}),n(g,m).forEach(function(j){S.push({op:"add",path:y.add(j).toString(),value:g[j]})}),r([m,g]).forEach(function(j){S.push.apply(S,b(m[j],g[j],y.add(j)))}),S}fr.diffObjects=f;function h(m,g,y,b){if(b===void 0&&(b=h),m===g)return[];var S=(0,e.objectType)(m),j=(0,e.objectType)(g);return S=="array"&&j=="array"?u(m,g,y,b):S=="object"&&j=="object"?f(m,g,y,b):[{op:"replace",path:y.toString(),value:g}]}return fr.diffAny=h,fr}var YE;function sG(){if(YE)return gn;YE=1;var e=gn&&gn.__extends||function(){var C=function(T,D){return C=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(E,R){E.__proto__=R}||function(E,R){for(var A in R)Object.prototype.hasOwnProperty.call(R,A)&&(E[A]=R[A])},C(T,D)};return function(T,D){if(typeof D!="function"&&D!==null)throw new TypeError("Class extends value "+String(D)+" is not a constructor or null");C(T,D);function E(){this.constructor=T}T.prototype=D===null?Object.create(D):(E.prototype=D.prototype,new E)}}();Object.defineProperty(gn,"__esModule",{value:!0}),gn.apply=gn.InvalidOperationError=gn.test=gn.copy=gn.move=gn.replace=gn.remove=gn.add=gn.TestError=gn.MissingError=void 0;var t=O_(),n=M_(),r=I_(),i=function(C){e(T,C);function T(D){var E=C.call(this,"Value required at path: ".concat(D))||this;return E.path=D,E.name="MissingError",E}return T}(Error);gn.MissingError=i;var s=function(C){e(T,C);function T(D,E){var R=C.call(this,"Test failed: ".concat(D," != ").concat(E))||this;return R.actual=D,R.expected=E,R.name="TestError",R}return T}(Error);gn.TestError=s;function c(C,T,D){if(Array.isArray(C))if(T=="-")C.push(D);else{var E=parseInt(T,10);C.splice(E,0,D)}else C[T]=D}function u(C,T){if(Array.isArray(C)){var D=parseInt(T,10);C.splice(D,1)}else delete C[T]}function f(C,T){var D=t.Pointer.fromJSON(T.path).evaluate(C);return D.parent===void 0?new i(T.path):(c(D.parent,D.key,(0,n.clone)(T.value)),null)}gn.add=f;function h(C,T){var D=t.Pointer.fromJSON(T.path).evaluate(C);return D.value===void 0?new i(T.path):(u(D.parent,D.key),null)}gn.remove=h;function m(C,T){var D=t.Pointer.fromJSON(T.path).evaluate(C);if(D.parent===null)return new i(T.path);if(Array.isArray(D.parent)){if(parseInt(D.key,10)>=D.parent.length)return new i(T.path)}else if(D.value===void 0)return new i(T.path);return D.parent[D.key]=(0,n.clone)(T.value),null}gn.replace=m;function g(C,T){var D=t.Pointer.fromJSON(T.from).evaluate(C);if(D.value===void 0)return new i(T.from);var E=t.Pointer.fromJSON(T.path).evaluate(C);return E.parent===void 0?new i(T.path):(u(D.parent,D.key),c(E.parent,E.key,D.value),null)}gn.move=g;function y(C,T){var D=t.Pointer.fromJSON(T.from).evaluate(C);if(D.value===void 0)return new i(T.from);var E=t.Pointer.fromJSON(T.path).evaluate(C);return E.parent===void 0?new i(T.path):(c(E.parent,E.key,(0,n.clone)(D.value)),null)}gn.copy=y;function b(C,T){var D=t.Pointer.fromJSON(T.path).evaluate(C);return(0,r.diffAny)(D.value,T.value,new t.Pointer).length?new s(D.value,T.value):null}gn.test=b;var S=function(C){e(T,C);function T(D){var E=C.call(this,"Invalid operation: ".concat(D.op))||this;return E.operation=D,E.name="InvalidOperationError",E}return T}(Error);gn.InvalidOperationError=S;function j(C,T){switch(T.op){case"add":return f(C,T);case"remove":return h(C,T);case"replace":return m(C,T);case"move":return g(C,T);case"copy":return y(C,T);case"test":return b(C,T)}return new S(T)}return gn.apply=j,gn}var KE;function lG(){return KE||(KE=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createTests=e.createPatch=e.applyPatch=e.Pointer=void 0;var t=O_();Object.defineProperty(e,"Pointer",{enumerable:!0,get:function(){return t.Pointer}});var n=sG(),r=I_();function i(h,m){return m.map(function(g){return(0,n.apply)(h,g)})}e.applyPatch=i;function s(h){function m(g,y,b){var S=h(g,y,b);return Array.isArray(S)?S:(0,r.diffAny)(g,y,b,m)}return m}function c(h,m,g){var y=new t.Pointer;return(g?s(g):r.diffAny)(h,m,y)}e.createPatch=c;function u(h,m){var g=t.Pointer.fromJSON(m).evaluate(h);if(g!==void 0)return{op:"test",path:m,value:g.value}}function f(h,m){var g=new Array;return m.filter(r.isDestructive).forEach(function(y){var b=u(h,y.path);if(b&&g.push(b),"from"in y){var S=u(h,y.from);S&&g.push(S)}}),g}e.createTests=f}(Yv)),Yv}var L_=lG();const cG="_removed_el5zk_1",uG="_added_el5zk_6",XE={removed:cG,added:uG};function dG(e){var m;const{name:t,path:n,property:r,originalValue:i,revisedValue:s}=e,c=!!((m=r==null?void 0:r.type)!=null&&m.find(g=>g.code==="Attachment")),[u,f]=v.useState(c),h=()=>f(g=>!g);return o.jsx(o.Fragment,{children:c&&!u||!c?o.jsx(o.Fragment,{children:o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:t}),o.jsx(ye.Td,{className:XE.removed,children:i&&o.jsx(Li,{path:n,property:r,propertyType:i.type,value:i.value,ignoreMissingValues:!0})}),o.jsx(ye.Td,{className:XE.added,children:s&&o.jsx(Li,{path:n,property:r,propertyType:s.type,value:s.value,ignoreMissingValues:!0})})]})}):o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:t}),o.jsx(ye.Td,{colSpan:2,style:{textAlign:"right"},children:o.jsx(Ne,{onClick:h,variant:"light",children:"Expand"})})]})})}const fG="_root_15xvr_1",hG={root:fG};function pG(e){const t=_e(),{original:n,revised:r}=e,[i,s]=v.useState(!1);v.useEffect(()=>{t.requestSchema(e.original.resourceType).then(()=>s(!0)).catch(console.log)},[t,e.original.resourceType]);const c=v.useMemo(()=>{if(!i)return null;const u=[mi(n)],f=[mi(r)],h=[],m=mG(L_.createPatch(n,r));for(const g of m){const y=g.path,b=gG(y),S=vG(n.resourceType,b),j=g.op==="add"?void 0:Fs(b,u),C=g.op==="remove"?void 0:Fs(b,f);h.push({key:`op-${g.op}-${g.path}`,name:`${Hn(g.op)} ${b}`,path:(S==null?void 0:S.path)??n.resourceType+"."+b,property:S,originalValue:ZE(S,j),revisedValue:ZE(S,C)})}return h},[i,n,r]);return c?o.jsxs(ye,{className:hG.root,children:[o.jsx(ye.Thead,{children:o.jsxs(ye.Tr,{children:[o.jsx(ye.Th,{}),o.jsx(ye.Th,{children:"Before"}),o.jsx(ye.Th,{children:"After"})]})}),o.jsx(ye.Tbody,{children:c.map(u=>{const{key:f,...h}=u;return o.jsx(dG,{...h},f)})})]}):null}function mG(e){const t=[];for(const n of e){const{op:r,path:i}=n;if(i.startsWith("/meta/author")||i.startsWith("/meta/compartment")||i.startsWith("/meta/lastUpdated")||i.startsWith("/meta/versionId"))continue;const s=e.filter(u=>u.op===r&&u.path===i).length,c={op:r,path:i};s>1&&(r==="add"||r==="remove")&&/\/[0-9-]+$/.test(i)&&(c.op="replace",c.path=i.replace(/\/[^/]+$/,"")),t.some(u=>u.op===c.op&&u.path===c.path)||t.push(c)}return t}function gG(e){const t=e.split("/").filter(Boolean);let n="";for(let r=0;r<t.length;r++){const i=t[r];i==="-"?n+=".last()":/^\d+$/.test(i)?n+=`[${i}]`:(r>0&&(n+="."),n+=i)}return n.endsWith(".url")&&(n=n.replace(/\.url$/,"")),n}function vG(e,t){var r;const n=Mc(e,{code:e+"."+t,expression:e+"."+t});return(r=n==null?void 0:n.elementDefinitions)==null?void 0:r[0]}function ZE(e,t){return t&&{type:Array.isArray(t)?t[0].type:t.type,value:yG(t,!!(e!=null&&e.isArray))}}function yG(e,t){const n=X8(e).flatMap(r=>r.value);return t?n:n[0]}function Nb(e){const{profileUrl:t}=e,n=_e(),r=n.getAccessPolicy(),i=Qt(e.value),[s,c]=v.useState(!1);v.useEffect(()=>{if(i)if(t)n.requestProfileSchema(t,{expandProfile:!0}).then(()=>{Pc(t)?c(!0):console.error(`Schema not found for ${t}`)}).catch(f=>{console.error("Error in requestProfileSchema",f)});else{const f=i.resourceType;n.requestSchema(f).then(()=>{c(!0)}).catch(console.error)}},[n,t,i]);const u=v.useMemo(()=>i&&IA(i,Ns.READ,r),[r,i]);return!s||!i?null:o.jsx(Gh,{path:i.resourceType,value:{type:i.resourceType,value:e.forceUseInput?e.value:i},profileUrl:t,ignoreMissingValues:e.ignoreMissingValues,accessPolicyResource:u})}const xG="_item_5q6yx_1",bG="_itemPadding_5q6yx_5",JE={item:xG,itemPadding:bG};function SG(e){return o.jsx(Ic,{children:e.children})}function Gs(e){var f,h;const{resource:t,profile:n,padding:r,popupMenuItems:i,...s}=e,c=n??((f=t.meta)==null?void 0:f.author),u=e.dateTime??((h=t.meta)==null?void 0:h.lastUpdated);return o.jsxs(rm,{"data-testid":"timeline-item",fill:!0,...s,children:[o.jsxs(Ce,{justify:"space-between",gap:8,mx:"xs",my:"sm",children:[o.jsx(Xo,{value:c,link:!0,size:"md"}),o.jsxs("div",{style:{flex:1},children:[o.jsx(Ae,{size:"sm",children:o.jsx(Lc,{c:"dark",fw:500,value:c,link:!0})}),o.jsxs(Ae,{size:"xs",children:[o.jsx(mt,{c:"dimmed",to:e.resource,children:gr(u)}),o.jsx(Ae,{component:"span",c:"dimmed",mx:8,children:"·"}),o.jsx(mt,{c:"dimmed",to:e.resource,children:e.resource.resourceType})]})]}),i&&o.jsxs(je,{position:"bottom-end",shadow:"md",width:200,children:[o.jsx(je.Target,{children:o.jsx(_n,{color:"gray",variant:"subtle",radius:"xl","aria-label":`Actions for ${zt(e.resource)}`,children:o.jsx(eF,{})})}),i]})]}),o.jsx(a_,{children:o.jsx("div",{className:Ut(JE.item,{[JE.itemPadding]:r}),children:e.children})})]})}function z_(e,t){e.sort((n,r)=>{const i=eT(n,t),s=eT(r,t);return i>s?1:i<s?-1:tT(n,t)-tT(r,t)})}function eT(e,t){if(!$_(e,t)){const n=e.priority;if(typeof n=="string")return{stat:4,asap:3,urgent:2}[n]??0}return 0}function tT(e,t){var r;if(!$_(e,t)){if(e.resourceType==="Communication"&&e.sent)return new Date(e.sent).getTime();if((e.resourceType==="DiagnosticReport"||e.resourceType==="Media"||e.resourceType==="Observation")&&e.issued)return new Date(e.issued).getTime();if(e.resourceType==="DocumentReference"&&e.date)return new Date(e.date).getTime()}const n=(r=e.meta)==null?void 0:r.lastUpdated;return n?new Date(n).getTime():0}function $_(e,t){return!!t&&e.resourceType===t.resourceType&&e.id===t.id}const wG="_pinnedComment_u08s5_1",jG={pinnedComment:wG};function sm(e){const t=_e(),n=t.getProfile(),r=v.useRef(null),i=Qt(e.value),[s,c]=v.useState(),[u,f]=v.useState([]),h=e.loadTimelineResources,m=v.useRef(u);m.current=u;const g=v.useCallback(R=>{z_(R,i),R.reverse(),f(R)},[i]),y=v.useCallback(R=>{const A=[];for(const k of R){if(k.status!=="fulfilled")continue;const M=k.value;if(M.type==="history"&&c(M),M.entry)for(const I of M.entry)A.push(I.resource)}g(A)},[g]),b=v.useCallback(R=>g([...m.current,R]),[g]),S=v.useCallback(()=>{var k;let R,A;"resourceType"in e.value?(R=e.value.resourceType,A=e.value.id):[R,A]=(k=e.value.reference)==null?void 0:k.split("/"),h(t,R,A).then(y).catch(console.error)},[t,e.value,h,y]);v.useEffect(()=>S(),[S]);function j(R){!i||!e.createCommunication||t.createResource(e.createCommunication(i,n,R)).then(A=>b(A)).catch(console.error)}function C(R){!i||!e.createMedia||t.createResource(e.createMedia(i,n,R)).then(A=>b(A)).then(()=>As({id:"upload-notification",color:"teal",title:"Upload complete",message:"",icon:o.jsx(eo,{size:16}),autoClose:2e3})).catch(A=>As({id:"upload-notification",color:"red",title:"Upload error",message:Ye(A),icon:o.jsx(OE,{size:16}),autoClose:2e3}))}function T(){Oe({id:"upload-notification",loading:!0,title:"Initializing upload...",message:"Please wait...",autoClose:!1,withCloseButton:!1})}function D(R){As({id:"upload-notification",loading:!0,title:"Uploading...",message:_G(R),autoClose:!1,withCloseButton:!1})}function E(R){As({id:"upload-notification",color:"red",title:"Upload error",message:Ye(R),icon:o.jsx(OE,{size:16}),autoClose:2e3})}return i?o.jsxs(SG,{children:[e.createCommunication&&o.jsx(rm,{children:o.jsx(pt,{testid:"timeline-form",onSubmit:R=>{j(R.text);const A=r.current;A&&(A.value="",A.focus())},children:o.jsxs(Ce,{gap:"xs",wrap:"nowrap",style:{width:"100%"},children:[o.jsx(Xo,{value:n}),o.jsx(ze,{name:"text",ref:r,placeholder:"Add comment",style:{width:"100%",maxWidth:300}}),o.jsx(_n,{type:"submit",radius:"xl",color:"blue",variant:"filled",children:o.jsx(lF,{size:16})}),o.jsx(Eb,{securityContext:on(i),onUpload:C,onUploadStart:T,onUploadProgress:D,onUploadError:E,children:R=>o.jsx(_n,{...R,radius:"xl",color:"blue",variant:"filled",children:o.jsx(gb,{size:16})})})]})})}),u.map(R=>{var M;if(!R)return null;const A=`${R.resourceType}/${R.id}/${(M=R.meta)==null?void 0:M.versionId}`,k=e.getMenu?e.getMenu({primaryResource:i,currentResource:R,reloadTimeline:S}):void 0;if(R.resourceType===i.resourceType&&R.id===i.id)return o.jsx(CG,{history:s,resource:R,popupMenuItems:k},A);switch(R.resourceType){case"AuditEvent":return o.jsx(DG,{resource:R,popupMenuItems:k},A);case"Communication":return o.jsx(TG,{resource:R,popupMenuItems:k},A);case"DiagnosticReport":return o.jsx(AG,{resource:R,popupMenuItems:k},A);case"Media":return o.jsx(RG,{resource:R,popupMenuItems:k},A);default:return o.jsx(Gs,{resource:R,padding:!0,children:o.jsx(Nb,{value:R,ignoreMissingValues:!0})},A)}})]}):o.jsx(er,{style:{width:"100%",height:"100%"},children:o.jsx(_r,{})})}function CG(e){const{history:t,resource:n,...r}=e,i=EG(t,n);return i?o.jsx(Gs,{resource:n,padding:!0,...r,children:o.jsx(pG,{original:i,revised:e.resource})}):o.jsxs(Gs,{resource:n,padding:!0,...r,children:[o.jsx("h3",{children:"Created"}),o.jsx(Nb,{value:n,ignoreMissingValues:!0,forceUseInput:!0})]})}function EG(e,t){const n=e.entry??[],r=n.findIndex(i=>{var s,c,u;return((c=(s=i.resource)==null?void 0:s.meta)==null?void 0:c.versionId)===((u=t.meta)==null?void 0:u.versionId)});if(!(r>=n.length-1))return n[r+1].resource}function TG(e){var r,i;const n=!e.resource.priority||e.resource.priority==="routine"?void 0:jG.pinnedComment;return o.jsx(Gs,{resource:e.resource,profile:e.resource.sender,dateTime:e.resource.sent,padding:!0,className:n,popupMenuItems:e.popupMenuItems,children:o.jsx("p",{children:(i=(r=e.resource.payload)==null?void 0:r[0])==null?void 0:i.contentString})})}function RG(e){var r;const t=(r=e.resource.content)==null?void 0:r.contentType,n=t&&!t.startsWith("image/")&&!t.startsWith("video/")&&t!=="application/pdf";return o.jsx(Gs,{resource:e.resource,padding:!!n,popupMenuItems:e.popupMenuItems,children:o.jsx(Nd,{value:e.resource.content})})}function DG(e){return o.jsx(Gs,{resource:e.resource,padding:!0,popupMenuItems:e.popupMenuItems,children:o.jsx(Yr,{children:o.jsx("pre",{children:e.resource.outcomeDesc})})})}function AG(e){return o.jsx(Gs,{resource:e.resource,padding:!0,popupMenuItems:e.popupMenuItems,children:o.jsx(Pb,{value:e.resource})})}function _G(e){if(e.lengthComputable){const t=100*e.loaded/e.total;return`Uploaded: ${Xv(e.loaded)} / ${Xv(e.total)} ${t.toFixed(2)}%`}return`Uploaded: ${Xv(e.loaded)}`}function Xv(e){if(e===0)return"0.00 B";const t=Math.floor(Math.log(e)/Math.log(1024));return(e/Math.pow(1024,t)).toFixed(2)+" "+" KMGTP".charAt(t)+"B"}function kG(e){const{resource:t,...n}=e;return o.jsx(sm,{value:t,loadTimelineResources:async(r,i,s)=>{const c=`${i}/${s}`;return Promise.allSettled([r.readHistory(i,s),r.search("Task",{_filter:`based-on eq ${c} or focus eq ${c} or subject eq ${c}`,_count:100})])},...n})}function PG(e){const{encounter:t,...n}=e;return o.jsx(sm,{value:t,loadTimelineResources:async(r,i,s)=>Promise.allSettled([r.readHistory("Encounter",s),r.search("Communication","encounter=Encounter/"+s),r.search("Media","encounter=Encounter/"+s)]),createCommunication:(r,i,s)=>({resourceType:"Communication",status:"completed",encounter:on(r),subject:r.subject,sender:on(i),sent:new Date().toISOString(),payload:[{contentString:s}]}),createMedia:(r,i,s)=>({resourceType:"Media",status:"completed",encounter:on(r),subject:r.subject,operator:on(i),issued:new Date().toISOString(),content:s}),...n})}function NG(e){let t;try{t=Oc(e.path,e.resource)}catch(n){return console.warn("FhirPathDisplay:",n),null}if(t.length>1)throw new Error(`Component "path" for "FhirPathDisplay" must resolve to a single element. Received ${t.length} elements [${JSON.stringify(t,null,2)}]`);return o.jsx(Li,{value:t[0]||"",propertyType:e.propertyType})}function OG(e){return o.jsxs($n,{title:"Export",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:e.onCancel,children:[o.jsxs(ce,{display:"flex",style:{justifyContent:"space-between"},children:[e.exportCsv&&o.jsx(nT,{text:"CSV",exportLogic:e.exportCsv,onCancel:e.onCancel}),e.exportTransactionBundle&&o.jsx(nT,{text:"Transaction Bundle",exportLogic:e.exportTransactionBundle,onCancel:e.onCancel})]}),o.jsx(Ae,{style:{marginTop:"10px",marginLeft:"2px"},children:"Limited to 1000 records"})]})}function nT(e){return o.jsx(Ne,{onClick:()=>{e.exportLogic(),e.onCancel()},children:`Export as ${e.text}`})}const MG={string:[ue.EQUALS,ue.NOT,ue.CONTAINS,ue.EXACT],fulltext:[ue.EQUALS,ue.NOT,ue.CONTAINS,ue.EXACT],token:[ue.EQUALS,ue.NOT],reference:[ue.EQUALS,ue.NOT],numeric:[ue.EQUALS,ue.NOT_EQUALS,ue.GREATER_THAN,ue.LESS_THAN,ue.GREATER_THAN_OR_EQUALS,ue.LESS_THAN_OR_EQUALS],quantity:[ue.EQUALS,ue.NOT_EQUALS,ue.GREATER_THAN,ue.LESS_THAN,ue.GREATER_THAN_OR_EQUALS,ue.LESS_THAN_OR_EQUALS],date:[ue.EQUALS,ue.NOT_EQUALS,ue.GREATER_THAN,ue.LESS_THAN,ue.GREATER_THAN_OR_EQUALS,ue.LESS_THAN_OR_EQUALS,ue.STARTS_AFTER,ue.ENDS_BEFORE,ue.APPROXIMATELY],datetime:[ue.EQUALS,ue.NOT_EQUALS,ue.GREATER_THAN,ue.LESS_THAN,ue.GREATER_THAN_OR_EQUALS,ue.LESS_THAN_OR_EQUALS,ue.STARTS_AFTER,ue.ENDS_BEFORE,ue.APPROXIMATELY],uri:[ue.EQUALS,ue.NOT,ue.ABOVE,ue.BELOW]},IG={eq:"equals",ne:"not equals",gt:"greater than",lt:"less than",ge:"greater than or equals",le:"less than or equals",sa:"starts after",eb:"ends before",ap:"approximately",sw:"starts with",contains:"contains",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"};function Ob(e,t){return{...e,filters:t,offset:0,name:void 0}}function U_(e,t){return Ob(e,(e.filters??[]).filter(n=>n.code!==t))}function lm(e,t,n,r,i){const s=[];return e.filters&&s.push(...e.filters),s.push({code:t,operator:n,value:r??""}),Ob(e,s)}function LG(e,t){if(!e.filters)return e;const n=[...e.filters];return n.splice(t,1),{...e,filters:n,name:void 0}}function zG(e,t){return Mb(e,t,-1)}function $G(e,t){return Mb(e,t,0)}function UG(e,t){return Mb(e,t,1)}function Mb(e,t,n){const r=new Date;r.setDate(r.getDate()+n),r.setHours(0,0,0,0);const i=new Date(r.getTime());return i.setDate(i.getDate()+1),i.setTime(i.getTime()-1),cm(e,t,r,i)}function BG(e,t){const n=new Date,r=new Date(n.getTime()+24*60*60*1e3);return cm(e,t,n,r)}function VG(e,t){return Ib(e,t,-1)}function FG(e,t){return Ib(e,t,0)}function HG(e,t){return Ib(e,t,1)}function Ib(e,t,n){const r=new Date;r.setMonth(r.getMonth()+n),r.setDate(1),r.setHours(0,0,0,0);const i=new Date(r.getTime());return i.setMonth(i.getMonth()+1),i.setDate(1),i.setHours(0,0,0,0),i.setTime(i.getTime()-1),cm(e,t,r,i)}function qG(e,t){const n=new Date;return n.setMonth(0),n.setDate(1),n.setHours(0,0,0,0),cm(e,t,n,new Date)}function cm(e,t,n,r){return e=U_(e,t),e=rT(e,t,ue.GREATER_THAN_OR_EQUALS,n),e=rT(e,t,ue.LESS_THAN_OR_EQUALS,r),e}function rT(e,t,n,r){return lm(e,t,n,r.toISOString())}function iT(e,t,n=!0){return lm(e,t,ue.MISSING,n.toString())}function GG(e,t){return e.offset===t?e:{...e,offset:t,name:void 0}}function QG(e,t){const n=e.count??Kp,r=(t-1)*n;return GG(e,r)}function WG(e,t,n){return t===YG(e)&&n!==void 0&&n===KG(e)?e:{...e,sortRules:[{code:t,descending:!!n}],name:void 0}}function YG(e){const t=e.sortRules;if(!t||t.length===0)return;const n=t[0].code;return n.startsWith("-")?n.substr(1):n}function KG(e){const t=e.sortRules;return!t||t.length===0?!1:!!t[0].descending}function XG(e){return MG[e.type]}function B_(e){return IG[e]??""}function Qs(e){let t=e;return t.includes(".")&&(t=t.split(".").pop()),t==="versionId"?"Version ID":(t=t.replace("[x]",""),t=t.replace(/([A-Z])/g," $1"),t=t.replace(/[-_]/g," "),t=t.replace(/\s+/g," "),t=t.trim(),t.toLowerCase()==="id"?"ID":t.split(/\s/).map(Hn).join(" "))}function ZG(e,t){var r,i;const n=t.name;return n==="id"?o.jsx(mt,{to:`/${e.resourceType}/${e.id}`,children:e.id}):n==="meta.versionId"?(r=e.meta)==null?void 0:r.versionId:n==="_lastUpdated"?gr((i=e.meta)==null?void 0:i.lastUpdated):t.elementDefinition&&`${e.resourceType}.${t.name}`===t.elementDefinition.path?JG(e,t.elementDefinition):t.searchParams&&t.searchParams.length===1&&t.name===t.searchParams[0].code?eQ(e,t.searchParams[0]):null}function JG(e,t){var s,c,u;const n=((u=(c=(s=t.path)==null?void 0:s.split("."))==null?void 0:c.pop())==null?void 0:u.replaceAll("[x]",""))??"",[r,i]=im({type:e.resourceType,value:e},n);return r?o.jsx(Li,{path:t.path,property:t,propertyType:i,value:r,maxWidth:200,ignoreMissingValues:!0,link:!1}):null}function eQ(e,t){const n=Fs(t.expression,[{type:e.resourceType,value:e}]);return!n||n.length===0?null:o.jsx(o.Fragment,{children:n.map((r,i)=>o.jsx(Li,{propertyType:r.type,value:r.value,maxWidth:200,ignoreMissingValues:!0,link:!1},`${i}-${n.length}`))})}function tQ(e){const t=v.useRef(!1),[n,r]=v.useState({search:JSON.parse(Ii(e.search))}),[i,s]=v.useState(!1);v.useEffect(()=>{r({search:e.search})},[e.search]);const c=v.useMemo(()=>{if(!e.visible)return[];const f=e.search.resourceType,h=fA(f),m=nb(f);return ad(nQ(h,m)).map(g=>({value:g,label:Qs(g)}))},[e.visible,e.search.resourceType]);function u(f){r({search:{...n.search,fields:f}})}return o.jsx($n,{title:"Fields",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:()=>{e.onCancel()},size:"auto",withOverlay:!0,closeOnClickOutside:!1,overlayProps:{onMouseDownCapture:()=>{t.current=i},onClick:()=>{t.current||e.onCancel(),t.current=!1},children:o.jsx("div",{"data-testid":"overlay-child"})},children:o.jsxs(Ge,{children:[o.jsx(Op,{style:{width:550},placeholder:"Select fields to display",data:c,value:n.search.fields??[],onChange:u,onDropdownOpen:()=>s(!0),onDropdownClose:()=>s(!1),maxDropdownHeight:"250px",clearButtonProps:{"aria-label":"Clear selection"},clearable:!0,searchable:!0}),o.jsx(Ce,{justify:"flex-end",children:o.jsx(Ne,{onClick:()=>e.onOk(n.search),children:"OK"})})]})})}function nQ(e,t){const n=[],r=new Set,i=new Set;for(const s of Object.keys(e.elements))n.push(s),r.add(s.toLowerCase()),i.add(Qs(s));if(t)for(const s of Object.keys(t)){const c=Qs(s);!r.has(s)&&!i.has(c)&&(n.push(s),r.add(s),i.add(c))}return n}function V_(e){const t=Mc(e.resourceType,e.searchParam),n=e.name??"filter-value";switch(t.type){case Jn.REFERENCE:return o.jsx(Md,{name:n,defaultValue:e.defaultValue?{reference:e.defaultValue}:void 0,targetTypes:e.searchParam.target,autoFocus:e.autoFocus,onChange:r=>{r?e.onChange(r.reference):e.onChange("")}});case Jn.BOOLEAN:return o.jsx(Fn,{name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultChecked:e.defaultValue==="true",autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.checked.toString())});case Jn.DATE:return o.jsx(ze,{type:"date",name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value)});case Jn.DATETIME:return o.jsx(aa,{name:n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:e.onChange});case Jn.NUMBER:return o.jsx(ze,{type:"number",name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value)});case Jn.QUANTITY:return o.jsx(qs,{name:n,path:"",defaultValue:rQ(e.defaultValue),autoFocus:e.autoFocus,onChange:r=>{r?e.onChange(`${r.value}`):e.onChange("")}});default:return o.jsx(ze,{name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value),placeholder:"Search value"})}}function rQ(e){if(e){const[t,n,r]=e.split("|");if(t)return{value:parseFloat(t),system:n,unit:r}}}function iQ(e){const[t,n]=v.useState(Qr(e.search)),r=v.useRef(t);r.current=t,v.useEffect(()=>{n(Qr(e.search))},[e.search]);function i(f){n(lm(r.current,f.code,f.operator,f.value))}const s=e.search.resourceType,c=nb(s)??{},u=t.filters||[];return o.jsx($n,{title:"Filters",closeButtonProps:{"aria-label":"Close"},size:900,opened:e.visible,onClose:e.onCancel,children:o.jsxs(pt,{onSubmit:()=>e.onOk(r.current),children:[o.jsxs("div",{children:[o.jsxs("table",{children:[o.jsxs("colgroup",{children:[o.jsx("col",{style:{width:200}}),o.jsx("col",{style:{width:200}}),o.jsx("col",{style:{width:380}}),o.jsx("col",{style:{width:40}})]}),o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Field"}),o.jsx("th",{children:"Operation"}),o.jsx("th",{children:"Value"}),o.jsx("th",{})]})}),o.jsx("tbody",{children:u.map((f,h)=>o.jsx(aQ,{id:`filter-${h}-row`,resourceType:s,searchParams:c,value:f,onChange:m=>{const g=[...u];g[h]=m,n(Ob(r.current,g))},onDelete:()=>n(LG(r.current,h))},`filter-${h}-row`))})]}),o.jsx(Ab,{propertyDisplayName:"Filter",onClick:()=>i({})})]}),o.jsx(Ce,{justify:"flex-end",mt:"xl",children:o.jsx(Or,{children:"OK"})})]})})}function aQ(e){const t=e.value,n=v.useRef(t);n.current=t;function r(f){n.current.code=f,n.current.operator=ue.EQUALS,n.current.value="",e.onChange(n.current)}function i(f){n.current.operator=f,n.current.value="",e.onChange(n.current)}function s(f){n.current.value=f,e.onChange(n.current)}const c=e.searchParams[t.code],u=c&&XG(c);return o.jsxs("tr",{children:[o.jsx("td",{children:o.jsx(ln,{"data-testid":`${e.id}-filter-field`,defaultValue:e.value.code,onChange:f=>r(f.currentTarget.value),data:["",...Object.keys(e.searchParams).map(f=>({value:f,label:Qs(f)}))]})}),o.jsx("td",{children:u&&o.jsx(ln,{"data-testid":`${e.id}-filter-operation`,defaultValue:t.operator,onChange:f=>i(f.currentTarget.value),data:["",...u.map(f=>({value:f,label:B_(f)}))]},`${e.id}-filter-value-${e.value.code}`)}),o.jsx("td",{children:c&&t.operator&&o.jsx(V_,{name:`${e.id}-filter-value`,resourceType:e.resourceType,searchParam:c,defaultValue:t.value,onChange:s},`${e.id}-filter-value-${e.value.code}-${e.value.operator}`)}),o.jsx("td",{children:e.onDelete&&o.jsx(_n,{variant:"outline",color:"red",radius:"xl","aria-label":"Delete filter",onClick:e.onDelete,children:o.jsx(Hs,{style:{width:"70%",height:"70%"},stroke:1.5})})})]})}function oQ(e){const[t,n]=v.useState(e.defaultValue??"");if(!e.searchParam||!e.filter)return null;function r(){e.onOk({...e.filter,value:t})}return o.jsx($n,{title:e.title,size:"xl",opened:e.visible,onClose:e.onCancel,children:o.jsx(pt,{onSubmit:r,children:o.jsxs(or,{children:[o.jsx(or.Col,{span:10,children:o.jsx(V_,{resourceType:e.resourceType,searchParam:e.searchParam,defaultValue:t,autoFocus:!0,onChange:n})}),o.jsx(or.Col,{span:2,children:o.jsx(Ne,{onClick:r,fullWidth:!0,children:"OK"})})]})})})}function sQ(e){var i;const{resourceType:t,filter:n}=e,r=(i=la.types[t].searchParams)==null?void 0:i[n.code];if(r){if(r.type==="reference"&&(n.operator===ue.EQUALS||n.operator===ue.NOT_EQUALS))return o.jsx(Lc,{value:{reference:n.value}});const s=Mc(t,r);if(n.code==="_lastUpdated"||s.type===Jn.DATETIME)return o.jsx(o.Fragment,{children:gr(n.value)})}return o.jsx(o.Fragment,{children:n.value})}function lQ(e){if(!e.searchParams)return null;function t(s,c){i(WG(e.search,s.code,c))}function n(s){i(U_(e.search,s.code))}function r(s,c){e.onPrompt(s,{code:s.code,operator:c,value:""})}function i(s){e.onChange(s)}return e.searchParams.length===1?o.jsx(cQ,{search:e.search,searchParam:e.searchParams[0],onSort:t,onPrompt:r,onChange:i,onClear:n}):o.jsx(je.Dropdown,{children:e.searchParams.map(s=>o.jsx(je.Item,{children:Qs(s.code)},s.code))})}function cQ(e){switch(e.searchParam.type){case"date":return o.jsx(uQ,{...e});case"number":case"quantity":return o.jsx(dQ,{...e});case"reference":return o.jsx(fQ,{...e});case"string":return o.jsx(hQ,{...e});case"token":case"uri":return o.jsx(pQ,{...e});default:return o.jsxs(o.Fragment,{children:["Unknown search param type: ",e.searchParam.type]})}}function uQ(e){const{searchParam:t}=e,n=t.code;return o.jsxs(je.Dropdown,{children:[o.jsx(je.Item,{leftSection:o.jsx(vb,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort Oldest to Newest"}),o.jsx(je.Item,{leftSection:o.jsx(yb,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Newest to Oldest"}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Pd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),o.jsx(je.Item,{leftSection:o.jsx(kd,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT_EQUALS),children:"Does not equal..."}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(n_,{size:14}),onClick:()=>e.onPrompt(t,ue.ENDS_BEFORE),children:"Before..."}),o.jsx(je.Item,{leftSection:o.jsx(t_,{size:14}),onClick:()=>e.onPrompt(t,ue.STARTS_AFTER),children:"After..."}),o.jsx(je.Item,{leftSection:o.jsx(HV,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Between..."}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(UG(e.search,n)),children:"Tomorrow"}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange($G(e.search,n)),children:"Today"}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(zG(e.search,n)),children:"Yesterday"}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(BG(e.search,n)),children:"Next 24 Hours"}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(HG(e.search,n)),children:"Next Month"}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(FG(e.search,n)),children:"This Month"}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(VG(e.search,n)),children:"Last Month"}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(qG(e.search,n)),children:"Year to date"}),o.jsx(Ld,{...e})]})}function dQ(e){const{searchParam:t}=e;return o.jsxs(je.Dropdown,{children:[o.jsx(je.Item,{leftSection:o.jsx(vb,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort Smallest to Largest"}),o.jsx(je.Item,{leftSection:o.jsx(yb,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Largest to Smallest"}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Pd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),o.jsx(je.Item,{leftSection:o.jsx(kd,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT_EQUALS),children:"Does not equal..."}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(t_,{size:14}),onClick:()=>e.onPrompt(t,ue.GREATER_THAN),children:"Greater than..."}),o.jsx(je.Item,{leftSection:o.jsx(Vy,{size:14}),onClick:()=>e.onPrompt(t,ue.GREATER_THAN_OR_EQUALS),children:"Greater than or equal to..."}),o.jsx(je.Item,{leftSection:o.jsx(n_,{size:14}),onClick:()=>e.onPrompt(t,ue.LESS_THAN),children:"Less than..."}),o.jsx(je.Item,{leftSection:o.jsx(Vy,{size:14}),onClick:()=>e.onPrompt(t,ue.LESS_THAN_OR_EQUALS),children:"Less than or equal to..."}),o.jsx(Ld,{...e})]})}function fQ(e){const{searchParam:t}=e;return o.jsxs(je.Dropdown,{children:[o.jsx(je.Item,{leftSection:o.jsx(Pd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),o.jsx(je.Item,{leftSection:o.jsx(kd,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT),children:"Does not equal..."}),o.jsx(Ld,{...e})]})}function hQ(e){const{searchParam:t}=e;return o.jsxs(je.Dropdown,{children:[o.jsx(je.Item,{leftSection:o.jsx(vb,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort A to Z"}),o.jsx(je.Item,{leftSection:o.jsx(yb,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Z to A"}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Pd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),o.jsx(je.Item,{leftSection:o.jsx(kd,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT),children:"Does not equal..."}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(QV,{size:14}),onClick:()=>e.onPrompt(t,ue.CONTAINS),children:"Contains..."}),o.jsx(je.Item,{leftSection:o.jsx(GV,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Does not contain..."}),o.jsx(Ld,{...e})]})}function pQ(e){const{searchParam:t}=e;return o.jsxs(je.Dropdown,{children:[o.jsx(je.Item,{leftSection:o.jsx(Pd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),o.jsx(je.Item,{leftSection:o.jsx(kd,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT),children:"Does not equal..."}),o.jsx(Ld,{...e})]})}function Ld(e){const{searchParam:t}=e,n=t.code;return o.jsxs(o.Fragment,{children:[o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(VV,{size:14}),onClick:()=>e.onChange(iT(e.search,n)),children:"Missing"}),o.jsx(je.Item,{leftSection:o.jsx(BV,{size:14}),onClick:()=>e.onChange(iT(e.search,n,!1)),children:"Not missing"}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Hs,{size:14}),onClick:()=>e.onClear(t),children:"Clear filters"})]})}const mQ="_root_vlout_1",gQ="_table_vlout_8",vQ="_tr_vlout_12",yQ="_control_vlout_22",xQ="_icon_vlout_31",zu={root:mQ,table:gQ,tr:vQ,control:yQ,icon:xQ};function bQ(e){const t=e.resourceType,n=[];for(const r of e.fields||["id","_lastUpdated"])n.push(SQ(t,r));return n}function SQ(e,t){var i;if(t==="_lastUpdated")return{name:"_lastUpdated",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_lastUpdated",name:"_lastUpdated",type:"date",expression:"Resource.meta.lastUpdated"}]};if(t==="meta.versionId")return{name:"meta.versionId",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_versionId",name:"_versionId",type:"token",expression:"Resource.meta.versionId"}]};const n=Yo(e,t),r=pU(e,t.toLowerCase());if(n&&r)return{name:t,elementDefinition:n,searchParams:[r]};if(n){const s=nb(e);let c;if(s){const u=new RegExp(`${e}\\.${t.replaceAll("[x]","")}([^\\w-]|$)`);c=Object.values(s).filter(f=>!!f.expression&&u.test(f==null?void 0:f.expression)),c.length===0&&(c=void 0)}return{name:t,elementDefinition:n,searchParams:c}}if(r){const s=Mc(e,r);return{name:t,elementDefinition:(i=s.elementDefinitions)==null?void 0:i[0],searchParams:[r]}}return{name:t}}class wQ extends Event{constructor(t){super("change"),this.definition=t}}class jQ extends Event{constructor(t){super("load"),this.response=t}}class Qh extends Event{constructor(t,n){super("click"),this.resource=t,this.browserEvent=n}}function zc(e){var G,Z;const t=_e(),[n,r]=v.useState(),{search:i,onLoad:s}=e,[c,u]=v.useState(i);sa(i,c)||u(i);const[f,h]=v.useState({selected:{},fieldEditorVisible:!1,filterEditorVisible:!1,exportDialogVisible:!1,filterDialogVisible:!1}),m=v.useRef(f);m.current=f;const g=c.total??"accurate",y=v.useCallback(P=>{r(void 0),t.requestSchema(c.resourceType).then(()=>t.search(c.resourceType,Uo({...c,total:g,fields:void 0}),P)).then(L=>{h({...m.current,searchResponse:L}),s&&s(new jQ(L))}).catch(L=>{h({...m.current,searchResponse:void 0}),r(Zt(L))})},[t,c,g,s]),b=v.useCallback(()=>{h({...m.current,searchResponse:void 0}),y({cache:"reload"})},[y]);v.useEffect(()=>{y()},[y]);function S(P,L){P.stopPropagation();const H=P.target.checked,O={...m.current.selected};H?O[L]=!0:delete O[L],h({...m.current,selected:O})}function j(P){P.stopPropagation();const z=P.target.checked,H={},O=m.current.searchResponse;z&&(O!=null&&O.entry)&&O.entry.forEach(U=>{var K;(K=U.resource)!=null&&K.id&&(H[U.resource.id]=!0)}),h({...m.current,selected:H})}function C(){var L,z;const P=m.current;if(!((L=P.searchResponse)!=null&&L.entry)||P.searchResponse.entry.length===0)return!1;for(const H of P.searchResponse.entry)if((z=H.resource)!=null&&z.id&&!P.selected[H.resource.id])return!1;return!0}function T(P){e.onChange&&e.onChange(new wQ(P))}function D(P,L){if(s_(P.target)||P.button===2)return;pn(P);const z=o_(P);!z&&e.onClick&&e.onClick(new Qh(L,P)),z&&e.onAuxClick&&e.onAuxClick(new Qh(L,P))}function E(){return!!(e.onExport??e.onExportCsv??e.onExportTransactionBundle)}if(n)return o.jsx(Kr,{outcome:n});if(!dA(c.resourceType))return o.jsx(er,{style:{width:"100%",height:"100%"},children:o.jsx(_r,{})});const R=e.checkboxesEnabled,A=bQ(c),k=c.resourceType,M=f.searchResponse,I=M==null?void 0:M.entry,$=I==null?void 0:I.map(P=>P.resource),V="subtle",Y="gray",Q=16,J=window.innerWidth<768;return o.jsxs("div",{className:zu.root,"data-testid":"search-control",children:[!e.hideToolbar&&o.jsxs(Ce,{justify:"space-between",mb:"xl",children:[o.jsxs(Ce,{gap:2,children:[o.jsx(Ne,{size:"compact-md",variant:V,color:Y,leftSection:o.jsx(XV,{size:Q}),onClick:()=>h({...m.current,fieldEditorVisible:!0,dialogOpenTime:Date.now()}),children:"Fields"}),o.jsx(Ne,{size:"compact-md",variant:V,color:Y,leftSection:o.jsx(nF,{size:Q}),onClick:()=>h({...m.current,filterEditorVisible:!0,dialogOpenTime:Date.now()}),children:"Filters"}),e.onNew&&o.jsx(Ne,{size:"compact-md",variant:V,color:Y,leftSection:o.jsx(tF,{size:Q}),onClick:e.onNew,children:"New..."}),!J&&E()&&o.jsx(Ne,{size:"compact-md",variant:V,color:Y,leftSection:o.jsx(jF,{size:Q}),onClick:e.onExport?e.onExport:()=>h({...m.current,exportDialogVisible:!0,dialogOpenTime:Date.now()}),children:"Export..."}),!J&&e.onDelete&&o.jsx(Ne,{size:"compact-md",variant:V,color:Y,leftSection:o.jsx(xb,{size:Q}),onClick:()=>e.onDelete(Object.keys(f.selected)),children:"Delete..."}),!J&&e.onBulk&&o.jsx(Ne,{size:"compact-md",variant:V,color:Y,leftSection:o.jsx(FV,{size:Q}),onClick:()=>e.onBulk(Object.keys(f.selected)),children:"Bulk..."})]}),o.jsxs(Ce,{gap:2,children:[M&&o.jsxs(Ae,{size:"xs",c:"dimmed","data-testid":"count-display",children:[F_(c,M).toLocaleString(),"-",DQ(c,M).toLocaleString(),M.total!==void 0&&` of ${c.total==="estimate"?"~":""}${(G=M.total)==null?void 0:G.toLocaleString()}`]}),o.jsx(_n,{variant:V,color:Y,title:"Refresh",onClick:b,children:o.jsx(i_,{size:Q})})]})]}),o.jsxs(ye,{className:zu.table,children:[o.jsxs(ye.Thead,{children:[o.jsxs(ye.Tr,{children:[R&&o.jsx(ye.Th,{children:o.jsx("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:C(),onChange:P=>j(P)})}),A.map(P=>o.jsx(ye.Th,{children:o.jsxs(je,{shadow:"md",width:240,position:"bottom-end",children:[o.jsx(je.Target,{children:o.jsx(tr,{className:zu.control,p:2,children:o.jsxs(Ce,{justify:"space-between",wrap:"nowrap",children:[o.jsx(Ae,{fw:500,children:Qs(P.name)}),o.jsx(er,{className:zu.icon,children:o.jsx(zV,{size:14,stroke:1.5})})]})})}),o.jsx(lQ,{search:c,searchParams:P.searchParams,onPrompt:(L,z)=>{h({...m.current,filterDialogVisible:!0,filterDialogSearchParam:L,filterDialogFilter:z,dialogOpenTime:Date.now()})},onChange:L=>{T(L)}})]})},P.name))]}),!e.hideFilters&&o.jsxs(ye.Tr,{children:[R&&o.jsx(ye.Th,{}),A.map(P=>o.jsx(ye.Th,{children:P.searchParams&&o.jsx(EQ,{resourceType:k,searchParams:P.searchParams,filters:c.filters})},P.name))]})]}),o.jsx(ye.Tbody,{children:$==null?void 0:$.map(P=>P&&o.jsxs(ye.Tr,{className:zu.tr,"data-testid":"search-control-row",onClick:L=>D(L,P),onAuxClick:L=>D(L,P),children:[R&&o.jsx(ye.Td,{children:o.jsx("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${P.id}`,checked:!!f.selected[P.id],onChange:L=>S(L,P.id)})}),A.map(L=>o.jsx(ye.Td,{children:ZG(P,L)},L.name))]},P.id))})]}),!($!=null&&$.length)&&o.jsx(Ic,{children:o.jsx(er,{style:{height:150},children:o.jsx(Ae,{size:"xl",c:"dimmed",children:"No results"})})}),M&&o.jsx(er,{m:"md",p:"md",children:o.jsx($i,{value:TQ(c),total:RQ(c,M),onChange:P=>T(QG(c,P)),getControlProps:P=>{switch(P){case"previous":return{"aria-label":"Previous page"};case"next":return{"aria-label":"Next page"};default:return{}}}})}),o.jsx(tQ,{search:c,visible:m.current.fieldEditorVisible,onOk:P=>{T(P),h({...m.current,fieldEditorVisible:!1})},onCancel:()=>{h({...m.current,fieldEditorVisible:!1})}},`search-field-editor-${f.dialogOpenTime}`),o.jsx(iQ,{search:c,visible:m.current.filterEditorVisible,onOk:P=>{T(P),h({...m.current,filterEditorVisible:!1})},onCancel:()=>{h({...m.current,filterEditorVisible:!1})}},`search-filter-editor-${f.dialogOpenTime}`),o.jsx(OG,{visible:m.current.exportDialogVisible,exportCsv:e.onExportCsv,exportTransactionBundle:e.onExportTransactionBundle,onCancel:()=>{h({...m.current,exportDialogVisible:!1})}},`search-export-dialog-${f.dialogOpenTime}`),o.jsx(oQ,{visible:m.current.filterDialogVisible,title:(Z=f.filterDialogSearchParam)!=null&&Z.code?Qs(f.filterDialogSearchParam.code):"",resourceType:k,searchParam:f.filterDialogSearchParam,filter:f.filterDialogFilter,defaultValue:"",onOk:P=>{T(lm(c,P.code,P.operator,P.value)),h({...m.current,filterDialogVisible:!1})},onCancel:()=>{h({...m.current,filterDialogVisible:!1})}},`search-filter-dialog-${f.dialogOpenTime}`)]})}const CQ=zc;function EQ(e){const t=(e.filters??[]).filter(n=>e.searchParams.find(r=>r.code===n.code));return t.length===0?o.jsx("span",{children:"no filters"}):o.jsx(o.Fragment,{children:t.map(n=>o.jsxs("div",{children:[B_(n.operator)," ",o.jsx(sQ,{resourceType:e.resourceType,filter:n})]},`filter-${n.code}-${n.operator}-${n.value}`))})}function TQ(e){return Math.floor((e.offset??0)/(e.count??Kp))+1}function RQ(e,t){const n=e.count??Kp,r=H_(e,t);return Math.ceil(r/n)}function F_(e,t){return Math.min(H_(e,t),(e.offset??0)+1)}function DQ(e,t){var n;return Math.max(F_(e,t)+(((n=t.entry)==null?void 0:n.length)??0)-1,0)}function H_(e,t){var r,i;let n=t.total;return n===void 0&&(n=(e.offset??0)+(((r=t.entry)==null?void 0:r.length)??0)+((i=t.link)!=null&&i.some(s=>s.relation==="next")?1:0)),n}function AQ(e){const t=_e(),[n,r]=v.useState(!1),[i,s]=v.useState(),{query:c,fields:u}=e,[f,h]=v.useState(),[m,g]=v.useState({}),y=v.useRef(f);y.current=f;const b=v.useRef({});b.current=m,v.useEffect(()=>{s(void 0),t.graphql(c).then(h).catch(E=>s(Zt(E)))},[t,c]);function S(E,R){E.stopPropagation();const k=E.target.checked,M={...b.current};k?M[R]=!0:delete M[R],g(M)}function j(E){var I;E.stopPropagation();const A=E.target.checked,k={},M=(I=y.current)==null?void 0:I.data.ResourceList;A&&M&&M.forEach($=>{$.id&&(k[$.id]=!0)}),g(k)}function C(){var R;const E=(R=y.current)==null?void 0:R.data.ResourceList;if(!E||E.length===0)return!1;for(const A of E)if(A.id&&!b.current[A.id])return!1;return!0}function T(E,R){s_(E.target)||(pn(E),E.button!==1&&e.onClick&&e.onClick(new Qh(R,E)),E.button===1&&e.onAuxClick&&e.onAuxClick(new Qh(R,E)))}if(v.useEffect(()=>{t.requestSchema(e.resourceType).then(()=>r(!0)).catch(console.log)},[t,e.resourceType]),!n)return o.jsx(_r,{});const D=e.checkboxesEnabled;return o.jsxs("div",{onContextMenu:E=>pn(E),"data-testid":"search-control",children:[o.jsxs(ye,{children:[o.jsx(ye.Thead,{children:o.jsxs(ye.Tr,{children:[D&&o.jsx(ye.Th,{children:o.jsx("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:C(),onChange:E=>j(E)})}),u.map(E=>o.jsx(ye.Th,{children:E.name},E.name))]})}),o.jsx(ye.Tbody,{children:f==null?void 0:f.data.ResourceList.map(E=>E&&o.jsxs(ye.Tr,{"data-testid":"search-control-row",onClick:R=>T(R,E),onAuxClick:R=>T(R,E),children:[D&&o.jsx(ye.Td,{children:o.jsx("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${E.id}`,checked:!!m[E.id],onChange:R=>S(R,E.id)})}),u.map(R=>o.jsx(ye.Td,{children:o.jsx(NG,{propertyType:R.propertyType,path:R.fhirPath,resource:E})},R.name))]},E.id))})]}),(f==null?void 0:f.data.ResourceList.length)===0&&o.jsx("div",{"data-testid":"empty-search",children:"No results"}),i&&o.jsx("div",{"data-testid":"search-error",children:o.jsx("pre",{style:{textAlign:"left"},children:JSON.stringify(i,void 0,2)})}),e.onBulk&&o.jsx(Ne,{onClick:()=>e.onBulk(Object.keys(b.current)),children:"Bulk..."})]})}const _Q=v.memo(AQ),kQ="_root_1fbwr_1",PQ="_entry_1fbwr_8",NQ="_key_1fbwr_13",OQ="_value_1fbwr_20",um={root:kQ,entry:PQ,key:NQ,value:OQ};function ht(e){return o.jsx(Yr,{children:o.jsx("div",{className:um.root,children:e.children})})}ht.Entry=function(t){return o.jsx("div",{className:um.entry,children:t.children})};ht.Key=function(t){return o.jsx("div",{className:um.key,children:t.children})};ht.Value=function(t){return o.jsx("div",{className:um.value,children:t.children})};function MQ(e){const{group:t}=e;return o.jsx(mr,{withBorder:!0,radius:"md",p:"xs",display:"flex",style:{alignItems:"center",justifyContent:"center"},children:o.jsxs(Ce,{children:[t.measureScore&&o.jsx(zQ,{group:t}),!t.measureScore&&o.jsx(LQ,{group:t})]})})}function IQ(e){const{measure:t}=e;return o.jsxs(o.Fragment,{children:[o.jsx(Ae,{fz:"md",fw:500,mb:8,children:t.title}),o.jsx(Ae,{fz:"xs",c:"dimmed",mb:8,children:t.subtitle})]})}function LQ(e){const{group:t}=e,n=t.population,r=n==null?void 0:n.find(f=>Fo(f.code)==="numerator"),i=n==null?void 0:n.find(f=>Fo(f.code)==="denominator"),s=r==null?void 0:r.count,c=i==null?void 0:i.count;if(c===0)return o.jsxs(ce,{children:[o.jsx(Le,{order:3,children:"Not Applicable"}),o.jsx(Ae,{children:`Denominator: ${c}`})]});if(s===void 0||c===void 0)return o.jsxs(ce,{children:[o.jsx(Le,{order:3,children:"Insufficient Data"}),o.jsx(Ae,{children:`Numerator: ${s}`}),o.jsx(Ae,{children:`Denominator: ${c}`})]});const u=s/c*100;return o.jsx(Vp,{size:120,thickness:12,roundCaps:!0,sections:[{value:u,color:q_(u)}],label:o.jsx(Vo,{justify:"center",children:o.jsxs(Ae,{fw:700,fz:18,children:[s," / ",c]})})})}function zQ(e){var r,i,s;const{group:t}=e,n=((r=t.measureScore)==null?void 0:r.unit)??((i=t.measureScore)==null?void 0:i.code);return o.jsx(o.Fragment,{children:n==="%"?o.jsx(Vp,{size:120,thickness:12,roundCaps:!0,sections:[{value:$Q(t),color:q_(((s=t==null?void 0:t.measureScore)==null?void 0:s.value)??0)}],label:o.jsx(Vo,{justify:"center",children:o.jsx(Ae,{fw:700,fz:18,children:o.jsx(cd,{value:t.measureScore})})})}):o.jsx(Vo,{h:120,align:"center",children:o.jsx(Le,{order:3,children:o.jsx(cd,{value:t.measureScore})})})})}function $Q(e){var r,i;const t=(r=e.measureScore)==null?void 0:r.value,n=(i=e.measureScore)==null?void 0:i.unit;return t?t<=1&&n==="%"?t*100:t:0}function q_(e){return e<=33?"red":e<=67?"yellow":"green"}function UQ(e){var r;const t=Qt(e.measureReport),[n]=kV("Measure",{url:t==null?void 0:t.measure});return t?o.jsxs(ce,{children:[n&&o.jsx(IQ,{measure:n}),o.jsx(I0,{cols:{base:3,sm:1},spacing:{base:"md",sm:"sm"},children:(r=t.group)==null?void 0:r.map((i,s)=>o.jsx(MQ,{group:i},i.id??s))})]}):null}const Zv="patient-export",Jv="Patient Export",BQ={everything:{operation:"$everything",extension:"json",contentType:hn.FHIR_JSON},summary:{operation:"$summary",extension:"json",contentType:hn.FHIR_JSON},ccda:{operation:"$ccda-export",extension:"xml",contentType:hn.CDA_XML},ccdaReferral:{operation:"$ccda-export",type:"referral",extension:"xml",contentType:hn.CDA_XML}};function VQ(e){const t=_e(),{patient:n}=e,r=v.useCallback(async i=>{const s=Bs(n),c=i.format,{operation:u,type:f,contentType:h,extension:m}=BQ[c],g=t.fhirUrl("Patient",s,u),y={};f&&(y.type=f),i.author&&(y.author={reference:i.author}),i.authoredOn&&(y.authoredOn=Rb(i.authoredOn)),i.startDate&&(y.start=i.startDate),i.endDate&&(y.end=i.endDate),di.show({id:Zv,title:Jv,loading:!0,message:"Exporting...",autoClose:!1,withCloseButton:!1});try{const b=await t.post(g,y,void 0,{cache:"no-cache",headers:{Accept:h}}),S=`Patient-export-${s}-${new Date().toISOString().replaceAll(":","-")}.${m}`;FQ(b,S,h),di.update({id:Zv,title:Jv,color:"green",message:"Done",icon:o.jsx(eo,{size:"1rem"}),loading:!1,autoClose:!0,withCloseButton:!0})}catch(b){di.update({id:Zv,title:Jv,color:"red",message:Ye(b),icon:o.jsx(Hs,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}},[t,n]);return o.jsx(pt,{onSubmit:r,children:o.jsxs(Ge,{children:[o.jsx($t,{title:"Export Format",description:"Required",withAsterisk:!0,children:o.jsx(Fp,{name:"format",data:[{label:"FHIR Everything",value:"everything"},{label:"Patient Summary",value:"summary"},{label:"C-CDA",value:"ccda"},{label:"C-CDA Referral",value:"ccdaReferral"}],fullWidth:!0})}),o.jsx($t,{title:"Author",description:"Optional author for composition. Default value is current user.",children:o.jsx(Md,{name:"author",placeholder:"Author",targetTypes:["Organization","Practitioner","PractitionerRole"]})}),o.jsx($t,{title:"Authored On",description:"Optional date for composition authored on. Default value is current date.",children:o.jsx(aa,{name:"authoredOn",placeholder:"Authored on"})}),o.jsx($t,{title:"Start Date",description:"The start date of care. If no start date is provided, all records prior to the end date are in scope.",children:o.jsx(aa,{name:"startDate",placeholder:"Start date"})}),o.jsx($t,{title:"End Date",description:"The end date of care. If no end date is provided, all records subsequent to the start date are in scope.",children:o.jsx(aa,{name:"endDate",placeholder:"End date"})}),o.jsx(Ce,{justify:"right",children:o.jsx(Or,{children:"Request Export"})})]})})}function FQ(e,t,n){const r=typeof e=="string"?e:JSON.stringify(e,null,2),i=new Blob([r],{type:n}),s=window.URL.createObjectURL(i),c=document.createElement("a");document.body.appendChild(c),c.style.display="none",c.href=s,c.download=t,c.click(),window.URL.revokeObjectURL(s)}function HQ(e){if(e.gender==="male")return"blue";if(e.gender==="female")return"pink"}function G_(e){var n,r;const t=Qt(e.patient);return t?o.jsxs(ht,{children:[o.jsx(Xo,{value:t,size:"lg",color:HQ(t)}),o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Name"}),o.jsx(ht.Value,{children:o.jsx(mt,{to:t,fw:500,children:t.name?o.jsx(bb,{value:t.name[0],options:{use:!1}}):"[blank]"})})]}),t.birthDate&&o.jsxs(o.Fragment,{children:[o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"DoB"}),o.jsx(ht.Value,{children:t.birthDate})]}),o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Age"}),o.jsx(ht.Value,{children:$8(t.birthDate)})]})]}),t.gender&&o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Gender"}),o.jsx(ht.Value,{children:t.gender})]}),t.address&&o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"State"}),o.jsx(ht.Value,{children:(n=t.address[0])==null?void 0:n.state})]}),(r=t.identifier)==null?void 0:r.map(i=>o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:i==null?void 0:i.system}),o.jsx(ht.Value,{children:i==null?void 0:i.value})]},`${i==null?void 0:i.system}-${i==null?void 0:i.value}`))]}):null}function qQ(e){const{patient:t,...n}=e,r=v.useCallback((i,s,c)=>{const u=`${s}/${c}`,f=100;return Promise.allSettled([i.readHistory("Patient",c),i.search("Communication",{subject:u,_count:f}),i.search("Device",{patient:u,_count:f}),i.search("DeviceRequest",{patient:u,_count:f}),i.search("DiagnosticReport",{subject:u,_count:f}),i.search("Media",{subject:u,_count:f}),i.search("ServiceRequest",{subject:u,_count:f}),i.search("Task",{subject:u,_count:f})])},[]);return o.jsx(sm,{value:t,loadTimelineResources:r,createCommunication:(i,s,c)=>({resourceType:"Communication",status:"completed",subject:on(i),sender:on(s),sent:new Date().toISOString(),payload:[{contentString:c}]}),createMedia:(i,s,c)=>({resourceType:"Media",status:"completed",subject:on(i),operator:on(s),issued:new Date().toISOString(),content:c}),...n})}const GQ="_section_pqpwm_1",QQ="_hovering_pqpwm_7",Gy={section:GQ,hovering:QQ};function WQ(e){const t=_e(),n=Qt(e.value),[r,i]=v.useState(!1),[s,c]=v.useState(),[u,f]=v.useState(),[h,m]=v.useState();function g(){f(void 0)}function y(){c(void 0)}const b=v.useRef(h);if(b.current=h,v.useEffect(()=>{t.requestSchema("PlanDefinition").then(()=>i(!0)).catch(console.log)},[t]),v.useEffect(()=>(m(JQ(n??{resourceType:"PlanDefinition",status:"active"})),document.addEventListener("mouseover",g),document.addEventListener("click",y),()=>{document.removeEventListener("mouseover",g),document.removeEventListener("click",y)}),[n]),!r||!h)return null;function S(j,C){m({...b.current,[j]:C})}return o.jsx("div",{children:o.jsxs(pt,{testid:"questionnaire-form",onSubmit:()=>e.onSubmit(h),children:[o.jsx(ze,{label:"Plan Title",py:"md",defaultValue:h.title,onChange:j=>S("title",j.currentTarget.value)}),o.jsx(YQ,{actions:h.action||[],selectedKey:s,setSelectedKey:c,hoverKey:u,setHoverKey:f,onChange:j=>S("action",j)}),o.jsx(Or,{children:"Save"})]})})}function YQ(e){const t=v.useRef(e.actions);t.current=e.actions;function n(s){e.onChange(t.current.map(c=>c.id===s.id?s:c))}function r(s){e.onChange([...t.current,s]),e.setSelectedKey(s.id)}function i(s){e.onChange(t.current.filter(c=>c!==s))}return o.jsxs(Ge,{gap:"md",className:Gy.section,children:[e.actions.map(s=>o.jsx(KQ,{action:s,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,setHoverKey:e.setHoverKey,onChange:n,onRemove:()=>i(s)},s.id)),o.jsx("div",{children:o.jsx(Ne,{variant:"outline",onClick:s=>{pn(s),r({id:Q_()})},children:"Add action"})})]})}function KQ(e){const{action:t}=e,n=ZQ(t);function r(s){s.stopPropagation(),e.setSelectedKey(e.action.id)}function i(s){pn(s),e.setHoverKey(e.action.id)}return o.jsx("div",{onClick:r,onMouseOver:i,onFocus:i,children:o.jsx(XQ,{action:t,actionType:n,onChange:e.onChange,selectedKey:e.selectedKey,hoverKey:e.hoverKey,onRemove:e.onRemove})})}function XQ(e){const{action:t}=e,[n,r]=v.useState(e.actionType),i=e.selectedKey===e.action.id,s=e.hoverKey===e.action.id;function c(f,h){e.onChange({...t,[f]:h})}const u=Ut(Gy.section,{[Gy.hovering]:s&&!i});return o.jsxs(mr,{"data-testid":t.id,className:u,p:0,radius:"sm",withBorder:!0,children:[o.jsxs(Vo,{w:"100%",p:"xs",bg:"gray.0",gap:"md",align:"center",justify:"space-between",children:[o.jsx(ze,{w:"100%",name:`actionTitle-${t.id}`,defaultValue:t.title,placeholder:"Title",onChange:f=>c("title",f.currentTarget.value)}),o.jsx(Qo,{"data-testid":"close-button",onClick:e.onRemove})]}),i&&o.jsxs(Ge,{gap:"xl",p:"md",children:[o.jsx(ce,{children:o.jsx(ze,{label:"Task Description",placeholder:"Enter task description",name:`actionDescription-${t.id}`,defaultValue:t.description,onChange:f=>c("description",f.currentTarget.value)})}),o.jsx(ce,{children:o.jsx(ln,{label:"Type of Action",value:n,onChange:f=>{const h=f.currentTarget.value==="standard"?void 0:f.currentTarget.value;r(h),e.onChange({...e.action,definitionCanonical:h==="standard"?void 0:e.action.definitionCanonical})},data:[{value:"standard",label:"Standard task"},{value:"questionnaire",label:"Task with Questionnaire"},{value:"activitydefinition",label:"Task with Activity Definition"}]})}),n==="questionnaire"&&o.jsxs(Ge,{gap:0,children:[o.jsxs(Ce,{gap:0,mb:"xs",children:[o.jsx(Ae,{fw:600,children:"Select questionnaire"}),o.jsx(Ae,{c:"red",children:"*"})]}),o.jsxs(Ae,{size:"sm",c:"dimmed",mb:"sm",children:["Questionnaire to be shown in the task in Encounter view. You can create new one from"," ",o.jsx(Nt,{href:"/Questionnaire",target:"_blank",c:"blue",children:"questionnaires list"})]}),o.jsx(aT,{resourceType:"Questionnaire",action:t,onChange:e.onChange})]}),n==="activitydefinition"&&o.jsxs(Ge,{gap:0,children:[o.jsxs(Ce,{gap:0,mb:"xs",children:[o.jsx(Ae,{fw:600,children:"Select activity definition"}),o.jsx(Ae,{c:"red",children:"*"})]}),o.jsxs(Ae,{size:"sm",c:"dimmed",mb:"sm",children:["ActivityDefinition.kind resource to be shown in the task in Encounter view. You can create new one from"," ",o.jsx(Nt,{href:"/ActivityDefinition",target:"_blank",c:"blue",children:"activity definitions list"})]}),o.jsx(aT,{resourceType:"ActivityDefinition",action:t,onChange:e.onChange})]})]})]})}function aT(e){const{id:t,definitionCanonical:n}=e.action,r=n!=null&&n.startsWith(e.resourceType+"/")?{reference:n}:void 0;return o.jsx(il,{name:t,resourceType:e.resourceType,defaultValue:r,onChange:i=>{i?e.onChange({...e.action,definitionCanonical:zt(i)}):e.onChange({...e.action,definitionCanonical:void 0})}})}function ZQ(e){var t,n;return(t=e.definitionCanonical)!=null&&t.startsWith("Questionnaire")?"questionnaire":(n=e.definitionCanonical)!=null&&n.startsWith("ActivityDefinition")?"activitydefinition":"standard"}let ey=1;function Q_(e){if(e){if(e.startsWith("id-")){const t=parseInt(e.substring(3),10);isNaN(t)||(ey=Math.max(ey,t+1))}return e}return"id-"+ey++}function JQ(e){return{...e,action:W_(e.action)}}function W_(e){if(e)return e.map(t=>({...t,id:Q_(t.id),action:W_(t.action)}))}const _t={group:"group",display:"display",boolean:"boolean",decimal:"decimal",integer:"integer",date:"date",dateTime:"dateTime",time:"time",string:"string",text:"text",url:"url",choice:"choice",openChoice:"open-choice",attachment:"attachment",reference:"reference",quantity:"quantity"};function eW(e){return e.type==="choice"||e.type==="open-choice"}function tW(e,t){var i;const n=Ja(e,Dd+"/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-enableWhenExpression");if(t&&n){const s=(i=n.valueExpression)==null?void 0:i.expression;if(s){const c=mi(t),u=Fs(s,[c],{"%resource":c});return ea(u)}}if(!e.enableWhen)return!0;const r=e.enableBehavior??"any";for(const s of e.enableWhen){const c=K_(t==null?void 0:t.item,s.question);if(s.operator==="exists"&&!s.answerBoolean&&!(c!=null&&c.length)){if(r==="any")return!0;continue}const{anyMatch:u,allMatch:f}=aW(s,c,r);if(r==="any"&&u)return!0;if(r==="all"&&!f)return!1}return r!=="any"}function Lb(e,t){return e.map(n=>{if(n.item)return{...n,item:Lb(n.item,t)};try{const r=rW(n,t);if(!r)return null;const i=nW(n,r);return i?{id:n==null?void 0:n.id,linkId:n==null?void 0:n.linkId,text:n.text,answer:[i]}:null}catch(r){return{id:n==null?void 0:n.id,linkId:n==null?void 0:n.linkId,text:n.text,answer:[],extension:[{url:`${Dd}/fhir/StructureDefinition/questionnaire-validationError`,valueString:`Expression evaluation failed: ${Ye(r)}`}]}}}).filter(n=>n!==null)}function nW(e,t){if(e.type)switch(e.type){case _t.boolean:return t.type===oe.boolean?{valueBoolean:t.value}:void 0;case _t.date:return t.type===oe.date?{valueDate:t.value}:void 0;case _t.dateTime:return t.type===oe.dateTime?{valueDateTime:t.value}:void 0;case _t.time:return t.type===oe.time?{valueTime:t.value}:void 0;case _t.url:return t.type===oe.url?{valueString:t.value}:void 0;case _t.text:return t.type===oe.string?{valueString:t.value}:void 0;case _t.attachment:return t.type===oe.Attachment?{valueAttachment:t.value}:void 0;case _t.reference:return t.type===oe.Reference?{valueReference:t.value}:void 0;case _t.quantity:return{valueQuantity:t.value};case _t.decimal:return{valueDecimal:t.value};case _t.integer:return{valueInteger:t.value};case _t.string:return{valueString:t.value};default:return}}function rW(e,t){var r;if(!t)return;const n=Ja(e,Dd+"/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-calculatedExpression");if(n){const i=(r=n.valueExpression)==null?void 0:r.expression;if(i){const s=mi(t),c=Fs(i,[s],{"%resource":s});return c.length!==0?c[0]:void 0}}}function zb(e,t){return e.map(n=>{const r=t.find(i=>i.linkId===n.linkId);return r?{...n,item:r.item?zb(n.item||[],r.item):n.item,answer:r.answer||n.answer,extension:r.extension||n.extension}:n})}function Y_(e,t,n){var i;const r=[];for(const s of e){const c=(i=n.answerOption)==null?void 0:i.find(u=>vc(ca(u))===s);if(c){const u=ca(c);u&&r.push({[t]:u.value})}}return r}function K_(e,t){if(e)for(const n of e){if(n.linkId===t)return n.answer;if(n.item){const r=K_(n.item,t);if(r)return r}}}function iW(e,t,n){if(n==="exists")return!!e===t.value;if(e){const r=n==="="||n==="!="?n==null?void 0:n.replace("=","~"):n,[{value:i}]=Fs(`%actualAnswer ${r} %expectedAnswer`,[e],{"%actualAnswer":e,"%expectedAnswer":t});return i}else return!1}function aW(e,t,n){const r=t||[],i=dW(e);let s=!1,c=!0;for(const u of r){const f=fW(u),{operator:h}=e;if(iW(f,i,h)?s=!0:c=!1,n==="any"&&s)break}return{anyMatch:s,allMatch:c}}function X_(e){var n,r;const t=Ja(e,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource");if(t){if(t.valueCode!==void 0)return[t.valueCode];if(t.valueCodeableConcept)return(r=(n=t.valueCodeableConcept)==null?void 0:n.coding)==null?void 0:r.map(i=>i.code)}}function ty(e,t){var i;const n=Qr(e);let r=Ja(n,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource");return!t||t.length===0?(r&&(n.extension=(i=n.extension)==null?void 0:i.filter(s=>s!==r)),n):(r||(n.extension||(n.extension=[]),r={url:"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource"},n.extension.push(r)),t.length===1?(r.valueCode=t[0],delete r.valueCodeableConcept):(r.valueCodeableConcept={coding:t.map(s=>({code:s}))},delete r.valueCode),n)}function oW(e,t,n){const r=Ja(e,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceFilter");if(!(r!=null&&r.valueString))return;let i=r.valueString;t!=null&&t.reference&&(i=i.replaceAll("$subj",t.reference)),n!=null&&n.reference&&(i=i.replaceAll("$encounter",n.reference));const s={},c=i.split("&");for(const u of c){const[f,h]=Iy(u,"=",2);s[f]=h}return s}function oT(e,t){return{resourceType:"QuestionnaireResponse",questionnaire:e.url??zt(e),item:Z_(e.item,t==null?void 0:t.item),status:"in-progress"}}function Z_(e,t){return(e==null?void 0:e.map(n=>J_(n,t)))??[]}function J_(e,t){var r;const n=t==null?void 0:t.find(i=>i.linkId===e.linkId);return{id:n?n.id:lW(),linkId:e.linkId,text:e.text,item:Z_(e.item,n==null?void 0:n.item),answer:n?n.answer:((r=e.initial)==null?void 0:r.map(cW))??[]}}let sW=1;function lW(){return"id-"+sW++}function cW(e){return{...e}}function uW(e){var n,r,i,s;const t=(n=e==null?void 0:e.item)==null?void 0:n[0];if(t){const c=Ja(t,"http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl");if(((s=(i=(r=c==null?void 0:c.valueCodeableConcept)==null?void 0:r.coding)==null?void 0:i[0])==null?void 0:s.code)==="page")return e.item.length}return 1}function $b(e){return Ad({value:e},"value")}function ca(e){return Ad({value:e},"value")}function dW(e){return Ad({value:e},"answer")}function fW(e){return Ad({value:e},"value")}const ek=v.createContext({}),Is=30,Wh=50;function Qy(e){const t=v.useContext(ek),n=e.item,r=e.response;function i(g){var b,S,j,C;let y;Array.isArray(g)?y=g:e.index>=(((S=(b=e.response)==null?void 0:b.answer)==null?void 0:S.length)??0)?y=(((j=e.response)==null?void 0:j.answer)??[]).concat([g]):y=(((C=e.response)==null?void 0:C.answer)??[]).map((D,E)=>E===e.index?g:D)??[],e.onChange({id:r==null?void 0:r.id,linkId:r==null?void 0:r.linkId,text:n.text,answer:y})}const s=n.type;if(!s)return null;const c=n.linkId;if(!c)return null;const u=n.initial&&n.initial.length>0?n.initial[0]:void 0,f=Bb(r,e.index)??$b(u),h=Ja(r,`${Dd}/fhir/StructureDefinition/questionnaire-validationError`);let m=null;switch(s){case _t.display:m=o.jsx("p",{children:e.item.text},e.item.linkId);break;case _t.boolean:m=o.jsx(R_,{title:e.item.text,htmlFor:e.item.linkId,children:o.jsx(Fn,{id:e.item.linkId,name:e.item.linkId,defaultChecked:f==null?void 0:f.value,onChange:g=>i({valueBoolean:g.currentTarget.checked})})},e.item.linkId);break;case _t.decimal:m=o.jsx(ze,{type:"number",step:"any",id:c,name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueDecimal:g.currentTarget.value===""?void 0:g.currentTarget.valueAsNumber})});break;case _t.integer:m=o.jsx(ze,{type:"number",step:1,id:c,name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueInteger:g.currentTarget.value===""?void 0:g.currentTarget.valueAsNumber})});break;case _t.date:m=o.jsx(ze,{type:"date",id:c,name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueDate:g.currentTarget.value})});break;case _t.dateTime:m=o.jsx(aa,{name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueDateTime:g})});break;case _t.time:m=o.jsx(ze,{type:"time",id:c,name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueTime:g.currentTarget.value})});break;case _t.string:case _t.url:m=o.jsx(ze,{id:c,name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>{const y=g.currentTarget.value;i({valueString:y===""?void 0:y})}});break;case _t.text:m=o.jsx(Js,{id:c,name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>{const y=g.currentTarget.value;i({valueString:y===""?void 0:y})}});break;case _t.attachment:m=o.jsx(Ce,{py:4,children:o.jsx(d_,{path:"",name:c,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueAttachment:g})})});break;case _t.reference:m=o.jsx(Md,{name:c,required:e.required??n.required,targetTypes:X_(n),searchCriteria:oW(n,t.subject,t.encounter),defaultValue:f==null?void 0:f.value,onChange:g=>i({valueReference:g})});break;case _t.quantity:m=o.jsx(qs,{path:"",name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueQuantity:g}),disableWheel:!0});break;case _t.choice:case _t.openChoice:xW(n)?m=o.jsx(gW,{name:c,item:n,initial:u,response:r,onChangeAnswer:g=>i(g)}):yW(n)||n.answerValueSet&&!bW(n)?m=o.jsx(hW,{name:c,item:n,initial:u,response:r,onChangeAnswer:g=>i(g)}):m=o.jsx(mW,{name:c,item:n,initial:u,response:r,onChangeAnswer:g=>i(g)});break;default:return null}return o.jsxs(o.Fragment,{children:[m,(h==null?void 0:h.valueString)&&o.jsx(Ae,{c:"red",size:"lg",mt:4,children:h.valueString})]})}function hW(e){var m;const{name:t,item:n,initial:r,onChangeAnswer:i,response:s}=e;if(!((m=n.answerOption)!=null&&m.length)&&!n.answerValueSet)return o.jsx(Ub,{});const c=$b(r),u=Bb(s)??c,f=rk(s),h=n.repeats||SW(n);if(n.answerValueSet)return o.jsx(nm,{name:t,placeholder:"Select items",binding:n.answerValueSet,maxValues:h?void 0:1,onChange:g=>{h?g.length===0?i({}):i(g.map(y=>({valueCoding:y}))):i({valueCoding:g[0]})},defaultValue:u==null?void 0:u.value});if(h){const{propertyName:g,data:y}=wW(n);return o.jsx(Op,{data:y,placeholder:"Select items",searchable:!0,defaultValue:f||[vc(c)],onChange:b=>{if(b.length===0)i({});else{const S=Y_(b,g,n);i(S)}}})}else{const g=[""];if(n.answerOption)for(const y of n.answerOption){const b=ca(y);g.push(vc(b))}return o.jsx(ln,{id:t,name:t,onChange:y=>{const b=y.currentTarget.selectedIndex;if(b===0){i({});return}const S=n.answerOption[b-1],j=ca(S),C="value"+Hn(j.type);i({[C]:j.value})},defaultValue:_d(u==null?void 0:u.value)||(u==null?void 0:u.value),data:g})}}function pW(e,t){return e?t.valueSetExpand({url:e,count:Is+1}).then(n=>{var r;return((r=n.expansion)==null?void 0:r.contains)??[]}):Promise.resolve([])}function tk(e){const t=_e(),[n,r]=v.useState([]),[i,s]=v.useState(!1);return v.useEffect(()=>{async function c(){if(e){s(!0);try{const u=await pW(e,t);r(u)}catch(u){console.error("Error loading value set:",u)}finally{s(!1)}}}c().catch(console.error)},[e,t]),[n,i]}function nk(e,t){return e.map((n,r)=>{const i=`${t}-valueset-${r}`,s={type:"Coding",value:{system:n.system,code:n.code,display:n.display}};return[i,s]})}function mW(e){const{name:t,item:n,initial:r,onChangeAnswer:i,response:s}=e,c=Yo("QuestionnaireItemAnswerOption","value[x]"),u=$b(r),[f,h]=tk(n.answerValueSet),m=[];let g;if(n.answerValueSet)m.push(...nk(f,t));else if(n.answerOption){const j=n.answerOption.slice(0,Wh).map((C,T)=>{const D=`${t}-option-${T}`,E=ca(C);return E!=null&&E.value?(u&&Ii(E)===Ii(u)&&(g=D),[D,E]):null}).filter(C=>C!==null);m.push(...j)}const y=Bb(s),b=vW(m,y);if(h)return o.jsx(Ae,{children:"Loading options..."});if(m.length===0)return o.jsx(Ub,{});const S=m.slice(0,Is);return o.jsxs(o.Fragment,{children:[o.jsx(Us.Group,{name:t,value:b??g,onChange:j=>{const C=m.find(T=>T[0]===j);if(C){const T=C[1],D="value"+Hn(T.type);i({[D]:T.value})}},children:S.map(([j,C])=>o.jsx(Us,{id:j,value:j,py:4,label:o.jsx(Li,{property:c,propertyType:C.type,value:C.value})},j))}),(n.answerValueSet&&m.length>Is||n.answerOption&&m.length>Wh)&&o.jsxs(Ae,{size:"sm",c:"dimmed",mt:"xs",children:["Showing first ",Is," options"]})]})}function gW(e){var S;const{name:t,item:n,onChangeAnswer:r,response:i}=e,s=Yo("QuestionnaireItemAnswerOption","value[x]"),[c,u]=tk(n.answerValueSet),f=n.answerValueSet?(((S=i.answer)==null?void 0:S.map(j=>j.valueCoding))||[]).filter(j=>j!==void 0):rk(i),[h,m]=v.useState(f),g=[];if(n.answerValueSet)g.push(...nk(c,t));else if(n.answerOption){const j=n.answerOption.slice(0,Wh).map((C,T)=>{const D=`${t}-option-${T}`,E=ca(C);return E!=null&&E.value?[D,E]:null}).filter(C=>C!==null);g.push(...j)}if(u)return o.jsx(Ae,{children:"Loading options..."});if(g.length===0)return o.jsx(Ub,{});const y=g.slice(0,Is),b=(j,C)=>{if(n.answerValueSet){const T=h;let D;C?D=[...T,j.value]:D=T.filter(E=>!sa(E,j.value)),m(D),D.length===0?r({}):r(D.map(E=>({valueCoding:E})))}else{const T=h,D=vc(j);let E;if(C?E=[...T,D]:E=T.filter(R=>R!==D),m(E),E.length===0)r({});else{const R=Y_(E,"value"+Hn(j.type),n);r(R)}}};return o.jsxs(Ce,{style:{flexDirection:"column",alignItems:"flex-start"},children:[y.map(([j,C])=>{const T=vc(C),D=n.answerValueSet?h.some(E=>sa(E,C.value)):h.includes(T);return o.jsx(Fn,{id:j,label:o.jsx(Li,{property:s,propertyType:C.type,value:C.value}),checked:D,onChange:E=>b(C,E.currentTarget.checked)},j)}),(n.answerValueSet&&g.length>Is||n.answerOption&&g.length>Wh)&&o.jsxs(Ae,{size:"sm",c:"dimmed",children:["Showing first ",Is," options"]})]})}function Ub(){return o.jsx(ze,{disabled:!0,placeholder:"No Answers Defined"})}function Bb(e,t=0){const n=e.answer;return ca((n==null?void 0:n[t])??{})}function rk(e){const t=e.answer;return t?t.map(r=>ca(r)).map(r=>_d(r==null?void 0:r.value)||(r==null?void 0:r.value)):[]}function vW(e,t){var n;return(n=e.find(r=>sa(r[1].value,t==null?void 0:t.value)))==null?void 0:n[0]}function dm(e,t){var n;return!!((n=e.extension)!=null&&n.some(r=>{var i,s,c;return r.url==="http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl"&&((c=(s=(i=r.valueCodeableConcept)==null?void 0:i.coding)==null?void 0:s[0])==null?void 0:c.code)===t}))}function yW(e){return dm(e,"drop-down")}function xW(e){return dm(e,"check-box")}function bW(e){return dm(e,"radio-button")}function SW(e){return dm(e,"multi-select")}function wW(e){var s;if(((s=e.answerOption)==null?void 0:s.length)===0)return{propertyName:"",data:[]};const t=e.answerOption[0],n=ca(t),r="value"+Hn(n.type),i=(e.answerOption??[]).map(c=>{const u=ca(c),f=vc(u);return{value:f,label:f}});return{propertyName:r,data:i}}const jW="_section_my8o4_1",CW="_hovering_my8o4_10",EW="_editing_my8o4_14",TW="_questionBody_my8o4_20",RW="_topActions_my8o4_24",DW="_bottomActions_my8o4_33",AW="_movementActions_my8o4_44",_W="_movementIcons_my8o4_56",kW="_columnAlignment_my8o4_60",PW="_linkIdInput_my8o4_65",NW="_typeSelect_my8o4_70",OW="_preserveBreaks_my8o4_74",Fr={section:jW,hovering:CW,editing:EW,questionBody:TW,topActions:RW,bottomActions:DW,movementActions:AW,movementIcons:_W,columnAlignment:kW,linkIdInput:PW,typeSelect:NW,preserveBreaks:OW};function MW(e){const t=_e(),n=Qt(e.questionnaire),[r,i]=v.useState(!1),[s,c]=v.useState(),[u,f]=v.useState(),[h,m]=v.useState();function g(){m(void 0)}function y(){f(void 0)}v.useEffect(()=>{t.requestSchema("Questionnaire").then(()=>i(!0)).catch(console.log)},[t]),v.useEffect(()=>(c($W(n??{resourceType:"Questionnaire",status:"active"})),document.addEventListener("mouseover",g),document.addEventListener("click",y),()=>{document.removeEventListener("mouseover",g),document.removeEventListener("click",y)}),[n]);const b=(S,j)=>{c(S),e.autoSave&&!j&&e.onSubmit&&e.onSubmit(S)};return!r||!s?null:o.jsx("div",{children:o.jsxs(pt,{testid:"questionnaire-form",onSubmit:()=>e.onSubmit(s),children:[o.jsx(ik,{item:s,selectedKey:u,setSelectedKey:f,hoverKey:h,setHoverKey:m,onChange:b}),o.jsx(Or,{children:"Save"})]})})}function ik(e){var E;const t=e.item,n=e.item,r=fa(e.item),i=r||n.type===_t.group,s=n.linkId??"[untitled]",c=e.selectedKey===e.item.id,u=e.hoverKey===e.item.id,f=v.useRef(e.item);f.current=e.item;function h(R){pn(R),e.setSelectedKey(e.item.id)}function m(R){pn(R),e.setHoverKey(e.item.id)}function g(R){var k;const A=f.current;e.onChange({...A,item:(k=A.item)==null?void 0:k.map(M=>M.id===R.id?R:M)})}function y(R,A){e.onChange({...e.item,item:[...e.item.item??[],R]},A)}function b(R){var A;e.onChange({...e.item,item:(A=e.item.item)==null?void 0:A.filter(k=>k!==R)})}function S(R,A){e.onChange({...f.current,[R]:A})}function j(R){e.onChange({...e.item,...R})}function C(R){var A;e.onChange({...e.item,item:(A=e.item.item)==null?void 0:A.map(k=>k===R?{...k,repeats:!k.repeats}:k)})}function T(R,A){const k=VW(e.item.item,R,A);e.onChange({...e.item,item:k})}const D=Ut(Fr.section,{[Fr.editing]:c,[Fr.hovering]:u&&!c});return o.jsxs("div",{"data-testid":n.linkId,className:D,onClick:h,onMouseOver:m,onFocus:m,children:[o.jsx("div",{className:Fr.questionBody,children:c?o.jsxs(o.Fragment,{children:[r&&o.jsx(ze,{size:"xl",defaultValue:t.title,onBlur:R=>S("title",R.currentTarget.value)}),!r&&o.jsx(Js,{autosize:!0,minRows:2,defaultValue:n.text,onBlur:R=>S("text",R.currentTarget.value)}),n.type==="reference"&&o.jsx(zW,{item:n,onChange:j}),eW(n)&&o.jsx(IW,{item:n,onChange:R=>j(R)})]}):o.jsxs(o.Fragment,{children:[t.title&&o.jsx(Le,{children:t.title}),n.text&&o.jsx("div",{className:Fr.preserveBreaks,children:n.text}),!i&&o.jsx(Qy,{item:n,index:0,required:!1,onChange:()=>{},response:{linkId:n.linkId}})]})}),(E=n.item)==null?void 0:E.map((R,A)=>o.jsx("div",{children:o.jsx(ik,{item:R,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,isFirst:A===0,isLast:A===(e.item.item??[]).length-1,setHoverKey:e.setHoverKey,onChange:g,onRemove:()=>b(R),onRepeatable:C,onMoveUp:()=>T(A,-1),onMoveDown:()=>T(A,1)})},R.id)),!i&&o.jsx("div",{className:Fr.topActions,children:c?o.jsxs(o.Fragment,{children:[o.jsx(ze,{size:"xs",className:Fr.linkIdInput,defaultValue:n.linkId,onBlur:R=>S("linkId",R.currentTarget.value)}),!i&&o.jsx(ln,{size:"xs",className:Fr.typeSelect,defaultValue:n.type,onChange:R=>S("type",R.currentTarget.value),data:[{value:"display",label:"Display"},{value:"boolean",label:"Boolean"},{value:"decimal",label:"Decimal"},{value:"integer",label:"Integer"},{value:"date",label:"Date"},{value:"dateTime",label:"Date/Time"},{value:"time",label:"Time"},{value:"string",label:"String"},{value:"text",label:"Text"},{value:"url",label:"URL"},{value:"choice",label:"Choice"},{value:"open-choice",label:"Open Choice"},{value:"attachment",label:"Attachment"},{value:"reference",label:"Reference"},{value:"quantity",label:"Quantity"}]})]}):o.jsx("div",{children:s})}),!r&&o.jsx(ce,{className:Fr.movementActions,children:o.jsxs(ce,{className:Fr.columnAlignment,children:[!e.isFirst&&o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),e.onMoveUp&&e.onMoveUp()},children:o.jsx(UV,{"data-testid":"up-button",size:15,className:Fr.movementIcons})}),!e.isLast&&o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),e.onMoveDown&&e.onMoveDown()},children:o.jsx($V,{"data-testid":"down-button",size:15,className:Fr.movementIcons})})]})}),o.jsxs("div",{className:Fr.bottomActions,children:[i&&o.jsxs(o.Fragment,{children:[o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),y({id:Ws(),linkId:Ky("q"),type:"string",text:"Question"})},children:"Add item"}),o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),y({id:Ws(),linkId:Ky("g"),type:"group",text:"Group"},!0)},children:"Add group"})]}),r&&o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),y(BW(),!0)},children:"Add Page"}),c&&!r&&o.jsxs(o.Fragment,{children:[o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),e.onRepeatable&&e.onRepeatable(n)},children:n.repeats?"Remove Repeatable":"Make Repeatable"}),o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),e.onRemove&&e.onRemove()},children:"Remove"})]})]})]})}function IW(e){const t=Yo("QuestionnaireItemAnswerOption","value[x]"),n=e.item.answerOption??[];return o.jsxs("div",{children:[e.item.answerValueSet!==void 0?o.jsx(ze,{placeholder:"Enter Value Set",defaultValue:e.item.answerValueSet,onChange:r=>e.onChange({...e.item,answerValueSet:r.target.value})}):o.jsx(LW,{options:n,property:t,item:e.item,onChange:e.onChange}),o.jsxs(ce,{display:"flex",children:[o.jsx(Nt,{href:"#",onClick:r=>{pn(r),e.onChange({...e.item,answerValueSet:void 0,answerOption:[...n,{id:Ws()}]})},children:"Add choice"}),o.jsx(Hp,{w:"lg"}),o.jsx(Nt,{href:"#",onClick:r=>{pn(r),e.onChange({...e.item,answerOption:[],answerValueSet:""})},children:"Add value set"})]})]})}function LW(e){return o.jsx("div",{children:e.options.map(t=>{const[n,r]=im({type:"QuestionnaireItemAnswerOption",value:t},"value");return o.jsxs("div",{style:{display:"flex",flexDirection:"row",justifyContent:"space-between",alignItems:"center",width:"80%"},children:[o.jsx("div",{children:o.jsx(Id,{name:"value[x]",path:"Questionnaire.answerOption.value[x]",property:e.property,defaultPropertyType:r,defaultValue:n,onChange:(i,s)=>{const c=[...e.options],u=c.findIndex(f=>f.id===t.id);c[u]={id:t.id,[s]:i},e.onChange({...e.item,answerOption:c})},outcome:void 0},t.id)}),o.jsx("div",{children:o.jsx(Nt,{href:"#",onClick:i=>{pn(i),e.onChange({...e.item,answerOption:e.options.filter(s=>s.id!==t.id)})},children:"Remove"})})]},t.id)})})}function zW(e){const t=X_(e.item)??[];return o.jsxs(o.Fragment,{children:[t.map((n,r)=>o.jsxs(Ce,{children:[o.jsx(jb,{name:"resourceType",placeholder:"Resource Type",defaultValue:n,onChange:i=>{e.onChange(ty(e.item,t.map(s=>s===n?i:s)))}}),o.jsx(Nt,{href:"#",onClick:i=>{pn(i),e.onChange(ty(e.item,t.filter(s=>s!==n)))},children:"Remove"})]},`${n}-${r}`)),o.jsx(Nt,{href:"#",onClick:n=>{pn(n),e.onChange(ty(e.item,[...t,""]))},children:"Add Resource Type"})]})}let Wy=1,Yy=1;function Ky(e){return e+Wy++}function Ws(){return"id-"+Yy++}function $W(e){return{...e,id:e.id||Ws(),item:ak(e.item)}}function ak(e){if(e)return e.forEach(t=>{var n,r;(n=t.id)!=null&&n.match(/^id-\d+$/)&&(Yy=Math.max(Yy,parseInt(t.id.substring(3),10)+1)),(r=t.linkId)!=null&&r.match(/^q\d+$/)&&(Wy=Math.max(Wy,parseInt(t.linkId.substring(1),10)+1))}),e.map(t=>({...t,id:t.id||Ws(),item:ak(t.item),answerOption:UW(t.answerOption)}))}function UW(e){if(e)return e.map(t=>({...t,id:t.id||Ws()}))}function BW(){return{id:Ws(),linkId:Ky("s"),type:"group",text:"New Page",extension:[{url:"http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl",valueCodeableConcept:{coding:[{system:"http://hl7.org/fhir/questionnaire-item-control",code:"page"}]}}]}}function VW(e,t,n){const r=e??[],i=t+n;if(i<0||i>=r.length)return r;const s=[...r];return[s[t],s[i]]=[s[i],s[t]],s}function ok(e){const{item:t,response:n,onChange:r}=e,[i,s]=v.useState(FW(t,n??{linkId:t.linkId}));if(!e.checkForQuestionEnabled(t)||!n)return null;if(t.type===_t.display)return o.jsx("p",{children:t.text},t.linkId);const c=(t==null?void 0:t.repeats)&&t.type!==_t.choice&&t.type!==_t.openChoice;return t.type===_t.boolean?o.jsx(Qy,{item:t,response:n,onChange:u=>r([u]),index:0},t.linkId):o.jsxs($t,{htmlFor:e.item.linkId,title:e.item.text,withAsterisk:e.item.required,children:[[...Array(i)].map((u,f)=>o.jsx(Qy,{item:t,response:n,onChange:h=>r([h]),index:f},`${t.linkId}-${f}`)),c&&o.jsx(Nt,{onClick:()=>s(u=>u+1),children:"Add Item"})]},e.item.linkId)}function FW(e,t){if(e.type===_t.choice||e.type===_t.openChoice)return 1;const n=t.answer;return n!=null&&n.length?n.length:1}function sk(e){const[t,n]=v.useState(e.response);if(v.useEffect(()=>{n(e.response)},[e.response]),t.length===0)return null;function r(s,c){const u=t.map((f,h)=>h===c?s[0]:f);n(u),e.onChange(u)}function i(){const s=J_(e.item,void 0);n([...t,s])}return o.jsxs(o.Fragment,{children:[t.map((s,c)=>o.jsx(lk,{item:e.item,response:s,checkForQuestionEnabled:e.checkForQuestionEnabled,onChange:u=>r(u,c)},s.id)),e.item.repeats&&o.jsx(Nt,{onClick:i,children:`Add Group: ${e.item.text}`})]})}function lk(e){var s;const{response:t,checkForQuestionEnabled:n,onChange:r}=e;function i(c){var m;const u=(m=t.item)==null?void 0:m.map(g=>c.find(b=>b.id===g.id)??g),f=u==null?void 0:u.concat(c.slice(1)),h={...t,item:f};r([h])}return e.checkForQuestionEnabled(e.item)?o.jsxs("div",{children:[e.item.text&&o.jsx(Le,{order:3,mb:"md",children:e.item.text}),o.jsx(Ge,{children:(s=e.item.item)==null?void 0:s.map(c=>{var u,f,h;return c.type===_t.group?c.repeats?o.jsx(sk,{item:c,response:((u=t.item)==null?void 0:u.filter(m=>m.linkId===c.linkId))??[],checkForQuestionEnabled:n,onChange:i},c.linkId):o.jsx(lk,{item:c,checkForQuestionEnabled:n,response:((f=t.item)==null?void 0:f.find(m=>m.linkId===c.linkId))??{linkId:c.linkId},onChange:i},c.linkId):o.jsx(ok,{item:c,response:(h=t.item)==null?void 0:h.find(m=>m.linkId===c.linkId),onChange:i,checkForQuestionEnabled:n},c.linkId)})})]},e.item.linkId):null}function HW(e){const{items:t,response:n,activePage:r,onChange:i,nextStep:s,prevStep:c,numberOfPages:u,renderPages:f,submitButtonText:h,excludeButtons:m,checkForQuestionEnabled:g}=e,y=t.map(b=>{var C;const S=((C=n==null?void 0:n.item)==null?void 0:C.filter(T=>T.linkId===b.linkId))??[],j=b.type===_t.group?o.jsx(sk,{item:b,response:S,onChange:i,checkForQuestionEnabled:g},b.linkId):o.jsx(ok,{item:b,response:S==null?void 0:S[0],onChange:i,checkForQuestionEnabled:g},b.linkId);return f?o.jsx(mc.Step,{label:b.text,children:j},b.linkId):j});return o.jsxs(o.Fragment,{children:[f&&o.jsx(mc,{active:r??0,allowNextStepsSelect:!1,p:6,children:y}),!f&&o.jsx(Ge,{children:y}),!m&&o.jsx(qW,{activePage:r??0,numberOfPages:u,nextStep:f?s:void 0,prevStep:f?c:void 0,renderPages:f,submitButtonText:h})]})}function qW(e){const t=e.renderPages&&e.activePage>0,n=e.renderPages&&e.activePage<e.numberOfPages-1,r=!e.renderPages||e.activePage===e.numberOfPages-1;return o.jsxs(Ce,{justify:"flex-end",mt:"xl",gap:"xs",children:[t&&o.jsx(Ne,{onClick:e.prevStep,children:"Back"}),n&&o.jsx(Ne,{onClick:i=>{const s=i.currentTarget.closest("form");e.nextStep&&s.reportValidity()&&e.nextStep()},children:"Next"}),r&&o.jsx(Or,{children:e.submitButtonText??"Submit"})]})}function ck(e){const t=_e(),{subject:n,source:r}=e,i=Qt(e.questionnaire),s=DV(i),c=Qt(e.questionnaireResponse),[u,f]=v.useState(c),[h,m]=v.useState(0),g=v.useRef(e.onChange);g.current=e.onChange;const y=v.useRef(e.onSubmit);y.current=e.onSubmit,v.useEffect(()=>{if(c!=null&&c.item&&i){const E=oT(i,c),R=dk(E,i);f(R)}else{if(i&&sT(s)===sT(i))return;f(i?oT(i):void 0)}},[c,i,s]),v.useEffect(()=>{if(u&&g.current)try{g.current(u)}catch(E){console.error("Error invoking QuestionnaireForm.onChange callback",E)}},[u]);const b=v.useCallback(E=>{f(R=>QW(R,E,i))},[i]),S=v.useCallback(()=>{const E=y.current;if(E&&i&&u){let R=r;if(!R){const A=t.getProfile();A&&(R=on(A))}E({...u,questionnaire:i.url??zt(i),subject:n,source:R,authored:new Date().toISOString(),status:"completed"})}},[t,i,u,n,r]);function j(E){return tW(E,u)}if(!i||!u)return null;const C=uW(i),T=()=>m(E=>E+1),D=()=>m(E=>E-1);return o.jsx(ek.Provider,{value:{subject:e.subject,encounter:e.encounter},children:o.jsxs(pt,{testid:"questionnaire-form",onSubmit:S,children:[i.title&&o.jsx(Le,{children:i.title}),o.jsx(HW,{items:i.item??[],response:u,onChange:b,renderPages:!e.disablePagination&&C>1,activePage:h,numberOfPages:C,excludeButtons:e.excludeButtons,submitButtonText:e.submitButtonText,checkForQuestionEnabled:j,nextStep:T,prevStep:D})]})})}function GW(e,t){const n=uk(e.item??[],t.item??[]);return{...t,item:n.length>0?n:void 0,answer:t.answer&&t.answer.length>0?t.answer:e.answer}}function uk(e,t){const n=[],r=new Set;for(const i of e){const s=i.id,c=t.find(u=>u.id===s);c?(n.push(GW(i,c)),r.add(c.id)):n.push(i)}for(const i of t)r.has(i.id)||n.push(i);return n}function sT(e){return(e==null?void 0:e.id)||e}function QW(e,t,n){if(!t)return{resourceType:"QuestionnaireResponse",status:"in-progress"};const r=(e==null?void 0:e.item)??[],i=uk(r,Array.isArray(t)?t:[t]),s={resourceType:"QuestionnaireResponse",status:"in-progress",item:i},c=Lb((n==null?void 0:n.item)??[],s);return s.item=zb(i,c),dk(s,n)}function dk(e,t){const n=Lb((t==null?void 0:t.item)??[],e);return{resourceType:"QuestionnaireResponse",status:"in-progress",item:zb(e.item??[],n)}}const WW="_section_4m5it_1",YW={section:WW},KW=["gender","age","gestationalAge","context","appliesTo","category"],XW={definition:{resourceType:"ObservationDefinition",code:{text:""}},onSubmit:()=>{}};function ZW(e){e=Object.assign(XW,e);const t=e.definition,[n,r]=v.useState([]),[i,s]=v.useState(1),[c,u]=v.useState(1);return v.useEffect(()=>{const S=tY(t,u);r(nY(S.qualifiedInterval||[],s))},[t]),o.jsxs(pt,{testid:"reference-range-editor",onSubmit:f,children:[o.jsx(Ge,{children:n.map(S=>{var j;return o.jsx(JW,{unit:iY((j=t.quantitativeDetails)==null?void 0:j.unit),onChange:g,onAdd:y,onRemove:b,onRemoveGroup:m,intervalGroup:S},`group-${S.id}`)})}),o.jsx(_n,{title:"Add Group",variant:"subtle",size:"sm",onClick:S=>{pn(S),h({id:`group-id-${i}`,filters:{},intervals:[]}),s(j=>j+1)},children:o.jsx(qh,{})}),o.jsx(Ce,{justify:"flex-end",children:o.jsx(Or,{children:"Save"})})]});function f(){const S=n.flatMap(j=>j.intervals).filter(j=>!aY(j));e.onSubmit({...t,qualifiedInterval:S})}function h(S){r(j=>[...j,S])}function m(S){r(j=>j.filter(C=>C.id!==S.id))}function g(S,j){r(C=>{C=[...C];const T=C.find(E=>E.id===S),D=T==null?void 0:T.intervals.findIndex(E=>E.id===j.id);return D!==void 0&&(T!=null&&T.intervals[D])&&(T.intervals[D]=j),C})}function y(S,j){j.id===void 0&&(j.id=`id-${c}`,u(C=>C+1)),r(C=>{C=[...C];const T=C.findIndex(D=>D.id===S);if(T!==-1){const D={...C[T]};j={...j,...D.filters},D.intervals=[...D.intervals,j],C[T]=D}return C})}function b(S,j){r(C=>{C=[...C];const T=C.find(D=>D.id===S);return T&&(T.intervals=T.intervals.filter(D=>D.id!==j.id)),C})}}function JW(e){const{intervalGroup:t,unit:n}=e;return o.jsx(Ic,{"data-testid":t.id,className:YW.section,children:o.jsxs(Ge,{gap:"lg",children:[o.jsx(Ce,{justify:"flex-end",children:o.jsx(_n,{title:"Remove Group",variant:"subtle","data-testid":`remove-group-button-${t.id}`,size:"sm",onClick:r=>{pn(r),e.onRemoveGroup(t)},children:o.jsx(Hh,{})},`remove-group-button-${t.id}`)}),o.jsx(eY,{intervalGroup:t,onChange:e.onChange}),o.jsx(Cn,{}),t.intervals.map(r=>o.jsxs(Ge,{gap:"xs",children:[o.jsxs(Ce,{children:[o.jsx(ze,{"data-testid":`condition-${r.id}`,defaultValue:r.condition,label:"Condition: ",size:"sm",onChange:i=>{pn(i),e.onChange(t.id,{...r,condition:i.currentTarget.value.trim()})}},`condition-${r.id}`),o.jsx(_n,{title:"Remove Interval",variant:"subtle",size:"sm","data-testid":`remove-interval-${r.id}`,onClick:i=>{pn(i),e.onRemove(t.id,r)},children:o.jsx(Hh,{})},`remove-interval-${r.id}`)]}),o.jsx(Db,{path:"",onChange:i=>{e.onChange(t.id,{...r,range:i})},name:`range-${r.id}`,defaultValue:r.range},`range-${r.id}`)]},`interval-${r.id}`)),o.jsx(_n,{title:"Add Interval",variant:"subtle",size:"sm",onClick:r=>{pn(r),e.onAdd(t.id,{range:{low:{unit:n},high:{unit:n}}})},children:o.jsx(qh,{})})]})})}function eY(e){var r,i;const{intervalGroup:t,onChange:n}=e;t.filters.age||(t.filters.age={});for(const s of["low","high"])(r=t.filters.age[s])!=null&&r.unit||(t.filters.age[s]={...t.filters.age[s],unit:"years",system:"http://unitsofmeasure.org"});return o.jsxs(Ge,{style:{maxWidth:"50%"},children:[o.jsx(Ce,{children:o.jsx(ln,{data:["","male","female"],label:"Gender:",defaultValue:t.filters.gender||"",onChange:s=>{for(const c of t.intervals){let u=s.currentTarget.value;u===""&&(u=void 0),n(t.id,{...c,gender:u})}}})}),o.jsxs(Ce,{gap:"xs",children:[o.jsx(Ae,{component:"label",htmlFor:`div-age-${t.id}`,children:"Age:"}),o.jsx("div",{id:`div-age-${t.id}`,children:o.jsx(Db,{path:"",name:`age-${t.id}`,defaultValue:t.filters.age,onChange:s=>{for(const c of t.intervals)n(t.id,{...c,age:s})}},`age-${t.id}`)})]}),o.jsx(ln,{data:["","pre-puberty","follicular","midcycle","luteal","postmenopausal"],label:"Endocrine:",defaultValue:((i=t.filters.context)==null?void 0:i.text)||"",onChange:s=>{for(const c of t.intervals){let u=s.currentTarget.value;u===""?(u=void 0,n(t.id,{...c,context:void 0})):n(t.id,{...c,context:{text:u,coding:[{code:u,system:"http://terminology.hl7.org/CodeSystem/referencerange-meaning"}]}})}}}),o.jsx(ln,{data:["","reference","critical","absolute"],label:"Category: ",defaultValue:t.filters.category,onChange:s=>{for(const c of t.intervals){const u=s.currentTarget.value;u===""?n(t.id,{...c,category:void 0}):n(t.id,{...c,category:u})}}})]})}function tY(e,t){const n=e.qualifiedInterval||[];let r=Math.max(...n.map(i=>{var c;const s=parseInt(((c=i.id)==null?void 0:c.substring(3))||"",10);return isNaN(s)?Number.NEGATIVE_INFINITY:s}))+1;return Number.isFinite(r)||(r=1),e={...e,qualifiedInterval:n.map(i=>({...i,id:i.id||`id-${r++}`}))},t(r),e}function nY(e,t){let n=1;const r={};for(const i of e){const s=rY(i);s in r||(r[s]={id:`group-id-${n++}`,filters:Object.fromEntries(KW.map(c=>[c,i[c]])),intervals:[]}),r[s].intervals.push(i)}return t(n),Object.values(r)}function rY(e){var n,r;return[`gender=${e.gender}`,`age=${od(e.age)}`,`gestationalAge=${od(e.gestationalAge)}`,`context=${(n=e.context)==null?void 0:n.text}`,`appliesTo=${(r=e.appliesTo)==null?void 0:r.map(i=>i.text).join("+")}`,`category=${e.category}`].join(":")}function iY(e){return e&&(K8(e,"http://unitsofmeasure.org")||e.text)}function aY(e){var t,n,r,i;return((n=(t=e.range)==null?void 0:t.low)==null?void 0:n.value)===void 0&&((i=(r=e.range)==null?void 0:r.high)==null?void 0:i.value)===void 0}function oY(e){var h;const t=_e(),n=Qt(e.value),[r,i]=v.useState(!1),[s,c]=v.useState();if(v.useEffect(()=>{n&&!r&&(t.executeBatch(u(n)).then(c).catch(console.log),i(!0))},[t,n,r]),!n||!s)return null;return o.jsx(or,{children:(h=n.action)==null?void 0:h.map((m,g)=>{var j,C,T,D,E,R;const y=m.resource&&f(m.resource),b=(C=(j=y==null?void 0:y.input)==null?void 0:j[0])==null?void 0:C.valueReference,S=(D=(T=y==null?void 0:y.output)==null?void 0:T[0])==null?void 0:D.valueReference;return o.jsxs(v.Fragment,{children:[o.jsx(or.Col,{span:1,p:"md",children:(y==null?void 0:y.status)==="completed"?o.jsx(YV,{}):o.jsx(bF,{color:"gray"})}),o.jsxs(or.Col,{span:9,p:"xs",children:[o.jsx(Ae,{fw:500,children:m.title}),m.description&&o.jsx("div",{children:m.description}),o.jsxs("div",{children:["Last edited by ",o.jsx(Lc,{value:(E=y==null?void 0:y.meta)==null?void 0:E.author})," on ",gr((R=y==null?void 0:y.meta)==null?void 0:R.lastUpdated)]}),o.jsxs("div",{children:["Status: ",o.jsx(om,{status:(y==null?void 0:y.status)||"unknown"})]})]}),o.jsxs(or.Col,{span:2,p:"md",children:[b&&!S&&o.jsx(Ne,{onClick:()=>e.onStart(y,b),children:"Start"}),b&&S&&o.jsx(Ne,{onClick:()=>e.onEdit(y,b,S),children:"Edit"})]})]},`action-${g}`)})});function u(m){var y;const g=[];if(m.action)for(const b of m.action)(y=b.resource)!=null&&y.reference&&g.push({request:{method:"GET",url:b.resource.reference}});return{resourceType:"Bundle",type:"batch",entry:g}}function f(m){for(const g of(s==null?void 0:s.entry)??[])if(g.resource&&m.reference===zt(g.resource))return g.resource}}function fk(e,t){const n=sY(e,t);return lY(n,e,t)}function sY(e,t){const n=e.length,r=t.length,i=n+r+1,s=1+2*i,c=s/2|0,u=new Array(s);u[c+1]={i:0,j:-1,prev:void 0,snake:!0};for(let f=0;f<i;f++){for(let h=-f;h<=f;h+=2){const m=c+h,g=m+1,y=m-1,b=u[g],S=u[y];let j,C=0;h===-f||h!==f&&S.i<b.i?(C=b.i,j=b):(C=S.i+1,j=S),u[y]=void 0;let T=C-h,D={i:C,j:T,prev:cY(j),snake:!1};for(;C<n&&T<r&&e[C]===t[T];)C++,T++;if(C>D.i&&(D={i:C,j:T,prev:D,snake:!0}),u[m]=D,C>=n&&T>=r)return u[m]}u[c+f-1]=void 0}}function lY(e,t,n){const r=[];let i=e;for(i.snake&&(i=i.prev);i!=null&&i.prev&&i.prev.j>=0;){const s=i.i,c=i.j;i=i.prev;const u=i.i,f=i.j,h={position:u,lines:t.slice(u,s)},m={position:f,lines:n.slice(f,c)};let g;h.lines.length===0&&m.lines.length>0?g="insert":h.lines.length>0&&m.lines.length===0?g="delete":g="change",r.push({original:h,revised:m,type:g}),i.snake&&(i=i.prev)}return r}function cY(e){return e&&!e.snake&&e.prev?e.prev:e}function uY(e){const t=(e.entry??[]).filter(r=>!!r.resource).map(r=>{var i;return{meta:(i=r.resource)==null?void 0:i.meta,lines:Ii(r.resource,!0).match(/[^\r\n]+/g)}}).sort((r,i)=>r.meta.lastUpdated.localeCompare(i.meta.lastUpdated));if(!t.length)return[];const n=t[0].lines.map(r=>({id:t[0].meta.versionId,meta:t[0].meta,value:r,span:1}));return dY(n,t),fY(n),n}function dY(e,t){for(let n=1;n<t.length;n++){const r=fk(t[n-1].lines,t[n].lines);for(const i of r){const s=i.original.position,c=i.original.lines,u=i.revised.lines;if((i.type==="delete"||i.type==="change")&&e.splice(s,c.length),i.type==="insert"||i.type==="change")for(let f=0;f<i.revised.lines.length;f++)e.splice(s+f,0,{id:t[n].meta.versionId,meta:t[n].meta,value:u[f],span:1})}}}function fY(e){let t=0;for(;t<e.length;){let n=t;for(;n<e.length&&e[n].id===e[t].id;)e[n].span=-1,n++;e[t].span=n-t,t=n}}const hY="_container_1oj0p_1",pY="_root_1oj0p_5",mY="_startRow_1oj0p_20",gY="_normalRow_1oj0p_24",vY="_author_1oj0p_28",yY="_dateTime_1oj0p_32",xY="_lineNumber_1oj0p_37",bY="_line_1oj0p_37",SY="_pre_1oj0p_52",Oa={container:hY,root:pY,startRow:mY,normalRow:gY,author:vY,dateTime:yY,lineNumber:xY,line:bY,pre:SY};function wY(e,t){return`/${e.resourceType}/${e.id}/_history/${t}`}function jY(e){const t=Math.floor((Date.now()-Date.parse(e))/1e3),n=Math.floor(t/31536e3);if(n>0)return Zl(n,"year");const r=Math.floor(t/2592e3);if(r>0)return Zl(r,"month");const i=Math.floor(t/86400);if(i>0)return Zl(i,"day");const s=Math.floor(t/3600);if(s>0)return Zl(s,"hour");const c=Math.floor(t/60);return c>0?Zl(c,"minute"):Zl(t,"second")}function Zl(e,t){return`${e} ${e===1?t:t+"s"} ago`}function CY(e){var c,u;const t=_e(),[n,r]=v.useState(e.history);if(v.useEffect(()=>{!e.history&&e.resourceType&&e.id&&t.readHistory(e.resourceType,e.id).then(r).catch(console.log)},[t,e.history,e.resourceType,e.id]),!n)return o.jsx("div",{children:"Loading..."});const i=(u=(c=n.entry)==null?void 0:c[0])==null?void 0:u.resource;if(!i)return null;const s=uY(n);return o.jsx("div",{className:Oa.container,children:o.jsx("table",{className:Oa.root,children:o.jsx("tbody",{children:s.map((f,h)=>o.jsxs("tr",{className:f.span>0?Oa.startRow:Oa.normalRow,children:[f.span>0&&o.jsxs(o.Fragment,{children:[o.jsx("td",{className:Oa.author,rowSpan:f.span,children:o.jsx(oc,{value:f.meta.author,link:!0})}),o.jsx("td",{className:Oa.dateTime,rowSpan:f.span,children:o.jsx(mt,{to:wY(i,f.meta.versionId),children:jY(f.meta.lastUpdated)})})]}),o.jsx("td",{className:Oa.lineNumber,children:h+1}),o.jsx("td",{className:Oa.line,children:o.jsx("pre",{className:Oa.pre,children:f.value})})]},"row-"+h))})})})}const EY="_removed_el5zk_1",TY="_added_el5zk_6",lT={removed:EY,added:TY};function RY(e){let t=e.original,n=e.revised;e.ignoreMeta&&(t={...t,meta:void 0},n={...n,meta:void 0});const r=Ii(t,!0).match(/[^\r\n]+/g),i=Ii(n,!0).match(/[^\r\n]+/g),s=fk(r,i);return o.jsx("pre",{style:{color:"gray"},children:s.map((c,u)=>o.jsx(DY,{delta:c},"delta"+u))})}function DY(e){return o.jsxs(o.Fragment,{children:["...",o.jsx("br",{}),e.delta.original.lines.length>0&&o.jsx("div",{className:lT.removed,children:e.delta.original.lines.join(`
|
|
536
|
+
}`.replace(/\s+/g," ");return(await e.graphql(r)).data.StructureDefinitionList[0]}function Mq(e){return e.type==="profile"&&!(e!=null&&e.error)&&Rn(e.resourceType)}function Iq(e,t,n){return t===void 0?e:n===void 0?t:`${t}[${n}]`}const Lq="_indented_ldk1d_1",A_={indented:Lq};function Ab({propertyDisplayName:e,onClick:t,testId:n}){const r=e?`Add ${e}`:"Add";return e?o.jsx(Ne,{title:r,size:"sm",color:"green.6",variant:"subtle","data-testid":n,leftSection:o.jsx(qh,{size:"1.25rem"}),onClick:t,children:r}):o.jsx(_n,{title:r,color:"green.6","data-testid":n,onClick:t,children:o.jsx(qh,{size:"1.25rem"})})}function __({propertyDisplayName:e,onClick:t,testId:n}){return o.jsx(_n,{title:e?`Remove ${e}`:"Remove",color:"red.5","data-testid":n,variant:"subtle",onClick:t,children:o.jsx(Hh,{size:"1.25rem"})})}function zq(e){var b,S;const{slice:t,property:n}=e,[r,i]=v.useState(e.defaultValue),s=((b=t.typeSchema)==null?void 0:b.elements)??t.elements,c=v.useContext(cn),u=v.useMemo(()=>{var j;if(Tn(s))return yc({parentContext:c,elements:s,path:e.path,profileUrl:(j=t.typeSchema)==null?void 0:j.url})},[c,e.path,(S=t.typeSchema)==null?void 0:S.url,s]);function f(j){i(j),e.onChange&&e.onChange(j)}const h=t.min>0,m=Rn(t.elements),g=kA(t.name),y=e.property.readonly&&r.length===0;return am(cn.Provider,u,o.jsx($t,{title:g,description:t.definition,withAsterisk:h,fhirPath:`${n.path}:${t.name}`,testId:e.testId,readonly:e.property.readonly,children:y?o.jsx(Ae,{c:"dimmed",children:"(empty)"}):o.jsxs(Ge,{className:m?A_.indented:void 0,children:[r.map((j,C)=>o.jsxs(Ce,{wrap:"nowrap",children:[o.jsx("div",{style:{flexGrow:1},"data-testid":e.testId&&`${e.testId}-elements-${C}`,children:o.jsx(_b,{elementDefinitionType:t.type[0],name:t.name,defaultValue:j,onChange:T=>{const D=[...r];D[C]=T,f(D)},outcome:e.outcome,min:t.min,max:t.max,binding:t.binding,path:e.path,valuePath:void 0,readOnly:e.property.readonly})}),!e.property.readonly&&r.length>t.min&&o.jsx(__,{propertyDisplayName:g,testId:e.testId&&`${e.testId}-remove-${C}`,onClick:T=>{pn(T);const D=[...r];D.splice(C,1),f(D)}})]},`${C}-${r.length}`)),!e.property.readonly&&r.length<t.max&&o.jsx(Ce,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:o.jsx(Ab,{propertyDisplayName:g,onClick:j=>{pn(j);const C=[...r,void 0];f(C)},testId:e.testId&&`${e.testId}-add`})})]})}))}function $q(e){var D;const{property:t}=e,n=_e(),[r,i]=v.useState(!0),[s,c]=v.useState([]),[u]=v.useState(()=>Array.isArray(e.defaultValue)?e.defaultValue:[]),[f,h]=v.useState(()=>[u]),m=v.useContext(cn),g=(D=t.type[0])==null?void 0:D.code;v.useEffect(()=>{j_({medplum:n,property:t}).then(E=>{c(E);const R=w_(u,E,t.slicing,m.profileUrl);Uq(R,E),h(R),i(!1)}).catch(E=>{console.error(E),i(!1)})},[n,t,u,m.profileUrl,h]);function y(E,R){const A=[...f];if(A[R]=E,h(A),e.onChange){const k=A.flat().filter(M=>M!==void 0);e.onChange(k)}}if(r)return o.jsx("div",{children:"Loading..."});const b=s.length,S=f[b],j=!(e.hideNonSliceValues??(g==="Extension"&&s.length>0)),C=Vs(t.path),T=e.property.readonly&&s.length===0&&u.length===0;return o.jsxs(Ge,{className:e.indent?A_.indented:void 0,children:[T&&o.jsx(Ae,{c:"dimmed",children:"(empty)"}),s.map((E,R)=>o.jsx(zq,{slice:E,path:e.path,valuePath:e.valuePath,property:t,defaultValue:f[R],onChange:A=>{y(A,R)},testId:`slice-${E.name}`},E.name)),j&&S.map((E,R)=>o.jsxs(Ce,{wrap:"nowrap",style:{flexGrow:1},children:[o.jsx("div",{style:{flexGrow:1},children:o.jsx(Id,{arrayElement:!0,property:e.property,name:e.name+"."+R,path:e.path,valuePath:Iq(e.path,e.valuePath,R),defaultValue:E,onChange:A=>{const k=[...S];k[R]=A,y(k,b)},defaultPropertyType:void 0,outcome:e.outcome})}),!e.property.readonly&&o.jsx(__,{propertyDisplayName:C,testId:`nonsliced-remove-${R}`,onClick:A=>{pn(A);const k=[...S];k.splice(R,1),y(k,b)}})]},`${R}-${S.length}`)),!e.property.readonly&&j&&f.flat().length<t.max&&o.jsx(Ce,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:o.jsx(Ab,{propertyDisplayName:C,onClick:E=>{pn(E);const R=[...S];R.push(void 0),y(R,b)},testId:"nonsliced-add"})})]})}function Uq(e,t){for(let n=0;n<t.length;n++){const r=t[n],i=e[n];for(;i.length<r.min;)i.push(void 0)}}function Bq(e){const[t,n]=v.useState(!1),r=pR(),i=v.useRef(null),s={...e.styles};return t||(s.input||(s.input={}),s.input.WebkitTextSecurity="disc"),o.jsxs(Vo,{gap:"xs",children:[o.jsx(Js,{...e,styles:{...s,root:{...s.root??{},flexGrow:1}},ref:i,autosize:!0,minRows:1,onFocus:()=>n(!0),onBlur:()=>n(!1)}),o.jsx(_n,{title:"Copy secret",onClick:()=>{var c;r.copy((c=i.current)==null?void 0:c.value),Oe({color:"green",message:"Copied"})},children:o.jsx(JA,{})})]})}const Vq=["sun","mon","tue","wed","thu","fri","sat"];function Fq(e){const[t,n]=v.useState(e.defaultValue),[r,i]=v.useState(!e.disabled&&(e.defaultModalOpen??!1)),s=v.useRef(t);return s.current=t,o.jsxs(o.Fragment,{children:[o.jsxs(Ce,{gap:"xs",grow:!0,wrap:"nowrap",children:[o.jsx("span",{children:DA(s.current)||"No repeat"}),o.jsx(Ne,{disabled:e.disabled,onClick:()=>i(!0),children:"Edit"})]}),!e.disabled&&o.jsx(Hq,{path:e.path,visible:r,defaultValue:s.current,onOk:c=>{e.onChange&&e.onChange(c),n(c),i(!1)},onCancel:()=>i(!1)})]})}const HE={repeat:{period:1,periodUnit:"d"}};function Hq(e){const[t,n]=v.useState(e.defaultValue||HE),{getExtendedProps:r}=v.useContext(cn),[i,s,c,u,f]=v.useMemo(()=>["event","repeat","repeat.period","repeat.periodUnit","repeat.dayOfWeek"].map(j=>r(e.path+"."+j)),[r,e.path]),h=v.useRef(t);h.current=t;function m(j){n({...h.current,event:[j]})}function g(j){n({...h.current,repeat:j})}function y(j){var C;g({...(C=h.current)==null?void 0:C.repeat,period:j})}function b(j){var C;g({...(C=h.current)==null?void 0:C.repeat,periodUnit:j})}function S(j){var C;g({...(C=h.current)==null?void 0:C.repeat,dayOfWeek:j})}return o.jsx($n,{title:"Timing",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:()=>e.onCancel(),children:o.jsxs(Ge,{children:[o.jsx($t,{title:"Starts on",htmlFor:"timing-dialog-start",children:o.jsx(aa,{disabled:i==null?void 0:i.readonly,name:"timing-dialog-start",onChange:j=>m(j)})}),o.jsx(Cd,{disabled:s==null?void 0:s.readonly,label:"Repeat",checked:!!t.repeat,onChange:j=>g(j.currentTarget.checked?HE.repeat:void 0)}),t.repeat&&o.jsxs(o.Fragment,{children:[o.jsx($t,{title:"Repeat every",htmlFor:"timing-dialog-period",children:o.jsxs(Ce,{gap:"xs",grow:!0,wrap:"nowrap",children:[o.jsx(ze,{disabled:c==null?void 0:c.readonly,type:"number",step:1,id:"timing-dialog-period",name:"timing-dialog-period",defaultValue:t.repeat.period||1,onChange:j=>y(parseInt(j.currentTarget.value,10)||1)}),o.jsx(ln,{disabled:u==null?void 0:u.readonly,id:"timing-dialog-periodUnit",name:"timing-dialog-periodUnit",defaultValue:t.repeat.periodUnit,onChange:j=>b(j.currentTarget.value),data:[{label:"second",value:"s"},{label:"minute",value:"min"},{label:"hour",value:"h"},{label:"day",value:"d"},{label:"week",value:"wk"},{label:"month",value:"mo"},{label:"year",value:"a"}]})]})}),t.repeat.periodUnit==="wk"&&o.jsx($t,{title:"Repeat on",children:o.jsx(td.Group,{multiple:!0,onChange:S,children:o.jsx(Ce,{justify:"space-between",mt:"md",gap:"xs",children:Vq.map(j=>o.jsx(td,{value:j,size:"xs",radius:"xl",disabled:f==null?void 0:f.readonly,children:j.charAt(0).toUpperCase()},j))})})})]}),o.jsx(Ce,{justify:"flex-end",children:o.jsx(Ne,{onClick:()=>e.onOk(t),children:"OK"})})]})})}function Id(e){var u;const{property:t,name:n,onChange:r,defaultValue:i}=e,s=e.defaultPropertyType&&e.defaultPropertyType!=="undefined"?e.defaultPropertyType:t.type[0].code,c=t.type;if((t.isArray||t.max>1)&&!e.arrayElement){if(s===oe.Attachment)return o.jsx(TH,{name:n,defaultValue:i,onChange:r,disabled:t.readonly});const f=((u=c[0])==null?void 0:u.code)!==oe.Extension;return o.jsx($q,{property:t,name:n,path:e.path,valuePath:e.valuePath,defaultValue:i,indent:f,onChange:r,outcome:e.outcome})}else return c.length>1?o.jsx(qq,{elementDefinitionTypes:c,...e}):o.jsx(_b,{name:n,defaultValue:i,onChange:f=>{if(e.onChange){const h=e.name.replace("[x]",Hn(c[0].code));e.onChange(f,h)}},outcome:e.outcome,elementDefinitionType:c[0],min:t.min,max:t.min,binding:t.binding,path:e.path,valuePath:e.valuePath,readOnly:t.readonly})}function qq(e){const t=e.elementDefinitionTypes;let n;e.defaultPropertyType&&(n=t.find(s=>s.code===e.defaultPropertyType)),n||(n=t[0]);const[r,i]=v.useState(n);return o.jsxs(Ce,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[o.jsx(ln,{disabled:e.property.readonly,style:{width:"200px"},defaultValue:r.code,"data-testid":e.name&&e.name+"-selector",onChange:s=>{i(t.find(c=>c.code===s.currentTarget.value))},data:t.map(s=>({value:s.code,label:s.code}))}),o.jsx(_b,{name:e.name,defaultValue:e.defaultValue,outcome:e.outcome,elementDefinitionType:r,onChange:s=>{e.onChange&&e.onChange(s,e.name.replace("[x]",Hn(r.code)))},min:e.property.min,max:e.property.max,binding:e.property.binding,path:e.property.path,valuePath:e.valuePath,readOnly:e.property.readonly})]})}function _b(e){const{name:t,onChange:n,outcome:r,binding:i,path:s,valuePath:c,readOnly:u}=e,f=e.min!==void 0&&e.min>0,h=e.elementDefinitionType.code,m=v.useContext(cn),g=v.useMemo(()=>{if(!eb(h)||!Rn(e.defaultValue))return e.defaultValue;const S=Object.create(null);if(m.path===e.path)DE(S,m.elements);else{const j=ks(m.path,e.path);if(j===void 0)return e.defaultValue;DE(S,m.elements,j)}return Tn(S)?S:e.defaultValue},[h,m.path,m.elements,e.path,e.defaultValue]);if(!h)return o.jsx("div",{children:"Property type not specified "});function y(){return{name:t,defaultValue:g,onChange:n,outcome:r,path:s,valuePath:c,disabled:u}}function b(){const S=Ot(e.outcome,c??s);return{id:t,name:t,"data-testid":t,defaultValue:g,required:f,error:S,disabled:u}}switch(h){case oe.SystemString:case oe.canonical:case oe.string:case oe.time:case oe.uri:case oe.url:return e.path==="Project.secret.value[x]"?o.jsx(Bq,{...b(),onChange:S=>{e.onChange&&e.onChange(S.currentTarget.value)}}):o.jsx(ze,{...b(),onChange:S=>{n&&n(S.currentTarget.value)}});case oe.date:return o.jsx(ze,{...b(),type:"date",onChange:S=>{n&&n(S.currentTarget.value)}});case oe.dateTime:case oe.instant:return o.jsx(aa,{...b(),onChange:n,outcome:r});case oe.decimal:case oe.integer:case oe.positiveInt:case oe.unsignedInt:return o.jsx(ze,{...b(),type:"number",step:h===oe.decimal?"any":"1",onChange:S=>{if(n){const j=S.currentTarget.valueAsNumber;n(Number.isNaN(j)?void 0:j)}}});case oe.code:return o.jsx(u_,{...b(),error:void 0,onChange:n,binding:i==null?void 0:i.valueSet,creatable:!0,maxValues:1});case oe.boolean:return o.jsx(Fn,{...b(),defaultChecked:!!g,onChange:S=>{n&&n(S.currentTarget.checked)}});case oe.base64Binary:case oe.markdown:return o.jsx(Js,{...b(),spellCheck:h!==oe.base64Binary,onChange:S=>{n&&n(S.currentTarget.value)}});case oe.Address:return o.jsx(MV,{...y()});case oe.Annotation:return o.jsx(IV,{...y()});case oe.Attachment:return o.jsx(d_,{...y()});case oe.CodeableConcept:return o.jsx(uq,{binding:i==null?void 0:i.valueSet,...y()});case oe.Coding:return o.jsx(hq,{binding:i==null?void 0:i.valueSet,...y()});case oe.ContactDetail:return o.jsx(gq,{...y()});case oe.ContactPoint:return o.jsx(D_,{...y()});case oe.Extension:return o.jsx(xq,{...y(),propertyType:e.elementDefinitionType});case oe.HumanName:return o.jsx(bq,{...y()});case oe.Identifier:return o.jsx(Sq,{...y()});case oe.Money:return o.jsx(jq,{...y()});case oe.Period:return o.jsx(Cq,{...y()});case oe.Duration:case oe.Quantity:return o.jsx(qs,{...y()});case oe.Range:return o.jsx(Db,{...y()});case oe.Ratio:return o.jsx(Tq,{...y()});case oe.Reference:return o.jsx(Md,{...y(),targetTypes:Qq(e.elementDefinitionType)});case oe.Timing:return o.jsx(Fq,{...y()});case oe.Dosage:case oe.UsageContext:default:return o.jsx(kb,{...y(),typeName:h})}}const Gq=[`${Dd}/fhir/StructureDefinition/`,"https://medplum.com/fhir/StructureDefinition/"];function Qq(e){var t;return(t=e==null?void 0:e.targetProfile)==null?void 0:t.map(n=>{const r=Gq.find(i=>n.startsWith(i));return r?n.slice(r.length):n})}function Wq(e){const[t,n]=v.useState(e.defaultValue??{}),r=v.useContext(cn),i=v.useMemo(()=>OV(r.elements),[r.elements]);function s(u){n(u),e.onChange&&e.onChange(u)}const c={type:e.type,value:t};return o.jsx(Ge,{style:{flexGrow:1},"data-testid":e.testId,children:i.map(([u,f])=>{const[h,m]=ZH(c,u,f),g=f.min!==void 0&&f.min>0,y=e.valuePath?e.valuePath+"."+u:void 0,b=o.jsx(Id,{property:f,name:u,path:e.path+"."+u,valuePath:y,defaultValue:h,defaultPropertyType:m,onChange:(S,j)=>{s(lq({...t},u,j??u,f,S))},outcome:e.outcome},u);return e.type==="Extension"||pb.includes(u)?b:f.type.length===1&&f.type[0].code==="boolean"?o.jsx(R_,{title:Vs(u),description:f.description,htmlFor:u,fhirPath:f.path,withAsterisk:g,readonly:f.readonly,children:b},u):o.jsx($t,{title:Vs(u),description:f.description,withAsterisk:g,htmlFor:u,outcome:e.outcome,fhirPath:f.path,errorExpression:y,readonly:f.readonly,children:b},u)})})}function kb(e){const[t]=v.useState(()=>e.defaultValue??{}),n=v.useContext(cn),r=e.profileUrl??(n==null?void 0:n.profileUrl),i=v.useMemo(()=>Gp(e.typeName,r),[e.typeName,r]),s=(i==null?void 0:i.type)??e.typeName,c=v.useMemo(()=>{if(i)return yc({parentContext:n,elements:i.elements,path:e.path,profileUrl:i.url,accessPolicyResource:e.accessPolicyResource})},[i,n,e.path,e.accessPolicyResource]);return i?am(cn.Provider,c,o.jsx(Wq,{path:e.path,valuePath:e.valuePath,type:s,defaultValue:t,onChange:e.onChange,outcome:e.outcome})):o.jsxs("div",{children:[s," not implemented"]})}const Yq="_noteCite_10swh_5",Kq="_noteRoot_10swh_10",qE={noteCite:Yq,noteRoot:Kq};function k_({value:e}){return e?o.jsx(Ge,{justify:"flex-start",gap:"xs",children:e.map(t=>{var n;return t.text&&o.jsx(c0,{classNames:{cite:qE.noteCite,root:qE.noteRoot},cite:((n=t.authorReference)==null?void 0:n.display)||t.authorString,icon:null,children:t.text},`note-${t.text}`)})}):null}function Lc(e){const{value:t,link:n,...r}=e,[i,s]=v.useState(),c=Qt(t,s);let u;if(i&&!oA(i))u=`[${Ye(i)}]`;else if(c)u=Va(c);else return null;return n?o.jsx(mt,{to:t,...r,children:u}):o.jsx(Ae,{component:"span",...r,children:u})}function oc(e){return o.jsxs(Ce,{gap:"xs",children:[o.jsx(Xo,{size:24,radius:12,value:e.value,link:e.link}),o.jsx(Lc,{value:e.value,link:e.link})]})}const Xq={draft:"blue",active:"blue","on-hold":"yellow",revoked:"red",completed:"green","entered-in-error":"red",unknown:"gray",retired:"gray",registered:"blue",preliminary:"blue",final:"green",amended:"yellow",corrected:"yellow",cancelled:"red",requested:"blue",received:"blue",accepted:"blue",rejected:"red",ready:"blue","in-progress":"blue",failed:"red",proposed:"blue",pending:"blue",booked:"blue",arrived:"blue",fulfilled:"green",noshow:"red","checked-in":"blue",waitlist:"gray",routine:"gray",urgent:"red",asap:"red",stat:"red","not-done":"red",connected:"green",disconnected:"red",finished:"green",planned:"gray"};function om(e){const{status:t,...n}=e;return o.jsx(Cp,{color:e.color||Xq[t],...n,children:t.replace(/-/g," ")})}const Zq="_table_pe9td_1",Jq="_criticalRow_pe9td_12",P_={table:Zq,criticalRow:Jq};Pb.defaultProps={hideObservationNotes:!1,hideSpecimenInfo:!1,hideSubject:!1};function Pb(e){var c;const t=_e(),n=Qt(e.value),[r,i]=v.useState();if(v.useEffect(()=>{n!=null&&n.specimen&&Promise.allSettled(n.specimen.map(u=>t.readReference(u))).then(u=>u.filter(f=>f.status==="fulfilled").map(f=>f.value)).then(i).catch(console.error)},[t,n]),!n)return null;const s=(r==null?void 0:r.flatMap(u=>u.note||[]))||[];if(n.presentedForm&&n.presentedForm.length>0){const u=n.presentedForm[0];(c=u.contentType)!=null&&c.startsWith("text/plain")&&u.data&&s.push({text:window.atob(u.data)})}return o.jsxs(Ge,{children:[o.jsx(Le,{children:"Diagnostic Report"}),o.jsx(eG,{value:n,hideSubject:e.hideSubject}),r&&!e.hideSpecimenInfo&&tG(r),n.result&&o.jsx(nG,{hideObservationNotes:e.hideObservationNotes,value:n.result}),s.length>0&&o.jsx(k_,{value:s})]})}function eG({value:e,hideSubject:t=!1}){var n,r;return o.jsxs(Ce,{mt:"md",gap:30,children:[e.subject&&!t&&o.jsxs("div",{children:[o.jsx(Ae,{size:"xs",tt:"uppercase",c:"dimmed",children:"Subject"}),o.jsx(oc,{value:e.subject,link:!0})]}),(n=e.resultsInterpreter)==null?void 0:n.map(i=>o.jsxs("div",{children:[o.jsx(Ae,{size:"xs",tt:"uppercase",c:"dimmed",children:"Interpreter"}),o.jsx(oc,{value:i,link:!0})]},i.reference)),(r=e.performer)==null?void 0:r.map(i=>o.jsxs("div",{children:[o.jsx(Ae,{size:"xs",tt:"uppercase",c:"dimmed",children:"Performer"}),o.jsx(oc,{value:i,link:!0})]},i.reference)),e.issued&&o.jsxs("div",{children:[o.jsx(Ae,{size:"xs",tt:"uppercase",c:"dimmed",children:"Issued"}),o.jsx(Ae,{children:gr(e.issued)})]}),e.status&&o.jsxs("div",{children:[o.jsx(Ae,{size:"xs",tt:"uppercase",c:"dimmed",children:"Status"}),o.jsx(om,{status:e.status})]})]})}function tG(e){return o.jsxs(Ge,{gap:"xs",children:[o.jsx(Le,{order:2,size:"h6",children:"Specimens"}),o.jsx(pr,{type:"ordered",children:e==null?void 0:e.map(t=>{var n;return o.jsx(pr.Item,{ml:"sm",children:o.jsxs(Ce,{gap:20,children:[o.jsxs(Ce,{gap:5,children:[o.jsx(Ae,{fw:500,children:"Collected:"})," ",gr((n=t.collection)==null?void 0:n.collectedDateTime)]}),o.jsxs(Ce,{gap:5,children:[o.jsx(Ae,{fw:500,children:"Received:"})," ",gr(t.receivedTime)]})]})},`specimen-${t.id}`)})})]})}function nG(e){return o.jsxs("table",{className:P_.table,children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Test"}),o.jsx("th",{children:"Value"}),o.jsx("th",{children:"Reference Range"}),o.jsx("th",{children:"Interpretation"}),o.jsx("th",{children:"Category"}),o.jsx("th",{children:"Performer"}),o.jsx("th",{children:"Status"})]})}),o.jsx("tbody",{children:o.jsx(N_,{value:e.value,ancestorIds:e.ancestorIds,hideObservationNotes:e.hideObservationNotes})})]})}function N_(e){var t;return o.jsx(o.Fragment,{children:(t=e.value)==null?void 0:t.map(n=>o.jsx(rG,{value:n,ancestorIds:e.ancestorIds,hideObservationNotes:e.hideObservationNotes},`obs-${Ko(n)?n.reference:n.id}`))})}function rG(e){var i,s;const t=Qt(e.value);if(!t||(i=e.ancestorIds)!=null&&i.includes(t.id))return null;const n=!e.hideObservationNotes&&t.note,r=oG(t);return o.jsxs(o.Fragment,{children:[o.jsxs("tr",{className:Ut({[P_.criticalRow]:r}),children:[o.jsx("td",{rowSpan:n?2:1,children:o.jsx(mt,{to:t,children:o.jsx(ia,{value:t.code})})}),o.jsx("td",{children:o.jsx(iG,{value:t})}),o.jsx("td",{children:o.jsx(aG,{value:t.referenceRange})}),o.jsx("td",{children:t.interpretation&&t.interpretation.length>0&&o.jsx(ia,{value:t.interpretation[0]})}),o.jsx("td",{children:t.category&&t.category.length>0&&o.jsx(o.Fragment,{children:t.category.map(c=>o.jsx("div",{children:o.jsx(ia,{value:c})},`category-${Fo(c)}`))})}),o.jsx("td",{children:(s=t.performer)==null?void 0:s.map(c=>o.jsx(Hy,{value:c},c.reference))}),o.jsx("td",{children:t.status&&o.jsx(om,{status:t.status})})]}),t.hasMember&&o.jsx(N_,{value:t.hasMember,ancestorIds:e.ancestorIds?[...e.ancestorIds,t.id]:[t.id],hideObservationNotes:e.hideObservationNotes}),n&&o.jsx("tr",{children:o.jsx("td",{colSpan:6,children:o.jsx(k_,{value:t.note})})})]})}function iG(e){const t=e.value;return o.jsx(o.Fragment,{children:AA(t)})}function aG(e){const t=e.value&&e.value.length>0&&e.value[0];return t?t.text?o.jsx(o.Fragment,{children:t.text}):o.jsx(Tb,{value:t}):null}function oG(e){var n,r,i,s;const t=(s=(i=(r=(n=e.interpretation)==null?void 0:n[0])==null?void 0:r.coding)==null?void 0:i[0])==null?void 0:s.code;return t==="AA"||t==="LL"||t==="HH"||t==="A"}var Yv={},Na={},GE;function O_(){if(GE)return Na;GE=1,Object.defineProperty(Na,"__esModule",{value:!0}),Na.Pointer=Na.escapeToken=Na.unescapeToken=void 0;function e(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}Na.unescapeToken=e;function t(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}Na.escapeToken=t;var n=function(){function r(i){i===void 0&&(i=[""]),this.tokens=i}return r.fromJSON=function(i){var s=i.split("/").map(e);if(s[0]!=="")throw new Error("Invalid JSON Pointer: ".concat(i));return new r(s)},r.prototype.toString=function(){return this.tokens.map(t).join("/")},r.prototype.evaluate=function(i){for(var s=null,c="",u=i,f=1,h=this.tokens.length;f<h;f++)s=u,c=this.tokens[f],!(c=="__proto__"||c=="constructor"||c=="prototype")&&(u=(s||{})[c]);return{parent:s,key:c,value:u}},r.prototype.get=function(i){return this.evaluate(i).value},r.prototype.set=function(i,s){var c=this.evaluate(i);c.parent&&(c.parent[c.key]=s)},r.prototype.push=function(i){this.tokens.push(i)},r.prototype.add=function(i){var s=this.tokens.concat(String(i));return new r(s)},r}();return Na.Pointer=n,Na}var gn={},Kv={},QE;function M_(){return QE||(QE=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.clone=e.objectType=e.hasOwnProperty=void 0,e.hasOwnProperty=Object.prototype.hasOwnProperty;function t(i){return i===void 0?"undefined":i===null?"null":Array.isArray(i)?"array":typeof i}e.objectType=t;function n(i){return i!=null&&typeof i=="object"}function r(i){if(!n(i))return i;if(i.constructor==Array){for(var s=i.length,c=new Array(s),u=0;u<s;u++)c[u]=r(i[u]);return c}if(i.constructor==Date){var f=new Date(+i);return f}var h={};for(var m in i)e.hasOwnProperty.call(i,m)&&(h[m]=r(i[m]));return h}e.clone=r}(Kv)),Kv}var fr={},WE;function I_(){if(WE)return fr;WE=1,Object.defineProperty(fr,"__esModule",{value:!0}),fr.diffAny=fr.diffObjects=fr.diffArrays=fr.intersection=fr.subtract=fr.isDestructive=void 0;var e=M_();function t(m){var g=m.op;return g==="remove"||g==="replace"||g==="copy"||g==="move"}fr.isDestructive=t;function n(m,g){var y={};for(var b in m)e.hasOwnProperty.call(m,b)&&m[b]!==void 0&&(y[b]=1);for(var S in g)e.hasOwnProperty.call(g,S)&&g[S]!==void 0&&delete y[S];return Object.keys(y)}fr.subtract=n;function r(m){for(var g=m.length,y={},b=0;b<g;b++){var S=m[b];for(var j in S)e.hasOwnProperty.call(S,j)&&S[j]!==void 0&&(y[j]=(y[j]||0)+1)}for(var j in y)y[j]<g&&delete y[j];return Object.keys(y)}fr.intersection=r;function i(m){return m.op==="add"}function s(m){return m.op==="remove"}function c(m,g){return{operations:m.operations.concat(g),cost:m.cost+1}}function u(m,g,y,b){b===void 0&&(b=h);var S={"0,0":{operations:[],cost:0}};function j(R,A){var k="".concat(R,",").concat(A),M=S[k];if(M===void 0){if(R>0&&A>0&&!b(m[R-1],g[A-1],y.add(String(R-1))).length)M=j(R-1,A-1);else{var I=[];if(R>0){var $=j(R-1,A),V={op:"remove",index:R-1};I.push(c($,V))}if(A>0){var Y=j(R,A-1),Q={op:"add",index:R-1,value:g[A-1]};I.push(c(Y,Q))}if(R>0&&A>0){var J=j(R-1,A-1),G={op:"replace",index:R-1,original:m[R-1],value:g[A-1]};I.push(c(J,G))}var Z=I.sort(function(P,L){return P.cost-L.cost})[0];M=Z}S[k]=M}return M}var C=isNaN(m.length)||m.length<=0?0:m.length,T=isNaN(g.length)||g.length<=0?0:g.length,D=j(C,T).operations,E=D.reduce(function(R,A){var k=R[0],M=R[1];if(i(A)){var I=A.index+1+M,$=I<C+M?String(I):"-",V={op:A.op,path:y.add($).toString(),value:A.value};return[k.concat(V),M+1]}else if(s(A)){var V={op:A.op,path:y.add(String(A.index+M)).toString()};return[k.concat(V),M-1]}else{var Y=y.add(String(A.index+M)),Q=b(A.original,A.value,Y);return[k.concat.apply(k,Q),M]}},[[],0])[0];return E}fr.diffArrays=u;function f(m,g,y,b){b===void 0&&(b=h);var S=[];return n(m,g).forEach(function(j){S.push({op:"remove",path:y.add(j).toString()})}),n(g,m).forEach(function(j){S.push({op:"add",path:y.add(j).toString(),value:g[j]})}),r([m,g]).forEach(function(j){S.push.apply(S,b(m[j],g[j],y.add(j)))}),S}fr.diffObjects=f;function h(m,g,y,b){if(b===void 0&&(b=h),m===g)return[];var S=(0,e.objectType)(m),j=(0,e.objectType)(g);return S=="array"&&j=="array"?u(m,g,y,b):S=="object"&&j=="object"?f(m,g,y,b):[{op:"replace",path:y.toString(),value:g}]}return fr.diffAny=h,fr}var YE;function sG(){if(YE)return gn;YE=1;var e=gn&&gn.__extends||function(){var C=function(T,D){return C=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(E,R){E.__proto__=R}||function(E,R){for(var A in R)Object.prototype.hasOwnProperty.call(R,A)&&(E[A]=R[A])},C(T,D)};return function(T,D){if(typeof D!="function"&&D!==null)throw new TypeError("Class extends value "+String(D)+" is not a constructor or null");C(T,D);function E(){this.constructor=T}T.prototype=D===null?Object.create(D):(E.prototype=D.prototype,new E)}}();Object.defineProperty(gn,"__esModule",{value:!0}),gn.apply=gn.InvalidOperationError=gn.test=gn.copy=gn.move=gn.replace=gn.remove=gn.add=gn.TestError=gn.MissingError=void 0;var t=O_(),n=M_(),r=I_(),i=function(C){e(T,C);function T(D){var E=C.call(this,"Value required at path: ".concat(D))||this;return E.path=D,E.name="MissingError",E}return T}(Error);gn.MissingError=i;var s=function(C){e(T,C);function T(D,E){var R=C.call(this,"Test failed: ".concat(D," != ").concat(E))||this;return R.actual=D,R.expected=E,R.name="TestError",R}return T}(Error);gn.TestError=s;function c(C,T,D){if(Array.isArray(C))if(T=="-")C.push(D);else{var E=parseInt(T,10);C.splice(E,0,D)}else C[T]=D}function u(C,T){if(Array.isArray(C)){var D=parseInt(T,10);C.splice(D,1)}else delete C[T]}function f(C,T){var D=t.Pointer.fromJSON(T.path).evaluate(C);return D.parent===void 0?new i(T.path):(c(D.parent,D.key,(0,n.clone)(T.value)),null)}gn.add=f;function h(C,T){var D=t.Pointer.fromJSON(T.path).evaluate(C);return D.value===void 0?new i(T.path):(u(D.parent,D.key),null)}gn.remove=h;function m(C,T){var D=t.Pointer.fromJSON(T.path).evaluate(C);if(D.parent===null)return new i(T.path);if(Array.isArray(D.parent)){if(parseInt(D.key,10)>=D.parent.length)return new i(T.path)}else if(D.value===void 0)return new i(T.path);return D.parent[D.key]=(0,n.clone)(T.value),null}gn.replace=m;function g(C,T){var D=t.Pointer.fromJSON(T.from).evaluate(C);if(D.value===void 0)return new i(T.from);var E=t.Pointer.fromJSON(T.path).evaluate(C);return E.parent===void 0?new i(T.path):(u(D.parent,D.key),c(E.parent,E.key,D.value),null)}gn.move=g;function y(C,T){var D=t.Pointer.fromJSON(T.from).evaluate(C);if(D.value===void 0)return new i(T.from);var E=t.Pointer.fromJSON(T.path).evaluate(C);return E.parent===void 0?new i(T.path):(c(E.parent,E.key,(0,n.clone)(D.value)),null)}gn.copy=y;function b(C,T){var D=t.Pointer.fromJSON(T.path).evaluate(C);return(0,r.diffAny)(D.value,T.value,new t.Pointer).length?new s(D.value,T.value):null}gn.test=b;var S=function(C){e(T,C);function T(D){var E=C.call(this,"Invalid operation: ".concat(D.op))||this;return E.operation=D,E.name="InvalidOperationError",E}return T}(Error);gn.InvalidOperationError=S;function j(C,T){switch(T.op){case"add":return f(C,T);case"remove":return h(C,T);case"replace":return m(C,T);case"move":return g(C,T);case"copy":return y(C,T);case"test":return b(C,T)}return new S(T)}return gn.apply=j,gn}var KE;function lG(){return KE||(KE=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createTests=e.createPatch=e.applyPatch=e.Pointer=void 0;var t=O_();Object.defineProperty(e,"Pointer",{enumerable:!0,get:function(){return t.Pointer}});var n=sG(),r=I_();function i(h,m){return m.map(function(g){return(0,n.apply)(h,g)})}e.applyPatch=i;function s(h){function m(g,y,b){var S=h(g,y,b);return Array.isArray(S)?S:(0,r.diffAny)(g,y,b,m)}return m}function c(h,m,g){var y=new t.Pointer;return(g?s(g):r.diffAny)(h,m,y)}e.createPatch=c;function u(h,m){var g=t.Pointer.fromJSON(m).evaluate(h);if(g!==void 0)return{op:"test",path:m,value:g.value}}function f(h,m){var g=new Array;return m.filter(r.isDestructive).forEach(function(y){var b=u(h,y.path);if(b&&g.push(b),"from"in y){var S=u(h,y.from);S&&g.push(S)}}),g}e.createTests=f}(Yv)),Yv}var L_=lG();const cG="_removed_el5zk_1",uG="_added_el5zk_6",XE={removed:cG,added:uG};function dG(e){var m;const{name:t,path:n,property:r,originalValue:i,revisedValue:s}=e,c=!!((m=r==null?void 0:r.type)!=null&&m.find(g=>g.code==="Attachment")),[u,f]=v.useState(c),h=()=>f(g=>!g);return o.jsx(o.Fragment,{children:c&&!u||!c?o.jsx(o.Fragment,{children:o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:t}),o.jsx(ye.Td,{className:XE.removed,children:i&&o.jsx(Li,{path:n,property:r,propertyType:i.type,value:i.value,ignoreMissingValues:!0})}),o.jsx(ye.Td,{className:XE.added,children:s&&o.jsx(Li,{path:n,property:r,propertyType:s.type,value:s.value,ignoreMissingValues:!0})})]})}):o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:t}),o.jsx(ye.Td,{colSpan:2,style:{textAlign:"right"},children:o.jsx(Ne,{onClick:h,variant:"light",children:"Expand"})})]})})}const fG="_root_15xvr_1",hG={root:fG};function pG(e){const t=_e(),{original:n,revised:r}=e,[i,s]=v.useState(!1);v.useEffect(()=>{t.requestSchema(e.original.resourceType).then(()=>s(!0)).catch(console.log)},[t,e.original.resourceType]);const c=v.useMemo(()=>{if(!i)return null;const u=[mi(n)],f=[mi(r)],h=[],m=mG(L_.createPatch(n,r));for(const g of m){const y=g.path,b=gG(y),S=vG(n.resourceType,b),j=g.op==="add"?void 0:Fs(b,u),C=g.op==="remove"?void 0:Fs(b,f);h.push({key:`op-${g.op}-${g.path}`,name:`${Hn(g.op)} ${b}`,path:(S==null?void 0:S.path)??n.resourceType+"."+b,property:S,originalValue:ZE(S,j),revisedValue:ZE(S,C)})}return h},[i,n,r]);return c?o.jsxs(ye,{className:hG.root,children:[o.jsx(ye.Thead,{children:o.jsxs(ye.Tr,{children:[o.jsx(ye.Th,{}),o.jsx(ye.Th,{children:"Before"}),o.jsx(ye.Th,{children:"After"})]})}),o.jsx(ye.Tbody,{children:c.map(u=>{const{key:f,...h}=u;return o.jsx(dG,{...h},f)})})]}):null}function mG(e){const t=[];for(const n of e){const{op:r,path:i}=n;if(i.startsWith("/meta/author")||i.startsWith("/meta/compartment")||i.startsWith("/meta/lastUpdated")||i.startsWith("/meta/versionId"))continue;const s=e.filter(u=>u.op===r&&u.path===i).length,c={op:r,path:i};s>1&&(r==="add"||r==="remove")&&/\/[0-9-]+$/.test(i)&&(c.op="replace",c.path=i.replace(/\/[^/]+$/,"")),t.some(u=>u.op===c.op&&u.path===c.path)||t.push(c)}return t}function gG(e){const t=e.split("/").filter(Boolean);let n="";for(let r=0;r<t.length;r++){const i=t[r];i==="-"?n+=".last()":/^\d+$/.test(i)?n+=`[${i}]`:(r>0&&(n+="."),n+=i)}return n.endsWith(".url")&&(n=n.replace(/\.url$/,"")),n}function vG(e,t){var r;const n=Mc(e,{code:e+"."+t,expression:e+"."+t});return(r=n==null?void 0:n.elementDefinitions)==null?void 0:r[0]}function ZE(e,t){return t&&{type:Array.isArray(t)?t[0].type:t.type,value:yG(t,!!(e!=null&&e.isArray))}}function yG(e,t){const n=X$(e).flatMap(r=>r.value);return t?n:n[0]}function Nb(e){const{profileUrl:t}=e,n=_e(),r=n.getAccessPolicy(),i=Qt(e.value),[s,c]=v.useState(!1);v.useEffect(()=>{if(i)if(t)n.requestProfileSchema(t,{expandProfile:!0}).then(()=>{Pc(t)?c(!0):console.error(`Schema not found for ${t}`)}).catch(f=>{console.error("Error in requestProfileSchema",f)});else{const f=i.resourceType;n.requestSchema(f).then(()=>{c(!0)}).catch(console.error)}},[n,t,i]);const u=v.useMemo(()=>i&&IA(i,Ns.READ,r),[r,i]);return!s||!i?null:o.jsx(Gh,{path:i.resourceType,value:{type:i.resourceType,value:e.forceUseInput?e.value:i},profileUrl:t,ignoreMissingValues:e.ignoreMissingValues,accessPolicyResource:u})}const xG="_item_5q6yx_1",bG="_itemPadding_5q6yx_5",JE={item:xG,itemPadding:bG};function SG(e){return o.jsx(Ic,{children:e.children})}function Gs(e){var f,h;const{resource:t,profile:n,padding:r,popupMenuItems:i,...s}=e,c=n??((f=t.meta)==null?void 0:f.author),u=e.dateTime??((h=t.meta)==null?void 0:h.lastUpdated);return o.jsxs(rm,{"data-testid":"timeline-item",fill:!0,...s,children:[o.jsxs(Ce,{justify:"space-between",gap:8,mx:"xs",my:"sm",children:[o.jsx(Xo,{value:c,link:!0,size:"md"}),o.jsxs("div",{style:{flex:1},children:[o.jsx(Ae,{size:"sm",children:o.jsx(Lc,{c:"dark",fw:500,value:c,link:!0})}),o.jsxs(Ae,{size:"xs",children:[o.jsx(mt,{c:"dimmed",to:e.resource,children:gr(u)}),o.jsx(Ae,{component:"span",c:"dimmed",mx:8,children:"·"}),o.jsx(mt,{c:"dimmed",to:e.resource,children:e.resource.resourceType})]})]}),i&&o.jsxs(je,{position:"bottom-end",shadow:"md",width:200,children:[o.jsx(je.Target,{children:o.jsx(_n,{color:"gray",variant:"subtle",radius:"xl","aria-label":`Actions for ${zt(e.resource)}`,children:o.jsx(eF,{})})}),i]})]}),o.jsx(a_,{children:o.jsx("div",{className:Ut(JE.item,{[JE.itemPadding]:r}),children:e.children})})]})}function z_(e,t){e.sort((n,r)=>{const i=eT(n,t),s=eT(r,t);return i>s?1:i<s?-1:tT(n,t)-tT(r,t)})}function eT(e,t){if(!$_(e,t)){const n=e.priority;if(typeof n=="string")return{stat:4,asap:3,urgent:2}[n]??0}return 0}function tT(e,t){var r;if(!$_(e,t)){if(e.resourceType==="Communication"&&e.sent)return new Date(e.sent).getTime();if((e.resourceType==="DiagnosticReport"||e.resourceType==="Media"||e.resourceType==="Observation")&&e.issued)return new Date(e.issued).getTime();if(e.resourceType==="DocumentReference"&&e.date)return new Date(e.date).getTime()}const n=(r=e.meta)==null?void 0:r.lastUpdated;return n?new Date(n).getTime():0}function $_(e,t){return!!t&&e.resourceType===t.resourceType&&e.id===t.id}const wG="_pinnedComment_u08s5_1",jG={pinnedComment:wG};function sm(e){const t=_e(),n=t.getProfile(),r=v.useRef(null),i=Qt(e.value),[s,c]=v.useState(),[u,f]=v.useState([]),h=e.loadTimelineResources,m=v.useRef(u);m.current=u;const g=v.useCallback(R=>{z_(R,i),R.reverse(),f(R)},[i]),y=v.useCallback(R=>{const A=[];for(const k of R){if(k.status!=="fulfilled")continue;const M=k.value;if(M.type==="history"&&c(M),M.entry)for(const I of M.entry)A.push(I.resource)}g(A)},[g]),b=v.useCallback(R=>g([...m.current,R]),[g]),S=v.useCallback(()=>{var k;let R,A;"resourceType"in e.value?(R=e.value.resourceType,A=e.value.id):[R,A]=(k=e.value.reference)==null?void 0:k.split("/"),h(t,R,A).then(y).catch(console.error)},[t,e.value,h,y]);v.useEffect(()=>S(),[S]);function j(R){!i||!e.createCommunication||t.createResource(e.createCommunication(i,n,R)).then(A=>b(A)).catch(console.error)}function C(R){!i||!e.createMedia||t.createResource(e.createMedia(i,n,R)).then(A=>b(A)).then(()=>As({id:"upload-notification",color:"teal",title:"Upload complete",message:"",icon:o.jsx(eo,{size:16}),autoClose:2e3})).catch(A=>As({id:"upload-notification",color:"red",title:"Upload error",message:Ye(A),icon:o.jsx(OE,{size:16}),autoClose:2e3}))}function T(){Oe({id:"upload-notification",loading:!0,title:"Initializing upload...",message:"Please wait...",autoClose:!1,withCloseButton:!1})}function D(R){As({id:"upload-notification",loading:!0,title:"Uploading...",message:_G(R),autoClose:!1,withCloseButton:!1})}function E(R){As({id:"upload-notification",color:"red",title:"Upload error",message:Ye(R),icon:o.jsx(OE,{size:16}),autoClose:2e3})}return i?o.jsxs(SG,{children:[e.createCommunication&&o.jsx(rm,{children:o.jsx(pt,{testid:"timeline-form",onSubmit:R=>{j(R.text);const A=r.current;A&&(A.value="",A.focus())},children:o.jsxs(Ce,{gap:"xs",wrap:"nowrap",style:{width:"100%"},children:[o.jsx(Xo,{value:n}),o.jsx(ze,{name:"text",ref:r,placeholder:"Add comment",style:{width:"100%",maxWidth:300}}),o.jsx(_n,{type:"submit",radius:"xl",color:"blue",variant:"filled",children:o.jsx(lF,{size:16})}),o.jsx(Eb,{securityContext:on(i),onUpload:C,onUploadStart:T,onUploadProgress:D,onUploadError:E,children:R=>o.jsx(_n,{...R,radius:"xl",color:"blue",variant:"filled",children:o.jsx(gb,{size:16})})})]})})}),u.map(R=>{var M;if(!R)return null;const A=`${R.resourceType}/${R.id}/${(M=R.meta)==null?void 0:M.versionId}`,k=e.getMenu?e.getMenu({primaryResource:i,currentResource:R,reloadTimeline:S}):void 0;if(R.resourceType===i.resourceType&&R.id===i.id)return o.jsx(CG,{history:s,resource:R,popupMenuItems:k},A);switch(R.resourceType){case"AuditEvent":return o.jsx(DG,{resource:R,popupMenuItems:k},A);case"Communication":return o.jsx(TG,{resource:R,popupMenuItems:k},A);case"DiagnosticReport":return o.jsx(AG,{resource:R,popupMenuItems:k},A);case"Media":return o.jsx(RG,{resource:R,popupMenuItems:k},A);default:return o.jsx(Gs,{resource:R,padding:!0,children:o.jsx(Nb,{value:R,ignoreMissingValues:!0})},A)}})]}):o.jsx(er,{style:{width:"100%",height:"100%"},children:o.jsx(_r,{})})}function CG(e){const{history:t,resource:n,...r}=e,i=EG(t,n);return i?o.jsx(Gs,{resource:n,padding:!0,...r,children:o.jsx(pG,{original:i,revised:e.resource})}):o.jsxs(Gs,{resource:n,padding:!0,...r,children:[o.jsx("h3",{children:"Created"}),o.jsx(Nb,{value:n,ignoreMissingValues:!0,forceUseInput:!0})]})}function EG(e,t){const n=e.entry??[],r=n.findIndex(i=>{var s,c,u;return((c=(s=i.resource)==null?void 0:s.meta)==null?void 0:c.versionId)===((u=t.meta)==null?void 0:u.versionId)});if(!(r>=n.length-1))return n[r+1].resource}function TG(e){var r,i;const n=!e.resource.priority||e.resource.priority==="routine"?void 0:jG.pinnedComment;return o.jsx(Gs,{resource:e.resource,profile:e.resource.sender,dateTime:e.resource.sent,padding:!0,className:n,popupMenuItems:e.popupMenuItems,children:o.jsx("p",{children:(i=(r=e.resource.payload)==null?void 0:r[0])==null?void 0:i.contentString})})}function RG(e){var r;const t=(r=e.resource.content)==null?void 0:r.contentType,n=t&&!t.startsWith("image/")&&!t.startsWith("video/")&&t!=="application/pdf";return o.jsx(Gs,{resource:e.resource,padding:!!n,popupMenuItems:e.popupMenuItems,children:o.jsx(Nd,{value:e.resource.content})})}function DG(e){return o.jsx(Gs,{resource:e.resource,padding:!0,popupMenuItems:e.popupMenuItems,children:o.jsx(Yr,{children:o.jsx("pre",{children:e.resource.outcomeDesc})})})}function AG(e){return o.jsx(Gs,{resource:e.resource,padding:!0,popupMenuItems:e.popupMenuItems,children:o.jsx(Pb,{value:e.resource})})}function _G(e){if(e.lengthComputable){const t=100*e.loaded/e.total;return`Uploaded: ${Xv(e.loaded)} / ${Xv(e.total)} ${t.toFixed(2)}%`}return`Uploaded: ${Xv(e.loaded)}`}function Xv(e){if(e===0)return"0.00 B";const t=Math.floor(Math.log(e)/Math.log(1024));return(e/Math.pow(1024,t)).toFixed(2)+" "+" KMGTP".charAt(t)+"B"}function kG(e){const{resource:t,...n}=e;return o.jsx(sm,{value:t,loadTimelineResources:async(r,i,s)=>{const c=`${i}/${s}`;return Promise.allSettled([r.readHistory(i,s),r.search("Task",{_filter:`based-on eq ${c} or focus eq ${c} or subject eq ${c}`,_count:100})])},...n})}function PG(e){const{encounter:t,...n}=e;return o.jsx(sm,{value:t,loadTimelineResources:async(r,i,s)=>Promise.allSettled([r.readHistory("Encounter",s),r.search("Communication","encounter=Encounter/"+s),r.search("Media","encounter=Encounter/"+s)]),createCommunication:(r,i,s)=>({resourceType:"Communication",status:"completed",encounter:on(r),subject:r.subject,sender:on(i),sent:new Date().toISOString(),payload:[{contentString:s}]}),createMedia:(r,i,s)=>({resourceType:"Media",status:"completed",encounter:on(r),subject:r.subject,operator:on(i),issued:new Date().toISOString(),content:s}),...n})}function NG(e){let t;try{t=Oc(e.path,e.resource)}catch(n){return console.warn("FhirPathDisplay:",n),null}if(t.length>1)throw new Error(`Component "path" for "FhirPathDisplay" must resolve to a single element. Received ${t.length} elements [${JSON.stringify(t,null,2)}]`);return o.jsx(Li,{value:t[0]||"",propertyType:e.propertyType})}function OG(e){return o.jsxs($n,{title:"Export",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:e.onCancel,children:[o.jsxs(ce,{display:"flex",style:{justifyContent:"space-between"},children:[e.exportCsv&&o.jsx(nT,{text:"CSV",exportLogic:e.exportCsv,onCancel:e.onCancel}),e.exportTransactionBundle&&o.jsx(nT,{text:"Transaction Bundle",exportLogic:e.exportTransactionBundle,onCancel:e.onCancel})]}),o.jsx(Ae,{style:{marginTop:"10px",marginLeft:"2px"},children:"Limited to 1000 records"})]})}function nT(e){return o.jsx(Ne,{onClick:()=>{e.exportLogic(),e.onCancel()},children:`Export as ${e.text}`})}const MG={string:[ue.EQUALS,ue.NOT,ue.CONTAINS,ue.EXACT],fulltext:[ue.EQUALS,ue.NOT,ue.CONTAINS,ue.EXACT],token:[ue.EQUALS,ue.NOT],reference:[ue.EQUALS,ue.NOT],numeric:[ue.EQUALS,ue.NOT_EQUALS,ue.GREATER_THAN,ue.LESS_THAN,ue.GREATER_THAN_OR_EQUALS,ue.LESS_THAN_OR_EQUALS],quantity:[ue.EQUALS,ue.NOT_EQUALS,ue.GREATER_THAN,ue.LESS_THAN,ue.GREATER_THAN_OR_EQUALS,ue.LESS_THAN_OR_EQUALS],date:[ue.EQUALS,ue.NOT_EQUALS,ue.GREATER_THAN,ue.LESS_THAN,ue.GREATER_THAN_OR_EQUALS,ue.LESS_THAN_OR_EQUALS,ue.STARTS_AFTER,ue.ENDS_BEFORE,ue.APPROXIMATELY],datetime:[ue.EQUALS,ue.NOT_EQUALS,ue.GREATER_THAN,ue.LESS_THAN,ue.GREATER_THAN_OR_EQUALS,ue.LESS_THAN_OR_EQUALS,ue.STARTS_AFTER,ue.ENDS_BEFORE,ue.APPROXIMATELY],uri:[ue.EQUALS,ue.NOT,ue.ABOVE,ue.BELOW]},IG={eq:"equals",ne:"not equals",gt:"greater than",lt:"less than",ge:"greater than or equals",le:"less than or equals",sa:"starts after",eb:"ends before",ap:"approximately",sw:"starts with",contains:"contains",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"};function Ob(e,t){return{...e,filters:t,offset:0,name:void 0}}function U_(e,t){return Ob(e,(e.filters??[]).filter(n=>n.code!==t))}function lm(e,t,n,r,i){const s=[];return e.filters&&s.push(...e.filters),s.push({code:t,operator:n,value:r??""}),Ob(e,s)}function LG(e,t){if(!e.filters)return e;const n=[...e.filters];return n.splice(t,1),{...e,filters:n,name:void 0}}function zG(e,t){return Mb(e,t,-1)}function $G(e,t){return Mb(e,t,0)}function UG(e,t){return Mb(e,t,1)}function Mb(e,t,n){const r=new Date;r.setDate(r.getDate()+n),r.setHours(0,0,0,0);const i=new Date(r.getTime());return i.setDate(i.getDate()+1),i.setTime(i.getTime()-1),cm(e,t,r,i)}function BG(e,t){const n=new Date,r=new Date(n.getTime()+24*60*60*1e3);return cm(e,t,n,r)}function VG(e,t){return Ib(e,t,-1)}function FG(e,t){return Ib(e,t,0)}function HG(e,t){return Ib(e,t,1)}function Ib(e,t,n){const r=new Date;r.setMonth(r.getMonth()+n),r.setDate(1),r.setHours(0,0,0,0);const i=new Date(r.getTime());return i.setMonth(i.getMonth()+1),i.setDate(1),i.setHours(0,0,0,0),i.setTime(i.getTime()-1),cm(e,t,r,i)}function qG(e,t){const n=new Date;return n.setMonth(0),n.setDate(1),n.setHours(0,0,0,0),cm(e,t,n,new Date)}function cm(e,t,n,r){return e=U_(e,t),e=rT(e,t,ue.GREATER_THAN_OR_EQUALS,n),e=rT(e,t,ue.LESS_THAN_OR_EQUALS,r),e}function rT(e,t,n,r){return lm(e,t,n,r.toISOString())}function iT(e,t,n=!0){return lm(e,t,ue.MISSING,n.toString())}function GG(e,t){return e.offset===t?e:{...e,offset:t,name:void 0}}function QG(e,t){const n=e.count??Kp,r=(t-1)*n;return GG(e,r)}function WG(e,t,n){return t===YG(e)&&n!==void 0&&n===KG(e)?e:{...e,sortRules:[{code:t,descending:!!n}],name:void 0}}function YG(e){const t=e.sortRules;if(!t||t.length===0)return;const n=t[0].code;return n.startsWith("-")?n.substr(1):n}function KG(e){const t=e.sortRules;return!t||t.length===0?!1:!!t[0].descending}function XG(e){return MG[e.type]}function B_(e){return IG[e]??""}function Qs(e){let t=e;return t.includes(".")&&(t=t.split(".").pop()),t==="versionId"?"Version ID":(t=t.replace("[x]",""),t=t.replace(/([A-Z])/g," $1"),t=t.replace(/[-_]/g," "),t=t.replace(/\s+/g," "),t=t.trim(),t.toLowerCase()==="id"?"ID":t.split(/\s/).map(Hn).join(" "))}function ZG(e,t){var r,i;const n=t.name;return n==="id"?o.jsx(mt,{to:`/${e.resourceType}/${e.id}`,children:e.id}):n==="meta.versionId"?(r=e.meta)==null?void 0:r.versionId:n==="_lastUpdated"?gr((i=e.meta)==null?void 0:i.lastUpdated):t.elementDefinition&&`${e.resourceType}.${t.name}`===t.elementDefinition.path?JG(e,t.elementDefinition):t.searchParams&&t.searchParams.length===1&&t.name===t.searchParams[0].code?eQ(e,t.searchParams[0]):null}function JG(e,t){var s,c,u;const n=((u=(c=(s=t.path)==null?void 0:s.split("."))==null?void 0:c.pop())==null?void 0:u.replaceAll("[x]",""))??"",[r,i]=im({type:e.resourceType,value:e},n);return r?o.jsx(Li,{path:t.path,property:t,propertyType:i,value:r,maxWidth:200,ignoreMissingValues:!0,link:!1}):null}function eQ(e,t){const n=Fs(t.expression,[{type:e.resourceType,value:e}]);return!n||n.length===0?null:o.jsx(o.Fragment,{children:n.map((r,i)=>o.jsx(Li,{propertyType:r.type,value:r.value,maxWidth:200,ignoreMissingValues:!0,link:!1},`${i}-${n.length}`))})}function tQ(e){const t=v.useRef(!1),[n,r]=v.useState({search:JSON.parse(Ii(e.search))}),[i,s]=v.useState(!1);v.useEffect(()=>{r({search:e.search})},[e.search]);const c=v.useMemo(()=>{if(!e.visible)return[];const f=e.search.resourceType,h=fA(f),m=nb(f);return ad(nQ(h,m)).map(g=>({value:g,label:Qs(g)}))},[e.visible,e.search.resourceType]);function u(f){r({search:{...n.search,fields:f}})}return o.jsx($n,{title:"Fields",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:()=>{e.onCancel()},size:"auto",withOverlay:!0,closeOnClickOutside:!1,overlayProps:{onMouseDownCapture:()=>{t.current=i},onClick:()=>{t.current||e.onCancel(),t.current=!1},children:o.jsx("div",{"data-testid":"overlay-child"})},children:o.jsxs(Ge,{children:[o.jsx(Op,{style:{width:550},placeholder:"Select fields to display",data:c,value:n.search.fields??[],onChange:u,onDropdownOpen:()=>s(!0),onDropdownClose:()=>s(!1),maxDropdownHeight:"250px",clearButtonProps:{"aria-label":"Clear selection"},clearable:!0,searchable:!0}),o.jsx(Ce,{justify:"flex-end",children:o.jsx(Ne,{onClick:()=>e.onOk(n.search),children:"OK"})})]})})}function nQ(e,t){const n=[],r=new Set,i=new Set;for(const s of Object.keys(e.elements))n.push(s),r.add(s.toLowerCase()),i.add(Qs(s));if(t)for(const s of Object.keys(t)){const c=Qs(s);!r.has(s)&&!i.has(c)&&(n.push(s),r.add(s),i.add(c))}return n}function V_(e){const t=Mc(e.resourceType,e.searchParam),n=e.name??"filter-value";switch(t.type){case Jn.REFERENCE:return o.jsx(Md,{name:n,defaultValue:e.defaultValue?{reference:e.defaultValue}:void 0,targetTypes:e.searchParam.target,autoFocus:e.autoFocus,onChange:r=>{r?e.onChange(r.reference):e.onChange("")}});case Jn.BOOLEAN:return o.jsx(Fn,{name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultChecked:e.defaultValue==="true",autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.checked.toString())});case Jn.DATE:return o.jsx(ze,{type:"date",name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value)});case Jn.DATETIME:return o.jsx(aa,{name:n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:e.onChange});case Jn.NUMBER:return o.jsx(ze,{type:"number",name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value)});case Jn.QUANTITY:return o.jsx(qs,{name:n,path:"",defaultValue:rQ(e.defaultValue),autoFocus:e.autoFocus,onChange:r=>{r?e.onChange(`${r.value}`):e.onChange("")}});default:return o.jsx(ze,{name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value),placeholder:"Search value"})}}function rQ(e){if(e){const[t,n,r]=e.split("|");if(t)return{value:parseFloat(t),system:n,unit:r}}}function iQ(e){const[t,n]=v.useState(Qr(e.search)),r=v.useRef(t);r.current=t,v.useEffect(()=>{n(Qr(e.search))},[e.search]);function i(f){n(lm(r.current,f.code,f.operator,f.value))}const s=e.search.resourceType,c=nb(s)??{},u=t.filters||[];return o.jsx($n,{title:"Filters",closeButtonProps:{"aria-label":"Close"},size:900,opened:e.visible,onClose:e.onCancel,children:o.jsxs(pt,{onSubmit:()=>e.onOk(r.current),children:[o.jsxs("div",{children:[o.jsxs("table",{children:[o.jsxs("colgroup",{children:[o.jsx("col",{style:{width:200}}),o.jsx("col",{style:{width:200}}),o.jsx("col",{style:{width:380}}),o.jsx("col",{style:{width:40}})]}),o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Field"}),o.jsx("th",{children:"Operation"}),o.jsx("th",{children:"Value"}),o.jsx("th",{})]})}),o.jsx("tbody",{children:u.map((f,h)=>o.jsx(aQ,{id:`filter-${h}-row`,resourceType:s,searchParams:c,value:f,onChange:m=>{const g=[...u];g[h]=m,n(Ob(r.current,g))},onDelete:()=>n(LG(r.current,h))},`filter-${h}-row`))})]}),o.jsx(Ab,{propertyDisplayName:"Filter",onClick:()=>i({})})]}),o.jsx(Ce,{justify:"flex-end",mt:"xl",children:o.jsx(Or,{children:"OK"})})]})})}function aQ(e){const t=e.value,n=v.useRef(t);n.current=t;function r(f){n.current.code=f,n.current.operator=ue.EQUALS,n.current.value="",e.onChange(n.current)}function i(f){n.current.operator=f,n.current.value="",e.onChange(n.current)}function s(f){n.current.value=f,e.onChange(n.current)}const c=e.searchParams[t.code],u=c&&XG(c);return o.jsxs("tr",{children:[o.jsx("td",{children:o.jsx(ln,{"data-testid":`${e.id}-filter-field`,defaultValue:e.value.code,onChange:f=>r(f.currentTarget.value),data:["",...Object.keys(e.searchParams).map(f=>({value:f,label:Qs(f)}))]})}),o.jsx("td",{children:u&&o.jsx(ln,{"data-testid":`${e.id}-filter-operation`,defaultValue:t.operator,onChange:f=>i(f.currentTarget.value),data:["",...u.map(f=>({value:f,label:B_(f)}))]},`${e.id}-filter-value-${e.value.code}`)}),o.jsx("td",{children:c&&t.operator&&o.jsx(V_,{name:`${e.id}-filter-value`,resourceType:e.resourceType,searchParam:c,defaultValue:t.value,onChange:s},`${e.id}-filter-value-${e.value.code}-${e.value.operator}`)}),o.jsx("td",{children:e.onDelete&&o.jsx(_n,{variant:"outline",color:"red",radius:"xl","aria-label":"Delete filter",onClick:e.onDelete,children:o.jsx(Hs,{style:{width:"70%",height:"70%"},stroke:1.5})})})]})}function oQ(e){const[t,n]=v.useState(e.defaultValue??"");if(!e.searchParam||!e.filter)return null;function r(){e.onOk({...e.filter,value:t})}return o.jsx($n,{title:e.title,size:"xl",opened:e.visible,onClose:e.onCancel,children:o.jsx(pt,{onSubmit:r,children:o.jsxs(or,{children:[o.jsx(or.Col,{span:10,children:o.jsx(V_,{resourceType:e.resourceType,searchParam:e.searchParam,defaultValue:t,autoFocus:!0,onChange:n})}),o.jsx(or.Col,{span:2,children:o.jsx(Ne,{onClick:r,fullWidth:!0,children:"OK"})})]})})})}function sQ(e){var i;const{resourceType:t,filter:n}=e,r=(i=la.types[t].searchParams)==null?void 0:i[n.code];if(r){if(r.type==="reference"&&(n.operator===ue.EQUALS||n.operator===ue.NOT_EQUALS))return o.jsx(Lc,{value:{reference:n.value}});const s=Mc(t,r);if(n.code==="_lastUpdated"||s.type===Jn.DATETIME)return o.jsx(o.Fragment,{children:gr(n.value)})}return o.jsx(o.Fragment,{children:n.value})}function lQ(e){if(!e.searchParams)return null;function t(s,c){i(WG(e.search,s.code,c))}function n(s){i(U_(e.search,s.code))}function r(s,c){e.onPrompt(s,{code:s.code,operator:c,value:""})}function i(s){e.onChange(s)}return e.searchParams.length===1?o.jsx(cQ,{search:e.search,searchParam:e.searchParams[0],onSort:t,onPrompt:r,onChange:i,onClear:n}):o.jsx(je.Dropdown,{children:e.searchParams.map(s=>o.jsx(je.Item,{children:Qs(s.code)},s.code))})}function cQ(e){switch(e.searchParam.type){case"date":return o.jsx(uQ,{...e});case"number":case"quantity":return o.jsx(dQ,{...e});case"reference":return o.jsx(fQ,{...e});case"string":return o.jsx(hQ,{...e});case"token":case"uri":return o.jsx(pQ,{...e});default:return o.jsxs(o.Fragment,{children:["Unknown search param type: ",e.searchParam.type]})}}function uQ(e){const{searchParam:t}=e,n=t.code;return o.jsxs(je.Dropdown,{children:[o.jsx(je.Item,{leftSection:o.jsx(vb,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort Oldest to Newest"}),o.jsx(je.Item,{leftSection:o.jsx(yb,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Newest to Oldest"}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Pd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),o.jsx(je.Item,{leftSection:o.jsx(kd,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT_EQUALS),children:"Does not equal..."}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(n_,{size:14}),onClick:()=>e.onPrompt(t,ue.ENDS_BEFORE),children:"Before..."}),o.jsx(je.Item,{leftSection:o.jsx(t_,{size:14}),onClick:()=>e.onPrompt(t,ue.STARTS_AFTER),children:"After..."}),o.jsx(je.Item,{leftSection:o.jsx(HV,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Between..."}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(UG(e.search,n)),children:"Tomorrow"}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange($G(e.search,n)),children:"Today"}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(zG(e.search,n)),children:"Yesterday"}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(BG(e.search,n)),children:"Next 24 Hours"}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(HG(e.search,n)),children:"Next Month"}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(FG(e.search,n)),children:"This Month"}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(VG(e.search,n)),children:"Last Month"}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Po,{size:14}),onClick:()=>e.onChange(qG(e.search,n)),children:"Year to date"}),o.jsx(Ld,{...e})]})}function dQ(e){const{searchParam:t}=e;return o.jsxs(je.Dropdown,{children:[o.jsx(je.Item,{leftSection:o.jsx(vb,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort Smallest to Largest"}),o.jsx(je.Item,{leftSection:o.jsx(yb,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Largest to Smallest"}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Pd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),o.jsx(je.Item,{leftSection:o.jsx(kd,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT_EQUALS),children:"Does not equal..."}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(t_,{size:14}),onClick:()=>e.onPrompt(t,ue.GREATER_THAN),children:"Greater than..."}),o.jsx(je.Item,{leftSection:o.jsx(Vy,{size:14}),onClick:()=>e.onPrompt(t,ue.GREATER_THAN_OR_EQUALS),children:"Greater than or equal to..."}),o.jsx(je.Item,{leftSection:o.jsx(n_,{size:14}),onClick:()=>e.onPrompt(t,ue.LESS_THAN),children:"Less than..."}),o.jsx(je.Item,{leftSection:o.jsx(Vy,{size:14}),onClick:()=>e.onPrompt(t,ue.LESS_THAN_OR_EQUALS),children:"Less than or equal to..."}),o.jsx(Ld,{...e})]})}function fQ(e){const{searchParam:t}=e;return o.jsxs(je.Dropdown,{children:[o.jsx(je.Item,{leftSection:o.jsx(Pd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),o.jsx(je.Item,{leftSection:o.jsx(kd,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT),children:"Does not equal..."}),o.jsx(Ld,{...e})]})}function hQ(e){const{searchParam:t}=e;return o.jsxs(je.Dropdown,{children:[o.jsx(je.Item,{leftSection:o.jsx(vb,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort A to Z"}),o.jsx(je.Item,{leftSection:o.jsx(yb,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Z to A"}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Pd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),o.jsx(je.Item,{leftSection:o.jsx(kd,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT),children:"Does not equal..."}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(QV,{size:14}),onClick:()=>e.onPrompt(t,ue.CONTAINS),children:"Contains..."}),o.jsx(je.Item,{leftSection:o.jsx(GV,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Does not contain..."}),o.jsx(Ld,{...e})]})}function pQ(e){const{searchParam:t}=e;return o.jsxs(je.Dropdown,{children:[o.jsx(je.Item,{leftSection:o.jsx(Pd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),o.jsx(je.Item,{leftSection:o.jsx(kd,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT),children:"Does not equal..."}),o.jsx(Ld,{...e})]})}function Ld(e){const{searchParam:t}=e,n=t.code;return o.jsxs(o.Fragment,{children:[o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(VV,{size:14}),onClick:()=>e.onChange(iT(e.search,n)),children:"Missing"}),o.jsx(je.Item,{leftSection:o.jsx(BV,{size:14}),onClick:()=>e.onChange(iT(e.search,n,!1)),children:"Not missing"}),o.jsx(je.Divider,{}),o.jsx(je.Item,{leftSection:o.jsx(Hs,{size:14}),onClick:()=>e.onClear(t),children:"Clear filters"})]})}const mQ="_root_vlout_1",gQ="_table_vlout_8",vQ="_tr_vlout_12",yQ="_control_vlout_22",xQ="_icon_vlout_31",zu={root:mQ,table:gQ,tr:vQ,control:yQ,icon:xQ};function bQ(e){const t=e.resourceType,n=[];for(const r of e.fields||["id","_lastUpdated"])n.push(SQ(t,r));return n}function SQ(e,t){var i;if(t==="_lastUpdated")return{name:"_lastUpdated",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_lastUpdated",name:"_lastUpdated",type:"date",expression:"Resource.meta.lastUpdated"}]};if(t==="meta.versionId")return{name:"meta.versionId",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_versionId",name:"_versionId",type:"token",expression:"Resource.meta.versionId"}]};const n=Yo(e,t),r=pU(e,t.toLowerCase());if(n&&r)return{name:t,elementDefinition:n,searchParams:[r]};if(n){const s=nb(e);let c;if(s){const u=new RegExp(`${e}\\.${t.replaceAll("[x]","")}([^\\w-]|$)`);c=Object.values(s).filter(f=>!!f.expression&&u.test(f==null?void 0:f.expression)),c.length===0&&(c=void 0)}return{name:t,elementDefinition:n,searchParams:c}}if(r){const s=Mc(e,r);return{name:t,elementDefinition:(i=s.elementDefinitions)==null?void 0:i[0],searchParams:[r]}}return{name:t}}class wQ extends Event{constructor(t){super("change"),this.definition=t}}class jQ extends Event{constructor(t){super("load"),this.response=t}}class Qh extends Event{constructor(t,n){super("click"),this.resource=t,this.browserEvent=n}}function zc(e){var G,Z;const t=_e(),[n,r]=v.useState(),{search:i,onLoad:s}=e,[c,u]=v.useState(i);sa(i,c)||u(i);const[f,h]=v.useState({selected:{},fieldEditorVisible:!1,filterEditorVisible:!1,exportDialogVisible:!1,filterDialogVisible:!1}),m=v.useRef(f);m.current=f;const g=c.total??"accurate",y=v.useCallback(P=>{r(void 0),t.requestSchema(c.resourceType).then(()=>t.search(c.resourceType,Uo({...c,total:g,fields:void 0}),P)).then(L=>{h({...m.current,searchResponse:L}),s&&s(new jQ(L))}).catch(L=>{h({...m.current,searchResponse:void 0}),r(Zt(L))})},[t,c,g,s]),b=v.useCallback(()=>{h({...m.current,searchResponse:void 0}),y({cache:"reload"})},[y]);v.useEffect(()=>{y()},[y]);function S(P,L){P.stopPropagation();const H=P.target.checked,O={...m.current.selected};H?O[L]=!0:delete O[L],h({...m.current,selected:O})}function j(P){P.stopPropagation();const z=P.target.checked,H={},O=m.current.searchResponse;z&&(O!=null&&O.entry)&&O.entry.forEach(U=>{var K;(K=U.resource)!=null&&K.id&&(H[U.resource.id]=!0)}),h({...m.current,selected:H})}function C(){var L,z;const P=m.current;if(!((L=P.searchResponse)!=null&&L.entry)||P.searchResponse.entry.length===0)return!1;for(const H of P.searchResponse.entry)if((z=H.resource)!=null&&z.id&&!P.selected[H.resource.id])return!1;return!0}function T(P){e.onChange&&e.onChange(new wQ(P))}function D(P,L){if(s_(P.target)||P.button===2)return;pn(P);const z=o_(P);!z&&e.onClick&&e.onClick(new Qh(L,P)),z&&e.onAuxClick&&e.onAuxClick(new Qh(L,P))}function E(){return!!(e.onExport??e.onExportCsv??e.onExportTransactionBundle)}if(n)return o.jsx(Kr,{outcome:n});if(!dA(c.resourceType))return o.jsx(er,{style:{width:"100%",height:"100%"},children:o.jsx(_r,{})});const R=e.checkboxesEnabled,A=bQ(c),k=c.resourceType,M=f.searchResponse,I=M==null?void 0:M.entry,$=I==null?void 0:I.map(P=>P.resource),V="subtle",Y="gray",Q=16,J=window.innerWidth<768;return o.jsxs("div",{className:zu.root,"data-testid":"search-control",children:[!e.hideToolbar&&o.jsxs(Ce,{justify:"space-between",mb:"xl",children:[o.jsxs(Ce,{gap:2,children:[o.jsx(Ne,{size:"compact-md",variant:V,color:Y,leftSection:o.jsx(XV,{size:Q}),onClick:()=>h({...m.current,fieldEditorVisible:!0,dialogOpenTime:Date.now()}),children:"Fields"}),o.jsx(Ne,{size:"compact-md",variant:V,color:Y,leftSection:o.jsx(nF,{size:Q}),onClick:()=>h({...m.current,filterEditorVisible:!0,dialogOpenTime:Date.now()}),children:"Filters"}),e.onNew&&o.jsx(Ne,{size:"compact-md",variant:V,color:Y,leftSection:o.jsx(tF,{size:Q}),onClick:e.onNew,children:"New..."}),!J&&E()&&o.jsx(Ne,{size:"compact-md",variant:V,color:Y,leftSection:o.jsx(jF,{size:Q}),onClick:e.onExport?e.onExport:()=>h({...m.current,exportDialogVisible:!0,dialogOpenTime:Date.now()}),children:"Export..."}),!J&&e.onDelete&&o.jsx(Ne,{size:"compact-md",variant:V,color:Y,leftSection:o.jsx(xb,{size:Q}),onClick:()=>e.onDelete(Object.keys(f.selected)),children:"Delete..."}),!J&&e.onBulk&&o.jsx(Ne,{size:"compact-md",variant:V,color:Y,leftSection:o.jsx(FV,{size:Q}),onClick:()=>e.onBulk(Object.keys(f.selected)),children:"Bulk..."})]}),o.jsxs(Ce,{gap:2,children:[M&&o.jsxs(Ae,{size:"xs",c:"dimmed","data-testid":"count-display",children:[F_(c,M).toLocaleString(),"-",DQ(c,M).toLocaleString(),M.total!==void 0&&` of ${c.total==="estimate"?"~":""}${(G=M.total)==null?void 0:G.toLocaleString()}`]}),o.jsx(_n,{variant:V,color:Y,title:"Refresh",onClick:b,children:o.jsx(i_,{size:Q})})]})]}),o.jsxs(ye,{className:zu.table,children:[o.jsxs(ye.Thead,{children:[o.jsxs(ye.Tr,{children:[R&&o.jsx(ye.Th,{children:o.jsx("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:C(),onChange:P=>j(P)})}),A.map(P=>o.jsx(ye.Th,{children:o.jsxs(je,{shadow:"md",width:240,position:"bottom-end",children:[o.jsx(je.Target,{children:o.jsx(tr,{className:zu.control,p:2,children:o.jsxs(Ce,{justify:"space-between",wrap:"nowrap",children:[o.jsx(Ae,{fw:500,children:Qs(P.name)}),o.jsx(er,{className:zu.icon,children:o.jsx(zV,{size:14,stroke:1.5})})]})})}),o.jsx(lQ,{search:c,searchParams:P.searchParams,onPrompt:(L,z)=>{h({...m.current,filterDialogVisible:!0,filterDialogSearchParam:L,filterDialogFilter:z,dialogOpenTime:Date.now()})},onChange:L=>{T(L)}})]})},P.name))]}),!e.hideFilters&&o.jsxs(ye.Tr,{children:[R&&o.jsx(ye.Th,{}),A.map(P=>o.jsx(ye.Th,{children:P.searchParams&&o.jsx(EQ,{resourceType:k,searchParams:P.searchParams,filters:c.filters})},P.name))]})]}),o.jsx(ye.Tbody,{children:$==null?void 0:$.map(P=>P&&o.jsxs(ye.Tr,{className:zu.tr,"data-testid":"search-control-row",onClick:L=>D(L,P),onAuxClick:L=>D(L,P),children:[R&&o.jsx(ye.Td,{children:o.jsx("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${P.id}`,checked:!!f.selected[P.id],onChange:L=>S(L,P.id)})}),A.map(L=>o.jsx(ye.Td,{children:ZG(P,L)},L.name))]},P.id))})]}),!($!=null&&$.length)&&o.jsx(Ic,{children:o.jsx(er,{style:{height:150},children:o.jsx(Ae,{size:"xl",c:"dimmed",children:"No results"})})}),M&&o.jsx(er,{m:"md",p:"md",children:o.jsx($i,{value:TQ(c),total:RQ(c,M),onChange:P=>T(QG(c,P)),getControlProps:P=>{switch(P){case"previous":return{"aria-label":"Previous page"};case"next":return{"aria-label":"Next page"};default:return{}}}})}),o.jsx(tQ,{search:c,visible:m.current.fieldEditorVisible,onOk:P=>{T(P),h({...m.current,fieldEditorVisible:!1})},onCancel:()=>{h({...m.current,fieldEditorVisible:!1})}},`search-field-editor-${f.dialogOpenTime}`),o.jsx(iQ,{search:c,visible:m.current.filterEditorVisible,onOk:P=>{T(P),h({...m.current,filterEditorVisible:!1})},onCancel:()=>{h({...m.current,filterEditorVisible:!1})}},`search-filter-editor-${f.dialogOpenTime}`),o.jsx(OG,{visible:m.current.exportDialogVisible,exportCsv:e.onExportCsv,exportTransactionBundle:e.onExportTransactionBundle,onCancel:()=>{h({...m.current,exportDialogVisible:!1})}},`search-export-dialog-${f.dialogOpenTime}`),o.jsx(oQ,{visible:m.current.filterDialogVisible,title:(Z=f.filterDialogSearchParam)!=null&&Z.code?Qs(f.filterDialogSearchParam.code):"",resourceType:k,searchParam:f.filterDialogSearchParam,filter:f.filterDialogFilter,defaultValue:"",onOk:P=>{T(lm(c,P.code,P.operator,P.value)),h({...m.current,filterDialogVisible:!1})},onCancel:()=>{h({...m.current,filterDialogVisible:!1})}},`search-filter-dialog-${f.dialogOpenTime}`)]})}const CQ=zc;function EQ(e){const t=(e.filters??[]).filter(n=>e.searchParams.find(r=>r.code===n.code));return t.length===0?o.jsx("span",{children:"no filters"}):o.jsx(o.Fragment,{children:t.map(n=>o.jsxs("div",{children:[B_(n.operator)," ",o.jsx(sQ,{resourceType:e.resourceType,filter:n})]},`filter-${n.code}-${n.operator}-${n.value}`))})}function TQ(e){return Math.floor((e.offset??0)/(e.count??Kp))+1}function RQ(e,t){const n=e.count??Kp,r=H_(e,t);return Math.ceil(r/n)}function F_(e,t){return Math.min(H_(e,t),(e.offset??0)+1)}function DQ(e,t){var n;return Math.max(F_(e,t)+(((n=t.entry)==null?void 0:n.length)??0)-1,0)}function H_(e,t){var r,i;let n=t.total;return n===void 0&&(n=(e.offset??0)+(((r=t.entry)==null?void 0:r.length)??0)+((i=t.link)!=null&&i.some(s=>s.relation==="next")?1:0)),n}function AQ(e){const t=_e(),[n,r]=v.useState(!1),[i,s]=v.useState(),{query:c,fields:u}=e,[f,h]=v.useState(),[m,g]=v.useState({}),y=v.useRef(f);y.current=f;const b=v.useRef({});b.current=m,v.useEffect(()=>{s(void 0),t.graphql(c).then(h).catch(E=>s(Zt(E)))},[t,c]);function S(E,R){E.stopPropagation();const k=E.target.checked,M={...b.current};k?M[R]=!0:delete M[R],g(M)}function j(E){var I;E.stopPropagation();const A=E.target.checked,k={},M=(I=y.current)==null?void 0:I.data.ResourceList;A&&M&&M.forEach($=>{$.id&&(k[$.id]=!0)}),g(k)}function C(){var R;const E=(R=y.current)==null?void 0:R.data.ResourceList;if(!E||E.length===0)return!1;for(const A of E)if(A.id&&!b.current[A.id])return!1;return!0}function T(E,R){s_(E.target)||(pn(E),E.button!==1&&e.onClick&&e.onClick(new Qh(R,E)),E.button===1&&e.onAuxClick&&e.onAuxClick(new Qh(R,E)))}if(v.useEffect(()=>{t.requestSchema(e.resourceType).then(()=>r(!0)).catch(console.log)},[t,e.resourceType]),!n)return o.jsx(_r,{});const D=e.checkboxesEnabled;return o.jsxs("div",{onContextMenu:E=>pn(E),"data-testid":"search-control",children:[o.jsxs(ye,{children:[o.jsx(ye.Thead,{children:o.jsxs(ye.Tr,{children:[D&&o.jsx(ye.Th,{children:o.jsx("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:C(),onChange:E=>j(E)})}),u.map(E=>o.jsx(ye.Th,{children:E.name},E.name))]})}),o.jsx(ye.Tbody,{children:f==null?void 0:f.data.ResourceList.map(E=>E&&o.jsxs(ye.Tr,{"data-testid":"search-control-row",onClick:R=>T(R,E),onAuxClick:R=>T(R,E),children:[D&&o.jsx(ye.Td,{children:o.jsx("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${E.id}`,checked:!!m[E.id],onChange:R=>S(R,E.id)})}),u.map(R=>o.jsx(ye.Td,{children:o.jsx(NG,{propertyType:R.propertyType,path:R.fhirPath,resource:E})},R.name))]},E.id))})]}),(f==null?void 0:f.data.ResourceList.length)===0&&o.jsx("div",{"data-testid":"empty-search",children:"No results"}),i&&o.jsx("div",{"data-testid":"search-error",children:o.jsx("pre",{style:{textAlign:"left"},children:JSON.stringify(i,void 0,2)})}),e.onBulk&&o.jsx(Ne,{onClick:()=>e.onBulk(Object.keys(b.current)),children:"Bulk..."})]})}const _Q=v.memo(AQ),kQ="_root_1fbwr_1",PQ="_entry_1fbwr_8",NQ="_key_1fbwr_13",OQ="_value_1fbwr_20",um={root:kQ,entry:PQ,key:NQ,value:OQ};function ht(e){return o.jsx(Yr,{children:o.jsx("div",{className:um.root,children:e.children})})}ht.Entry=function(t){return o.jsx("div",{className:um.entry,children:t.children})};ht.Key=function(t){return o.jsx("div",{className:um.key,children:t.children})};ht.Value=function(t){return o.jsx("div",{className:um.value,children:t.children})};function MQ(e){const{group:t}=e;return o.jsx(mr,{withBorder:!0,radius:"md",p:"xs",display:"flex",style:{alignItems:"center",justifyContent:"center"},children:o.jsxs(Ce,{children:[t.measureScore&&o.jsx(zQ,{group:t}),!t.measureScore&&o.jsx(LQ,{group:t})]})})}function IQ(e){const{measure:t}=e;return o.jsxs(o.Fragment,{children:[o.jsx(Ae,{fz:"md",fw:500,mb:8,children:t.title}),o.jsx(Ae,{fz:"xs",c:"dimmed",mb:8,children:t.subtitle})]})}function LQ(e){const{group:t}=e,n=t.population,r=n==null?void 0:n.find(f=>Fo(f.code)==="numerator"),i=n==null?void 0:n.find(f=>Fo(f.code)==="denominator"),s=r==null?void 0:r.count,c=i==null?void 0:i.count;if(c===0)return o.jsxs(ce,{children:[o.jsx(Le,{order:3,children:"Not Applicable"}),o.jsx(Ae,{children:`Denominator: ${c}`})]});if(s===void 0||c===void 0)return o.jsxs(ce,{children:[o.jsx(Le,{order:3,children:"Insufficient Data"}),o.jsx(Ae,{children:`Numerator: ${s}`}),o.jsx(Ae,{children:`Denominator: ${c}`})]});const u=s/c*100;return o.jsx(Vp,{size:120,thickness:12,roundCaps:!0,sections:[{value:u,color:q_(u)}],label:o.jsx(Vo,{justify:"center",children:o.jsxs(Ae,{fw:700,fz:18,children:[s," / ",c]})})})}function zQ(e){var r,i,s;const{group:t}=e,n=((r=t.measureScore)==null?void 0:r.unit)??((i=t.measureScore)==null?void 0:i.code);return o.jsx(o.Fragment,{children:n==="%"?o.jsx(Vp,{size:120,thickness:12,roundCaps:!0,sections:[{value:$Q(t),color:q_(((s=t==null?void 0:t.measureScore)==null?void 0:s.value)??0)}],label:o.jsx(Vo,{justify:"center",children:o.jsx(Ae,{fw:700,fz:18,children:o.jsx(cd,{value:t.measureScore})})})}):o.jsx(Vo,{h:120,align:"center",children:o.jsx(Le,{order:3,children:o.jsx(cd,{value:t.measureScore})})})})}function $Q(e){var r,i;const t=(r=e.measureScore)==null?void 0:r.value,n=(i=e.measureScore)==null?void 0:i.unit;return t?t<=1&&n==="%"?t*100:t:0}function q_(e){return e<=33?"red":e<=67?"yellow":"green"}function UQ(e){var r;const t=Qt(e.measureReport),[n]=kV("Measure",{url:t==null?void 0:t.measure});return t?o.jsxs(ce,{children:[n&&o.jsx(IQ,{measure:n}),o.jsx(I0,{cols:{base:3,sm:1},spacing:{base:"md",sm:"sm"},children:(r=t.group)==null?void 0:r.map((i,s)=>o.jsx(MQ,{group:i},i.id??s))})]}):null}const Zv="patient-export",Jv="Patient Export",BQ={everything:{operation:"$everything",extension:"json",contentType:hn.FHIR_JSON},summary:{operation:"$summary",extension:"json",contentType:hn.FHIR_JSON},ccda:{operation:"$ccda-export",extension:"xml",contentType:hn.CDA_XML},ccdaReferral:{operation:"$ccda-export",type:"referral",extension:"xml",contentType:hn.CDA_XML}};function VQ(e){const t=_e(),{patient:n}=e,r=v.useCallback(async i=>{const s=Bs(n),c=i.format,{operation:u,type:f,contentType:h,extension:m}=BQ[c],g=t.fhirUrl("Patient",s,u),y={};f&&(y.type=f),i.author&&(y.author={reference:i.author}),i.authoredOn&&(y.authoredOn=Rb(i.authoredOn)),i.startDate&&(y.start=i.startDate),i.endDate&&(y.end=i.endDate),di.show({id:Zv,title:Jv,loading:!0,message:"Exporting...",autoClose:!1,withCloseButton:!1});try{const b=await t.post(g,y,void 0,{cache:"no-cache",headers:{Accept:h}}),S=`Patient-export-${s}-${new Date().toISOString().replaceAll(":","-")}.${m}`;FQ(b,S,h),di.update({id:Zv,title:Jv,color:"green",message:"Done",icon:o.jsx(eo,{size:"1rem"}),loading:!1,autoClose:!0,withCloseButton:!0})}catch(b){di.update({id:Zv,title:Jv,color:"red",message:Ye(b),icon:o.jsx(Hs,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}},[t,n]);return o.jsx(pt,{onSubmit:r,children:o.jsxs(Ge,{children:[o.jsx($t,{title:"Export Format",description:"Required",withAsterisk:!0,children:o.jsx(Fp,{name:"format",data:[{label:"FHIR Everything",value:"everything"},{label:"Patient Summary",value:"summary"},{label:"C-CDA",value:"ccda"},{label:"C-CDA Referral",value:"ccdaReferral"}],fullWidth:!0})}),o.jsx($t,{title:"Author",description:"Optional author for composition. Default value is current user.",children:o.jsx(Md,{name:"author",placeholder:"Author",targetTypes:["Organization","Practitioner","PractitionerRole"]})}),o.jsx($t,{title:"Authored On",description:"Optional date for composition authored on. Default value is current date.",children:o.jsx(aa,{name:"authoredOn",placeholder:"Authored on"})}),o.jsx($t,{title:"Start Date",description:"The start date of care. If no start date is provided, all records prior to the end date are in scope.",children:o.jsx(aa,{name:"startDate",placeholder:"Start date"})}),o.jsx($t,{title:"End Date",description:"The end date of care. If no end date is provided, all records subsequent to the start date are in scope.",children:o.jsx(aa,{name:"endDate",placeholder:"End date"})}),o.jsx(Ce,{justify:"right",children:o.jsx(Or,{children:"Request Export"})})]})})}function FQ(e,t,n){const r=typeof e=="string"?e:JSON.stringify(e,null,2),i=new Blob([r],{type:n}),s=window.URL.createObjectURL(i),c=document.createElement("a");document.body.appendChild(c),c.style.display="none",c.href=s,c.download=t,c.click(),window.URL.revokeObjectURL(s)}function HQ(e){if(e.gender==="male")return"blue";if(e.gender==="female")return"pink"}function G_(e){var n,r;const t=Qt(e.patient);return t?o.jsxs(ht,{children:[o.jsx(Xo,{value:t,size:"lg",color:HQ(t)}),o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Name"}),o.jsx(ht.Value,{children:o.jsx(mt,{to:t,fw:500,children:t.name?o.jsx(bb,{value:t.name[0],options:{use:!1}}):"[blank]"})})]}),t.birthDate&&o.jsxs(o.Fragment,{children:[o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"DoB"}),o.jsx(ht.Value,{children:t.birthDate})]}),o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Age"}),o.jsx(ht.Value,{children:$$(t.birthDate)})]})]}),t.gender&&o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Gender"}),o.jsx(ht.Value,{children:t.gender})]}),t.address&&o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"State"}),o.jsx(ht.Value,{children:(n=t.address[0])==null?void 0:n.state})]}),(r=t.identifier)==null?void 0:r.map(i=>o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:i==null?void 0:i.system}),o.jsx(ht.Value,{children:i==null?void 0:i.value})]},`${i==null?void 0:i.system}-${i==null?void 0:i.value}`))]}):null}function qQ(e){const{patient:t,...n}=e,r=v.useCallback((i,s,c)=>{const u=`${s}/${c}`,f=100;return Promise.allSettled([i.readHistory("Patient",c),i.search("Communication",{subject:u,_count:f}),i.search("Device",{patient:u,_count:f}),i.search("DeviceRequest",{patient:u,_count:f}),i.search("DiagnosticReport",{subject:u,_count:f}),i.search("Media",{subject:u,_count:f}),i.search("ServiceRequest",{subject:u,_count:f}),i.search("Task",{subject:u,_count:f})])},[]);return o.jsx(sm,{value:t,loadTimelineResources:r,createCommunication:(i,s,c)=>({resourceType:"Communication",status:"completed",subject:on(i),sender:on(s),sent:new Date().toISOString(),payload:[{contentString:c}]}),createMedia:(i,s,c)=>({resourceType:"Media",status:"completed",subject:on(i),operator:on(s),issued:new Date().toISOString(),content:c}),...n})}const GQ="_section_pqpwm_1",QQ="_hovering_pqpwm_7",Gy={section:GQ,hovering:QQ};function WQ(e){const t=_e(),n=Qt(e.value),[r,i]=v.useState(!1),[s,c]=v.useState(),[u,f]=v.useState(),[h,m]=v.useState();function g(){f(void 0)}function y(){c(void 0)}const b=v.useRef(h);if(b.current=h,v.useEffect(()=>{t.requestSchema("PlanDefinition").then(()=>i(!0)).catch(console.log)},[t]),v.useEffect(()=>(m(JQ(n??{resourceType:"PlanDefinition",status:"active"})),document.addEventListener("mouseover",g),document.addEventListener("click",y),()=>{document.removeEventListener("mouseover",g),document.removeEventListener("click",y)}),[n]),!r||!h)return null;function S(j,C){m({...b.current,[j]:C})}return o.jsx("div",{children:o.jsxs(pt,{testid:"questionnaire-form",onSubmit:()=>e.onSubmit(h),children:[o.jsx(ze,{label:"Plan Title",py:"md",defaultValue:h.title,onChange:j=>S("title",j.currentTarget.value)}),o.jsx(YQ,{actions:h.action||[],selectedKey:s,setSelectedKey:c,hoverKey:u,setHoverKey:f,onChange:j=>S("action",j)}),o.jsx(Or,{children:"Save"})]})})}function YQ(e){const t=v.useRef(e.actions);t.current=e.actions;function n(s){e.onChange(t.current.map(c=>c.id===s.id?s:c))}function r(s){e.onChange([...t.current,s]),e.setSelectedKey(s.id)}function i(s){e.onChange(t.current.filter(c=>c!==s))}return o.jsxs(Ge,{gap:"md",className:Gy.section,children:[e.actions.map(s=>o.jsx(KQ,{action:s,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,setHoverKey:e.setHoverKey,onChange:n,onRemove:()=>i(s)},s.id)),o.jsx("div",{children:o.jsx(Ne,{variant:"outline",onClick:s=>{pn(s),r({id:Q_()})},children:"Add action"})})]})}function KQ(e){const{action:t}=e,n=ZQ(t);function r(s){s.stopPropagation(),e.setSelectedKey(e.action.id)}function i(s){pn(s),e.setHoverKey(e.action.id)}return o.jsx("div",{onClick:r,onMouseOver:i,onFocus:i,children:o.jsx(XQ,{action:t,actionType:n,onChange:e.onChange,selectedKey:e.selectedKey,hoverKey:e.hoverKey,onRemove:e.onRemove})})}function XQ(e){const{action:t}=e,[n,r]=v.useState(e.actionType),i=e.selectedKey===e.action.id,s=e.hoverKey===e.action.id;function c(f,h){e.onChange({...t,[f]:h})}const u=Ut(Gy.section,{[Gy.hovering]:s&&!i});return o.jsxs(mr,{"data-testid":t.id,className:u,p:0,radius:"sm",withBorder:!0,children:[o.jsxs(Vo,{w:"100%",p:"xs",bg:"gray.0",gap:"md",align:"center",justify:"space-between",children:[o.jsx(ze,{w:"100%",name:`actionTitle-${t.id}`,defaultValue:t.title,placeholder:"Title",onChange:f=>c("title",f.currentTarget.value)}),o.jsx(Qo,{"data-testid":"close-button",onClick:e.onRemove})]}),i&&o.jsxs(Ge,{gap:"xl",p:"md",children:[o.jsx(ce,{children:o.jsx(ze,{label:"Task Description",placeholder:"Enter task description",name:`actionDescription-${t.id}`,defaultValue:t.description,onChange:f=>c("description",f.currentTarget.value)})}),o.jsx(ce,{children:o.jsx(ln,{label:"Type of Action",value:n,onChange:f=>{const h=f.currentTarget.value==="standard"?void 0:f.currentTarget.value;r(h),e.onChange({...e.action,definitionCanonical:h==="standard"?void 0:e.action.definitionCanonical})},data:[{value:"standard",label:"Standard task"},{value:"questionnaire",label:"Task with Questionnaire"},{value:"activitydefinition",label:"Task with Activity Definition"}]})}),n==="questionnaire"&&o.jsxs(Ge,{gap:0,children:[o.jsxs(Ce,{gap:0,mb:"xs",children:[o.jsx(Ae,{fw:600,children:"Select questionnaire"}),o.jsx(Ae,{c:"red",children:"*"})]}),o.jsxs(Ae,{size:"sm",c:"dimmed",mb:"sm",children:["Questionnaire to be shown in the task in Encounter view. You can create new one from"," ",o.jsx(Nt,{href:"/Questionnaire",target:"_blank",c:"blue",children:"questionnaires list"})]}),o.jsx(aT,{resourceType:"Questionnaire",action:t,onChange:e.onChange})]}),n==="activitydefinition"&&o.jsxs(Ge,{gap:0,children:[o.jsxs(Ce,{gap:0,mb:"xs",children:[o.jsx(Ae,{fw:600,children:"Select activity definition"}),o.jsx(Ae,{c:"red",children:"*"})]}),o.jsxs(Ae,{size:"sm",c:"dimmed",mb:"sm",children:["ActivityDefinition.kind resource to be shown in the task in Encounter view. You can create new one from"," ",o.jsx(Nt,{href:"/ActivityDefinition",target:"_blank",c:"blue",children:"activity definitions list"})]}),o.jsx(aT,{resourceType:"ActivityDefinition",action:t,onChange:e.onChange})]})]})]})}function aT(e){const{id:t,definitionCanonical:n}=e.action,r=n!=null&&n.startsWith(e.resourceType+"/")?{reference:n}:void 0;return o.jsx(il,{name:t,resourceType:e.resourceType,defaultValue:r,onChange:i=>{i?e.onChange({...e.action,definitionCanonical:zt(i)}):e.onChange({...e.action,definitionCanonical:void 0})}})}function ZQ(e){var t,n;return(t=e.definitionCanonical)!=null&&t.startsWith("Questionnaire")?"questionnaire":(n=e.definitionCanonical)!=null&&n.startsWith("ActivityDefinition")?"activitydefinition":"standard"}let ey=1;function Q_(e){if(e){if(e.startsWith("id-")){const t=parseInt(e.substring(3),10);isNaN(t)||(ey=Math.max(ey,t+1))}return e}return"id-"+ey++}function JQ(e){return{...e,action:W_(e.action)}}function W_(e){if(e)return e.map(t=>({...t,id:Q_(t.id),action:W_(t.action)}))}const _t={group:"group",display:"display",boolean:"boolean",decimal:"decimal",integer:"integer",date:"date",dateTime:"dateTime",time:"time",string:"string",text:"text",url:"url",choice:"choice",openChoice:"open-choice",attachment:"attachment",reference:"reference",quantity:"quantity"};function eW(e){return e.type==="choice"||e.type==="open-choice"}function tW(e,t){var i;const n=Ja(e,Dd+"/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-enableWhenExpression");if(t&&n){const s=(i=n.valueExpression)==null?void 0:i.expression;if(s){const c=mi(t),u=Fs(s,[c],{"%resource":c});return ea(u)}}if(!e.enableWhen)return!0;const r=e.enableBehavior??"any";for(const s of e.enableWhen){const c=K_(t==null?void 0:t.item,s.question);if(s.operator==="exists"&&!s.answerBoolean&&!(c!=null&&c.length)){if(r==="any")return!0;continue}const{anyMatch:u,allMatch:f}=aW(s,c,r);if(r==="any"&&u)return!0;if(r==="all"&&!f)return!1}return r!=="any"}function Lb(e,t){return e.map(n=>{if(n.item)return{...n,item:Lb(n.item,t)};try{const r=rW(n,t);if(!r)return null;const i=nW(n,r);return i?{id:n==null?void 0:n.id,linkId:n==null?void 0:n.linkId,text:n.text,answer:[i]}:null}catch(r){return{id:n==null?void 0:n.id,linkId:n==null?void 0:n.linkId,text:n.text,answer:[],extension:[{url:`${Dd}/fhir/StructureDefinition/questionnaire-validationError`,valueString:`Expression evaluation failed: ${Ye(r)}`}]}}}).filter(n=>n!==null)}function nW(e,t){if(e.type)switch(e.type){case _t.boolean:return t.type===oe.boolean?{valueBoolean:t.value}:void 0;case _t.date:return t.type===oe.date?{valueDate:t.value}:void 0;case _t.dateTime:return t.type===oe.dateTime?{valueDateTime:t.value}:void 0;case _t.time:return t.type===oe.time?{valueTime:t.value}:void 0;case _t.url:return t.type===oe.url?{valueString:t.value}:void 0;case _t.text:return t.type===oe.string?{valueString:t.value}:void 0;case _t.attachment:return t.type===oe.Attachment?{valueAttachment:t.value}:void 0;case _t.reference:return t.type===oe.Reference?{valueReference:t.value}:void 0;case _t.quantity:return{valueQuantity:t.value};case _t.decimal:return{valueDecimal:t.value};case _t.integer:return{valueInteger:t.value};case _t.string:return{valueString:t.value};default:return}}function rW(e,t){var r;if(!t)return;const n=Ja(e,Dd+"/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-calculatedExpression");if(n){const i=(r=n.valueExpression)==null?void 0:r.expression;if(i){const s=mi(t),c=Fs(i,[s],{"%resource":s});return c.length!==0?c[0]:void 0}}}function zb(e,t){return e.map(n=>{const r=t.find(i=>i.linkId===n.linkId);return r?{...n,item:r.item?zb(n.item||[],r.item):n.item,answer:r.answer||n.answer,extension:r.extension||n.extension}:n})}function Y_(e,t,n){var i;const r=[];for(const s of e){const c=(i=n.answerOption)==null?void 0:i.find(u=>vc(ca(u))===s);if(c){const u=ca(c);u&&r.push({[t]:u.value})}}return r}function K_(e,t){if(e)for(const n of e){if(n.linkId===t)return n.answer;if(n.item){const r=K_(n.item,t);if(r)return r}}}function iW(e,t,n){if(n==="exists")return!!e===t.value;if(e){const r=n==="="||n==="!="?n==null?void 0:n.replace("=","~"):n,[{value:i}]=Fs(`%actualAnswer ${r} %expectedAnswer`,[e],{"%actualAnswer":e,"%expectedAnswer":t});return i}else return!1}function aW(e,t,n){const r=t||[],i=dW(e);let s=!1,c=!0;for(const u of r){const f=fW(u),{operator:h}=e;if(iW(f,i,h)?s=!0:c=!1,n==="any"&&s)break}return{anyMatch:s,allMatch:c}}function X_(e){var n,r;const t=Ja(e,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource");if(t){if(t.valueCode!==void 0)return[t.valueCode];if(t.valueCodeableConcept)return(r=(n=t.valueCodeableConcept)==null?void 0:n.coding)==null?void 0:r.map(i=>i.code)}}function ty(e,t){var i;const n=Qr(e);let r=Ja(n,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource");return!t||t.length===0?(r&&(n.extension=(i=n.extension)==null?void 0:i.filter(s=>s!==r)),n):(r||(n.extension||(n.extension=[]),r={url:"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource"},n.extension.push(r)),t.length===1?(r.valueCode=t[0],delete r.valueCodeableConcept):(r.valueCodeableConcept={coding:t.map(s=>({code:s}))},delete r.valueCode),n)}function oW(e,t,n){const r=Ja(e,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceFilter");if(!(r!=null&&r.valueString))return;let i=r.valueString;t!=null&&t.reference&&(i=i.replaceAll("$subj",t.reference)),n!=null&&n.reference&&(i=i.replaceAll("$encounter",n.reference));const s={},c=i.split("&");for(const u of c){const[f,h]=Iy(u,"=",2);s[f]=h}return s}function oT(e,t){return{resourceType:"QuestionnaireResponse",questionnaire:e.url??zt(e),item:Z_(e.item,t==null?void 0:t.item),status:"in-progress"}}function Z_(e,t){return(e==null?void 0:e.map(n=>J_(n,t)))??[]}function J_(e,t){var r;const n=t==null?void 0:t.find(i=>i.linkId===e.linkId);return{id:n?n.id:lW(),linkId:e.linkId,text:e.text,item:Z_(e.item,n==null?void 0:n.item),answer:n?n.answer:((r=e.initial)==null?void 0:r.map(cW))??[]}}let sW=1;function lW(){return"id-"+sW++}function cW(e){return{...e}}function uW(e){var n,r,i,s;const t=(n=e==null?void 0:e.item)==null?void 0:n[0];if(t){const c=Ja(t,"http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl");if(((s=(i=(r=c==null?void 0:c.valueCodeableConcept)==null?void 0:r.coding)==null?void 0:i[0])==null?void 0:s.code)==="page")return e.item.length}return 1}function $b(e){return Ad({value:e},"value")}function ca(e){return Ad({value:e},"value")}function dW(e){return Ad({value:e},"answer")}function fW(e){return Ad({value:e},"value")}const ek=v.createContext({}),Is=30,Wh=50;function Qy(e){const t=v.useContext(ek),n=e.item,r=e.response;function i(g){var b,S,j,C;let y;Array.isArray(g)?y=g:e.index>=(((S=(b=e.response)==null?void 0:b.answer)==null?void 0:S.length)??0)?y=(((j=e.response)==null?void 0:j.answer)??[]).concat([g]):y=(((C=e.response)==null?void 0:C.answer)??[]).map((D,E)=>E===e.index?g:D)??[],e.onChange({id:r==null?void 0:r.id,linkId:r==null?void 0:r.linkId,text:n.text,answer:y})}const s=n.type;if(!s)return null;const c=n.linkId;if(!c)return null;const u=n.initial&&n.initial.length>0?n.initial[0]:void 0,f=Bb(r,e.index)??$b(u),h=Ja(r,`${Dd}/fhir/StructureDefinition/questionnaire-validationError`);let m=null;switch(s){case _t.display:m=o.jsx("p",{children:e.item.text},e.item.linkId);break;case _t.boolean:m=o.jsx(R_,{title:e.item.text,htmlFor:e.item.linkId,children:o.jsx(Fn,{id:e.item.linkId,name:e.item.linkId,defaultChecked:f==null?void 0:f.value,onChange:g=>i({valueBoolean:g.currentTarget.checked})})},e.item.linkId);break;case _t.decimal:m=o.jsx(ze,{type:"number",step:"any",id:c,name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueDecimal:g.currentTarget.value===""?void 0:g.currentTarget.valueAsNumber})});break;case _t.integer:m=o.jsx(ze,{type:"number",step:1,id:c,name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueInteger:g.currentTarget.value===""?void 0:g.currentTarget.valueAsNumber})});break;case _t.date:m=o.jsx(ze,{type:"date",id:c,name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueDate:g.currentTarget.value})});break;case _t.dateTime:m=o.jsx(aa,{name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueDateTime:g})});break;case _t.time:m=o.jsx(ze,{type:"time",id:c,name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueTime:g.currentTarget.value})});break;case _t.string:case _t.url:m=o.jsx(ze,{id:c,name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>{const y=g.currentTarget.value;i({valueString:y===""?void 0:y})}});break;case _t.text:m=o.jsx(Js,{id:c,name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>{const y=g.currentTarget.value;i({valueString:y===""?void 0:y})}});break;case _t.attachment:m=o.jsx(Ce,{py:4,children:o.jsx(d_,{path:"",name:c,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueAttachment:g})})});break;case _t.reference:m=o.jsx(Md,{name:c,required:e.required??n.required,targetTypes:X_(n),searchCriteria:oW(n,t.subject,t.encounter),defaultValue:f==null?void 0:f.value,onChange:g=>i({valueReference:g})});break;case _t.quantity:m=o.jsx(qs,{path:"",name:c,required:e.required??n.required,defaultValue:f==null?void 0:f.value,onChange:g=>i({valueQuantity:g}),disableWheel:!0});break;case _t.choice:case _t.openChoice:xW(n)?m=o.jsx(gW,{name:c,item:n,initial:u,response:r,onChangeAnswer:g=>i(g)}):yW(n)||n.answerValueSet&&!bW(n)?m=o.jsx(hW,{name:c,item:n,initial:u,response:r,onChangeAnswer:g=>i(g)}):m=o.jsx(mW,{name:c,item:n,initial:u,response:r,onChangeAnswer:g=>i(g)});break;default:return null}return o.jsxs(o.Fragment,{children:[m,(h==null?void 0:h.valueString)&&o.jsx(Ae,{c:"red",size:"lg",mt:4,children:h.valueString})]})}function hW(e){var m;const{name:t,item:n,initial:r,onChangeAnswer:i,response:s}=e;if(!((m=n.answerOption)!=null&&m.length)&&!n.answerValueSet)return o.jsx(Ub,{});const c=$b(r),u=Bb(s)??c,f=rk(s),h=n.repeats||SW(n);if(n.answerValueSet)return o.jsx(nm,{name:t,placeholder:"Select items",binding:n.answerValueSet,maxValues:h?void 0:1,onChange:g=>{h?g.length===0?i({}):i(g.map(y=>({valueCoding:y}))):i({valueCoding:g[0]})},defaultValue:u==null?void 0:u.value});if(h){const{propertyName:g,data:y}=wW(n);return o.jsx(Op,{data:y,placeholder:"Select items",searchable:!0,defaultValue:f||[vc(c)],onChange:b=>{if(b.length===0)i({});else{const S=Y_(b,g,n);i(S)}}})}else{const g=[""];if(n.answerOption)for(const y of n.answerOption){const b=ca(y);g.push(vc(b))}return o.jsx(ln,{id:t,name:t,onChange:y=>{const b=y.currentTarget.selectedIndex;if(b===0){i({});return}const S=n.answerOption[b-1],j=ca(S),C="value"+Hn(j.type);i({[C]:j.value})},defaultValue:_d(u==null?void 0:u.value)||(u==null?void 0:u.value),data:g})}}function pW(e,t){return e?t.valueSetExpand({url:e,count:Is+1}).then(n=>{var r;return((r=n.expansion)==null?void 0:r.contains)??[]}):Promise.resolve([])}function tk(e){const t=_e(),[n,r]=v.useState([]),[i,s]=v.useState(!1);return v.useEffect(()=>{async function c(){if(e){s(!0);try{const u=await pW(e,t);r(u)}catch(u){console.error("Error loading value set:",u)}finally{s(!1)}}}c().catch(console.error)},[e,t]),[n,i]}function nk(e,t){return e.map((n,r)=>{const i=`${t}-valueset-${r}`,s={type:"Coding",value:{system:n.system,code:n.code,display:n.display}};return[i,s]})}function mW(e){const{name:t,item:n,initial:r,onChangeAnswer:i,response:s}=e,c=Yo("QuestionnaireItemAnswerOption","value[x]"),u=$b(r),[f,h]=tk(n.answerValueSet),m=[];let g;if(n.answerValueSet)m.push(...nk(f,t));else if(n.answerOption){const j=n.answerOption.slice(0,Wh).map((C,T)=>{const D=`${t}-option-${T}`,E=ca(C);return E!=null&&E.value?(u&&Ii(E)===Ii(u)&&(g=D),[D,E]):null}).filter(C=>C!==null);m.push(...j)}const y=Bb(s),b=vW(m,y);if(h)return o.jsx(Ae,{children:"Loading options..."});if(m.length===0)return o.jsx(Ub,{});const S=m.slice(0,Is);return o.jsxs(o.Fragment,{children:[o.jsx(Us.Group,{name:t,value:b??g,onChange:j=>{const C=m.find(T=>T[0]===j);if(C){const T=C[1],D="value"+Hn(T.type);i({[D]:T.value})}},children:S.map(([j,C])=>o.jsx(Us,{id:j,value:j,py:4,label:o.jsx(Li,{property:c,propertyType:C.type,value:C.value})},j))}),(n.answerValueSet&&m.length>Is||n.answerOption&&m.length>Wh)&&o.jsxs(Ae,{size:"sm",c:"dimmed",mt:"xs",children:["Showing first ",Is," options"]})]})}function gW(e){var S;const{name:t,item:n,onChangeAnswer:r,response:i}=e,s=Yo("QuestionnaireItemAnswerOption","value[x]"),[c,u]=tk(n.answerValueSet),f=n.answerValueSet?(((S=i.answer)==null?void 0:S.map(j=>j.valueCoding))||[]).filter(j=>j!==void 0):rk(i),[h,m]=v.useState(f),g=[];if(n.answerValueSet)g.push(...nk(c,t));else if(n.answerOption){const j=n.answerOption.slice(0,Wh).map((C,T)=>{const D=`${t}-option-${T}`,E=ca(C);return E!=null&&E.value?[D,E]:null}).filter(C=>C!==null);g.push(...j)}if(u)return o.jsx(Ae,{children:"Loading options..."});if(g.length===0)return o.jsx(Ub,{});const y=g.slice(0,Is),b=(j,C)=>{if(n.answerValueSet){const T=h;let D;C?D=[...T,j.value]:D=T.filter(E=>!sa(E,j.value)),m(D),D.length===0?r({}):r(D.map(E=>({valueCoding:E})))}else{const T=h,D=vc(j);let E;if(C?E=[...T,D]:E=T.filter(R=>R!==D),m(E),E.length===0)r({});else{const R=Y_(E,"value"+Hn(j.type),n);r(R)}}};return o.jsxs(Ce,{style:{flexDirection:"column",alignItems:"flex-start"},children:[y.map(([j,C])=>{const T=vc(C),D=n.answerValueSet?h.some(E=>sa(E,C.value)):h.includes(T);return o.jsx(Fn,{id:j,label:o.jsx(Li,{property:s,propertyType:C.type,value:C.value}),checked:D,onChange:E=>b(C,E.currentTarget.checked)},j)}),(n.answerValueSet&&g.length>Is||n.answerOption&&g.length>Wh)&&o.jsxs(Ae,{size:"sm",c:"dimmed",children:["Showing first ",Is," options"]})]})}function Ub(){return o.jsx(ze,{disabled:!0,placeholder:"No Answers Defined"})}function Bb(e,t=0){const n=e.answer;return ca((n==null?void 0:n[t])??{})}function rk(e){const t=e.answer;return t?t.map(r=>ca(r)).map(r=>_d(r==null?void 0:r.value)||(r==null?void 0:r.value)):[]}function vW(e,t){var n;return(n=e.find(r=>sa(r[1].value,t==null?void 0:t.value)))==null?void 0:n[0]}function dm(e,t){var n;return!!((n=e.extension)!=null&&n.some(r=>{var i,s,c;return r.url==="http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl"&&((c=(s=(i=r.valueCodeableConcept)==null?void 0:i.coding)==null?void 0:s[0])==null?void 0:c.code)===t}))}function yW(e){return dm(e,"drop-down")}function xW(e){return dm(e,"check-box")}function bW(e){return dm(e,"radio-button")}function SW(e){return dm(e,"multi-select")}function wW(e){var s;if(((s=e.answerOption)==null?void 0:s.length)===0)return{propertyName:"",data:[]};const t=e.answerOption[0],n=ca(t),r="value"+Hn(n.type),i=(e.answerOption??[]).map(c=>{const u=ca(c),f=vc(u);return{value:f,label:f}});return{propertyName:r,data:i}}const jW="_section_my8o4_1",CW="_hovering_my8o4_10",EW="_editing_my8o4_14",TW="_questionBody_my8o4_20",RW="_topActions_my8o4_24",DW="_bottomActions_my8o4_33",AW="_movementActions_my8o4_44",_W="_movementIcons_my8o4_56",kW="_columnAlignment_my8o4_60",PW="_linkIdInput_my8o4_65",NW="_typeSelect_my8o4_70",OW="_preserveBreaks_my8o4_74",Fr={section:jW,hovering:CW,editing:EW,questionBody:TW,topActions:RW,bottomActions:DW,movementActions:AW,movementIcons:_W,columnAlignment:kW,linkIdInput:PW,typeSelect:NW,preserveBreaks:OW};function MW(e){const t=_e(),n=Qt(e.questionnaire),[r,i]=v.useState(!1),[s,c]=v.useState(),[u,f]=v.useState(),[h,m]=v.useState();function g(){m(void 0)}function y(){f(void 0)}v.useEffect(()=>{t.requestSchema("Questionnaire").then(()=>i(!0)).catch(console.log)},[t]),v.useEffect(()=>(c($W(n??{resourceType:"Questionnaire",status:"active"})),document.addEventListener("mouseover",g),document.addEventListener("click",y),()=>{document.removeEventListener("mouseover",g),document.removeEventListener("click",y)}),[n]);const b=(S,j)=>{c(S),e.autoSave&&!j&&e.onSubmit&&e.onSubmit(S)};return!r||!s?null:o.jsx("div",{children:o.jsxs(pt,{testid:"questionnaire-form",onSubmit:()=>e.onSubmit(s),children:[o.jsx(ik,{item:s,selectedKey:u,setSelectedKey:f,hoverKey:h,setHoverKey:m,onChange:b}),o.jsx(Or,{children:"Save"})]})})}function ik(e){var E;const t=e.item,n=e.item,r=fa(e.item),i=r||n.type===_t.group,s=n.linkId??"[untitled]",c=e.selectedKey===e.item.id,u=e.hoverKey===e.item.id,f=v.useRef(e.item);f.current=e.item;function h(R){pn(R),e.setSelectedKey(e.item.id)}function m(R){pn(R),e.setHoverKey(e.item.id)}function g(R){var k;const A=f.current;e.onChange({...A,item:(k=A.item)==null?void 0:k.map(M=>M.id===R.id?R:M)})}function y(R,A){e.onChange({...e.item,item:[...e.item.item??[],R]},A)}function b(R){var A;e.onChange({...e.item,item:(A=e.item.item)==null?void 0:A.filter(k=>k!==R)})}function S(R,A){e.onChange({...f.current,[R]:A})}function j(R){e.onChange({...e.item,...R})}function C(R){var A;e.onChange({...e.item,item:(A=e.item.item)==null?void 0:A.map(k=>k===R?{...k,repeats:!k.repeats}:k)})}function T(R,A){const k=VW(e.item.item,R,A);e.onChange({...e.item,item:k})}const D=Ut(Fr.section,{[Fr.editing]:c,[Fr.hovering]:u&&!c});return o.jsxs("div",{"data-testid":n.linkId,className:D,onClick:h,onMouseOver:m,onFocus:m,children:[o.jsx("div",{className:Fr.questionBody,children:c?o.jsxs(o.Fragment,{children:[r&&o.jsx(ze,{size:"xl",defaultValue:t.title,onBlur:R=>S("title",R.currentTarget.value)}),!r&&o.jsx(Js,{autosize:!0,minRows:2,defaultValue:n.text,onBlur:R=>S("text",R.currentTarget.value)}),n.type==="reference"&&o.jsx(zW,{item:n,onChange:j}),eW(n)&&o.jsx(IW,{item:n,onChange:R=>j(R)})]}):o.jsxs(o.Fragment,{children:[t.title&&o.jsx(Le,{children:t.title}),n.text&&o.jsx("div",{className:Fr.preserveBreaks,children:n.text}),!i&&o.jsx(Qy,{item:n,index:0,required:!1,onChange:()=>{},response:{linkId:n.linkId}})]})}),(E=n.item)==null?void 0:E.map((R,A)=>o.jsx("div",{children:o.jsx(ik,{item:R,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,isFirst:A===0,isLast:A===(e.item.item??[]).length-1,setHoverKey:e.setHoverKey,onChange:g,onRemove:()=>b(R),onRepeatable:C,onMoveUp:()=>T(A,-1),onMoveDown:()=>T(A,1)})},R.id)),!i&&o.jsx("div",{className:Fr.topActions,children:c?o.jsxs(o.Fragment,{children:[o.jsx(ze,{size:"xs",className:Fr.linkIdInput,defaultValue:n.linkId,onBlur:R=>S("linkId",R.currentTarget.value)}),!i&&o.jsx(ln,{size:"xs",className:Fr.typeSelect,defaultValue:n.type,onChange:R=>S("type",R.currentTarget.value),data:[{value:"display",label:"Display"},{value:"boolean",label:"Boolean"},{value:"decimal",label:"Decimal"},{value:"integer",label:"Integer"},{value:"date",label:"Date"},{value:"dateTime",label:"Date/Time"},{value:"time",label:"Time"},{value:"string",label:"String"},{value:"text",label:"Text"},{value:"url",label:"URL"},{value:"choice",label:"Choice"},{value:"open-choice",label:"Open Choice"},{value:"attachment",label:"Attachment"},{value:"reference",label:"Reference"},{value:"quantity",label:"Quantity"}]})]}):o.jsx("div",{children:s})}),!r&&o.jsx(ce,{className:Fr.movementActions,children:o.jsxs(ce,{className:Fr.columnAlignment,children:[!e.isFirst&&o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),e.onMoveUp&&e.onMoveUp()},children:o.jsx(UV,{"data-testid":"up-button",size:15,className:Fr.movementIcons})}),!e.isLast&&o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),e.onMoveDown&&e.onMoveDown()},children:o.jsx($V,{"data-testid":"down-button",size:15,className:Fr.movementIcons})})]})}),o.jsxs("div",{className:Fr.bottomActions,children:[i&&o.jsxs(o.Fragment,{children:[o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),y({id:Ws(),linkId:Ky("q"),type:"string",text:"Question"})},children:"Add item"}),o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),y({id:Ws(),linkId:Ky("g"),type:"group",text:"Group"},!0)},children:"Add group"})]}),r&&o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),y(BW(),!0)},children:"Add Page"}),c&&!r&&o.jsxs(o.Fragment,{children:[o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),e.onRepeatable&&e.onRepeatable(n)},children:n.repeats?"Remove Repeatable":"Make Repeatable"}),o.jsx(Nt,{href:"#",onClick:R=>{R.preventDefault(),e.onRemove&&e.onRemove()},children:"Remove"})]})]})]})}function IW(e){const t=Yo("QuestionnaireItemAnswerOption","value[x]"),n=e.item.answerOption??[];return o.jsxs("div",{children:[e.item.answerValueSet!==void 0?o.jsx(ze,{placeholder:"Enter Value Set",defaultValue:e.item.answerValueSet,onChange:r=>e.onChange({...e.item,answerValueSet:r.target.value})}):o.jsx(LW,{options:n,property:t,item:e.item,onChange:e.onChange}),o.jsxs(ce,{display:"flex",children:[o.jsx(Nt,{href:"#",onClick:r=>{pn(r),e.onChange({...e.item,answerValueSet:void 0,answerOption:[...n,{id:Ws()}]})},children:"Add choice"}),o.jsx(Hp,{w:"lg"}),o.jsx(Nt,{href:"#",onClick:r=>{pn(r),e.onChange({...e.item,answerOption:[],answerValueSet:""})},children:"Add value set"})]})]})}function LW(e){return o.jsx("div",{children:e.options.map(t=>{const[n,r]=im({type:"QuestionnaireItemAnswerOption",value:t},"value");return o.jsxs("div",{style:{display:"flex",flexDirection:"row",justifyContent:"space-between",alignItems:"center",width:"80%"},children:[o.jsx("div",{children:o.jsx(Id,{name:"value[x]",path:"Questionnaire.answerOption.value[x]",property:e.property,defaultPropertyType:r,defaultValue:n,onChange:(i,s)=>{const c=[...e.options],u=c.findIndex(f=>f.id===t.id);c[u]={id:t.id,[s]:i},e.onChange({...e.item,answerOption:c})},outcome:void 0},t.id)}),o.jsx("div",{children:o.jsx(Nt,{href:"#",onClick:i=>{pn(i),e.onChange({...e.item,answerOption:e.options.filter(s=>s.id!==t.id)})},children:"Remove"})})]},t.id)})})}function zW(e){const t=X_(e.item)??[];return o.jsxs(o.Fragment,{children:[t.map((n,r)=>o.jsxs(Ce,{children:[o.jsx(jb,{name:"resourceType",placeholder:"Resource Type",defaultValue:n,onChange:i=>{e.onChange(ty(e.item,t.map(s=>s===n?i:s)))}}),o.jsx(Nt,{href:"#",onClick:i=>{pn(i),e.onChange(ty(e.item,t.filter(s=>s!==n)))},children:"Remove"})]},`${n}-${r}`)),o.jsx(Nt,{href:"#",onClick:n=>{pn(n),e.onChange(ty(e.item,[...t,""]))},children:"Add Resource Type"})]})}let Wy=1,Yy=1;function Ky(e){return e+Wy++}function Ws(){return"id-"+Yy++}function $W(e){return{...e,id:e.id||Ws(),item:ak(e.item)}}function ak(e){if(e)return e.forEach(t=>{var n,r;(n=t.id)!=null&&n.match(/^id-\d+$/)&&(Yy=Math.max(Yy,parseInt(t.id.substring(3),10)+1)),(r=t.linkId)!=null&&r.match(/^q\d+$/)&&(Wy=Math.max(Wy,parseInt(t.linkId.substring(1),10)+1))}),e.map(t=>({...t,id:t.id||Ws(),item:ak(t.item),answerOption:UW(t.answerOption)}))}function UW(e){if(e)return e.map(t=>({...t,id:t.id||Ws()}))}function BW(){return{id:Ws(),linkId:Ky("s"),type:"group",text:"New Page",extension:[{url:"http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl",valueCodeableConcept:{coding:[{system:"http://hl7.org/fhir/questionnaire-item-control",code:"page"}]}}]}}function VW(e,t,n){const r=e??[],i=t+n;if(i<0||i>=r.length)return r;const s=[...r];return[s[t],s[i]]=[s[i],s[t]],s}function ok(e){const{item:t,response:n,onChange:r}=e,[i,s]=v.useState(FW(t,n??{linkId:t.linkId}));if(!e.checkForQuestionEnabled(t)||!n)return null;if(t.type===_t.display)return o.jsx("p",{children:t.text},t.linkId);const c=(t==null?void 0:t.repeats)&&t.type!==_t.choice&&t.type!==_t.openChoice;return t.type===_t.boolean?o.jsx(Qy,{item:t,response:n,onChange:u=>r([u]),index:0},t.linkId):o.jsxs($t,{htmlFor:e.item.linkId,title:e.item.text,withAsterisk:e.item.required,children:[[...Array(i)].map((u,f)=>o.jsx(Qy,{item:t,response:n,onChange:h=>r([h]),index:f},`${t.linkId}-${f}`)),c&&o.jsx(Nt,{onClick:()=>s(u=>u+1),children:"Add Item"})]},e.item.linkId)}function FW(e,t){if(e.type===_t.choice||e.type===_t.openChoice)return 1;const n=t.answer;return n!=null&&n.length?n.length:1}function sk(e){const[t,n]=v.useState(e.response);if(v.useEffect(()=>{n(e.response)},[e.response]),t.length===0)return null;function r(s,c){const u=t.map((f,h)=>h===c?s[0]:f);n(u),e.onChange(u)}function i(){const s=J_(e.item,void 0);n([...t,s])}return o.jsxs(o.Fragment,{children:[t.map((s,c)=>o.jsx(lk,{item:e.item,response:s,checkForQuestionEnabled:e.checkForQuestionEnabled,onChange:u=>r(u,c)},s.id)),e.item.repeats&&o.jsx(Nt,{onClick:i,children:`Add Group: ${e.item.text}`})]})}function lk(e){var s;const{response:t,checkForQuestionEnabled:n,onChange:r}=e;function i(c){var m;const u=(m=t.item)==null?void 0:m.map(g=>c.find(b=>b.id===g.id)??g),f=u==null?void 0:u.concat(c.slice(1)),h={...t,item:f};r([h])}return e.checkForQuestionEnabled(e.item)?o.jsxs("div",{children:[e.item.text&&o.jsx(Le,{order:3,mb:"md",children:e.item.text}),o.jsx(Ge,{children:(s=e.item.item)==null?void 0:s.map(c=>{var u,f,h;return c.type===_t.group?c.repeats?o.jsx(sk,{item:c,response:((u=t.item)==null?void 0:u.filter(m=>m.linkId===c.linkId))??[],checkForQuestionEnabled:n,onChange:i},c.linkId):o.jsx(lk,{item:c,checkForQuestionEnabled:n,response:((f=t.item)==null?void 0:f.find(m=>m.linkId===c.linkId))??{linkId:c.linkId},onChange:i},c.linkId):o.jsx(ok,{item:c,response:(h=t.item)==null?void 0:h.find(m=>m.linkId===c.linkId),onChange:i,checkForQuestionEnabled:n},c.linkId)})})]},e.item.linkId):null}function HW(e){const{items:t,response:n,activePage:r,onChange:i,nextStep:s,prevStep:c,numberOfPages:u,renderPages:f,submitButtonText:h,excludeButtons:m,checkForQuestionEnabled:g}=e,y=t.map(b=>{var C;const S=((C=n==null?void 0:n.item)==null?void 0:C.filter(T=>T.linkId===b.linkId))??[],j=b.type===_t.group?o.jsx(sk,{item:b,response:S,onChange:i,checkForQuestionEnabled:g},b.linkId):o.jsx(ok,{item:b,response:S==null?void 0:S[0],onChange:i,checkForQuestionEnabled:g},b.linkId);return f?o.jsx(mc.Step,{label:b.text,children:j},b.linkId):j});return o.jsxs(o.Fragment,{children:[f&&o.jsx(mc,{active:r??0,allowNextStepsSelect:!1,p:6,children:y}),!f&&o.jsx(Ge,{children:y}),!m&&o.jsx(qW,{activePage:r??0,numberOfPages:u,nextStep:f?s:void 0,prevStep:f?c:void 0,renderPages:f,submitButtonText:h})]})}function qW(e){const t=e.renderPages&&e.activePage>0,n=e.renderPages&&e.activePage<e.numberOfPages-1,r=!e.renderPages||e.activePage===e.numberOfPages-1;return o.jsxs(Ce,{justify:"flex-end",mt:"xl",gap:"xs",children:[t&&o.jsx(Ne,{onClick:e.prevStep,children:"Back"}),n&&o.jsx(Ne,{onClick:i=>{const s=i.currentTarget.closest("form");e.nextStep&&s.reportValidity()&&e.nextStep()},children:"Next"}),r&&o.jsx(Or,{children:e.submitButtonText??"Submit"})]})}function ck(e){const t=_e(),{subject:n,source:r}=e,i=Qt(e.questionnaire),s=DV(i),c=Qt(e.questionnaireResponse),[u,f]=v.useState(c),[h,m]=v.useState(0),g=v.useRef(e.onChange);g.current=e.onChange;const y=v.useRef(e.onSubmit);y.current=e.onSubmit,v.useEffect(()=>{if(c!=null&&c.item&&i){const E=oT(i,c),R=dk(E,i);f(R)}else{if(i&&sT(s)===sT(i))return;f(i?oT(i):void 0)}},[c,i,s]),v.useEffect(()=>{if(u&&g.current)try{g.current(u)}catch(E){console.error("Error invoking QuestionnaireForm.onChange callback",E)}},[u]);const b=v.useCallback(E=>{f(R=>QW(R,E,i))},[i]),S=v.useCallback(()=>{const E=y.current;if(E&&i&&u){let R=r;if(!R){const A=t.getProfile();A&&(R=on(A))}E({...u,questionnaire:i.url??zt(i),subject:n,source:R,authored:new Date().toISOString(),status:"completed"})}},[t,i,u,n,r]);function j(E){return tW(E,u)}if(!i||!u)return null;const C=uW(i),T=()=>m(E=>E+1),D=()=>m(E=>E-1);return o.jsx(ek.Provider,{value:{subject:e.subject,encounter:e.encounter},children:o.jsxs(pt,{testid:"questionnaire-form",onSubmit:S,children:[i.title&&o.jsx(Le,{children:i.title}),o.jsx(HW,{items:i.item??[],response:u,onChange:b,renderPages:!e.disablePagination&&C>1,activePage:h,numberOfPages:C,excludeButtons:e.excludeButtons,submitButtonText:e.submitButtonText,checkForQuestionEnabled:j,nextStep:T,prevStep:D})]})})}function GW(e,t){const n=uk(e.item??[],t.item??[]);return{...t,item:n.length>0?n:void 0,answer:t.answer&&t.answer.length>0?t.answer:e.answer}}function uk(e,t){const n=[],r=new Set;for(const i of e){const s=i.id,c=t.find(u=>u.id===s);c?(n.push(GW(i,c)),r.add(c.id)):n.push(i)}for(const i of t)r.has(i.id)||n.push(i);return n}function sT(e){return(e==null?void 0:e.id)||e}function QW(e,t,n){if(!t)return{resourceType:"QuestionnaireResponse",status:"in-progress"};const r=(e==null?void 0:e.item)??[],i=uk(r,Array.isArray(t)?t:[t]),s={resourceType:"QuestionnaireResponse",status:"in-progress",item:i},c=Lb((n==null?void 0:n.item)??[],s);return s.item=zb(i,c),dk(s,n)}function dk(e,t){const n=Lb((t==null?void 0:t.item)??[],e);return{resourceType:"QuestionnaireResponse",status:"in-progress",item:zb(e.item??[],n)}}const WW="_section_4m5it_1",YW={section:WW},KW=["gender","age","gestationalAge","context","appliesTo","category"],XW={definition:{resourceType:"ObservationDefinition",code:{text:""}},onSubmit:()=>{}};function ZW(e){e=Object.assign(XW,e);const t=e.definition,[n,r]=v.useState([]),[i,s]=v.useState(1),[c,u]=v.useState(1);return v.useEffect(()=>{const S=tY(t,u);r(nY(S.qualifiedInterval||[],s))},[t]),o.jsxs(pt,{testid:"reference-range-editor",onSubmit:f,children:[o.jsx(Ge,{children:n.map(S=>{var j;return o.jsx(JW,{unit:iY((j=t.quantitativeDetails)==null?void 0:j.unit),onChange:g,onAdd:y,onRemove:b,onRemoveGroup:m,intervalGroup:S},`group-${S.id}`)})}),o.jsx(_n,{title:"Add Group",variant:"subtle",size:"sm",onClick:S=>{pn(S),h({id:`group-id-${i}`,filters:{},intervals:[]}),s(j=>j+1)},children:o.jsx(qh,{})}),o.jsx(Ce,{justify:"flex-end",children:o.jsx(Or,{children:"Save"})})]});function f(){const S=n.flatMap(j=>j.intervals).filter(j=>!aY(j));e.onSubmit({...t,qualifiedInterval:S})}function h(S){r(j=>[...j,S])}function m(S){r(j=>j.filter(C=>C.id!==S.id))}function g(S,j){r(C=>{C=[...C];const T=C.find(E=>E.id===S),D=T==null?void 0:T.intervals.findIndex(E=>E.id===j.id);return D!==void 0&&(T!=null&&T.intervals[D])&&(T.intervals[D]=j),C})}function y(S,j){j.id===void 0&&(j.id=`id-${c}`,u(C=>C+1)),r(C=>{C=[...C];const T=C.findIndex(D=>D.id===S);if(T!==-1){const D={...C[T]};j={...j,...D.filters},D.intervals=[...D.intervals,j],C[T]=D}return C})}function b(S,j){r(C=>{C=[...C];const T=C.find(D=>D.id===S);return T&&(T.intervals=T.intervals.filter(D=>D.id!==j.id)),C})}}function JW(e){const{intervalGroup:t,unit:n}=e;return o.jsx(Ic,{"data-testid":t.id,className:YW.section,children:o.jsxs(Ge,{gap:"lg",children:[o.jsx(Ce,{justify:"flex-end",children:o.jsx(_n,{title:"Remove Group",variant:"subtle","data-testid":`remove-group-button-${t.id}`,size:"sm",onClick:r=>{pn(r),e.onRemoveGroup(t)},children:o.jsx(Hh,{})},`remove-group-button-${t.id}`)}),o.jsx(eY,{intervalGroup:t,onChange:e.onChange}),o.jsx(Cn,{}),t.intervals.map(r=>o.jsxs(Ge,{gap:"xs",children:[o.jsxs(Ce,{children:[o.jsx(ze,{"data-testid":`condition-${r.id}`,defaultValue:r.condition,label:"Condition: ",size:"sm",onChange:i=>{pn(i),e.onChange(t.id,{...r,condition:i.currentTarget.value.trim()})}},`condition-${r.id}`),o.jsx(_n,{title:"Remove Interval",variant:"subtle",size:"sm","data-testid":`remove-interval-${r.id}`,onClick:i=>{pn(i),e.onRemove(t.id,r)},children:o.jsx(Hh,{})},`remove-interval-${r.id}`)]}),o.jsx(Db,{path:"",onChange:i=>{e.onChange(t.id,{...r,range:i})},name:`range-${r.id}`,defaultValue:r.range},`range-${r.id}`)]},`interval-${r.id}`)),o.jsx(_n,{title:"Add Interval",variant:"subtle",size:"sm",onClick:r=>{pn(r),e.onAdd(t.id,{range:{low:{unit:n},high:{unit:n}}})},children:o.jsx(qh,{})})]})})}function eY(e){var r,i;const{intervalGroup:t,onChange:n}=e;t.filters.age||(t.filters.age={});for(const s of["low","high"])(r=t.filters.age[s])!=null&&r.unit||(t.filters.age[s]={...t.filters.age[s],unit:"years",system:"http://unitsofmeasure.org"});return o.jsxs(Ge,{style:{maxWidth:"50%"},children:[o.jsx(Ce,{children:o.jsx(ln,{data:["","male","female"],label:"Gender:",defaultValue:t.filters.gender||"",onChange:s=>{for(const c of t.intervals){let u=s.currentTarget.value;u===""&&(u=void 0),n(t.id,{...c,gender:u})}}})}),o.jsxs(Ce,{gap:"xs",children:[o.jsx(Ae,{component:"label",htmlFor:`div-age-${t.id}`,children:"Age:"}),o.jsx("div",{id:`div-age-${t.id}`,children:o.jsx(Db,{path:"",name:`age-${t.id}`,defaultValue:t.filters.age,onChange:s=>{for(const c of t.intervals)n(t.id,{...c,age:s})}},`age-${t.id}`)})]}),o.jsx(ln,{data:["","pre-puberty","follicular","midcycle","luteal","postmenopausal"],label:"Endocrine:",defaultValue:((i=t.filters.context)==null?void 0:i.text)||"",onChange:s=>{for(const c of t.intervals){let u=s.currentTarget.value;u===""?(u=void 0,n(t.id,{...c,context:void 0})):n(t.id,{...c,context:{text:u,coding:[{code:u,system:"http://terminology.hl7.org/CodeSystem/referencerange-meaning"}]}})}}}),o.jsx(ln,{data:["","reference","critical","absolute"],label:"Category: ",defaultValue:t.filters.category,onChange:s=>{for(const c of t.intervals){const u=s.currentTarget.value;u===""?n(t.id,{...c,category:void 0}):n(t.id,{...c,category:u})}}})]})}function tY(e,t){const n=e.qualifiedInterval||[];let r=Math.max(...n.map(i=>{var c;const s=parseInt(((c=i.id)==null?void 0:c.substring(3))||"",10);return isNaN(s)?Number.NEGATIVE_INFINITY:s}))+1;return Number.isFinite(r)||(r=1),e={...e,qualifiedInterval:n.map(i=>({...i,id:i.id||`id-${r++}`}))},t(r),e}function nY(e,t){let n=1;const r={};for(const i of e){const s=rY(i);s in r||(r[s]={id:`group-id-${n++}`,filters:Object.fromEntries(KW.map(c=>[c,i[c]])),intervals:[]}),r[s].intervals.push(i)}return t(n),Object.values(r)}function rY(e){var n,r;return[`gender=${e.gender}`,`age=${od(e.age)}`,`gestationalAge=${od(e.gestationalAge)}`,`context=${(n=e.context)==null?void 0:n.text}`,`appliesTo=${(r=e.appliesTo)==null?void 0:r.map(i=>i.text).join("+")}`,`category=${e.category}`].join(":")}function iY(e){return e&&(K$(e,"http://unitsofmeasure.org")||e.text)}function aY(e){var t,n,r,i;return((n=(t=e.range)==null?void 0:t.low)==null?void 0:n.value)===void 0&&((i=(r=e.range)==null?void 0:r.high)==null?void 0:i.value)===void 0}function oY(e){var h;const t=_e(),n=Qt(e.value),[r,i]=v.useState(!1),[s,c]=v.useState();if(v.useEffect(()=>{n&&!r&&(t.executeBatch(u(n)).then(c).catch(console.log),i(!0))},[t,n,r]),!n||!s)return null;return o.jsx(or,{children:(h=n.action)==null?void 0:h.map((m,g)=>{var j,C,T,D,E,R;const y=m.resource&&f(m.resource),b=(C=(j=y==null?void 0:y.input)==null?void 0:j[0])==null?void 0:C.valueReference,S=(D=(T=y==null?void 0:y.output)==null?void 0:T[0])==null?void 0:D.valueReference;return o.jsxs(v.Fragment,{children:[o.jsx(or.Col,{span:1,p:"md",children:(y==null?void 0:y.status)==="completed"?o.jsx(YV,{}):o.jsx(bF,{color:"gray"})}),o.jsxs(or.Col,{span:9,p:"xs",children:[o.jsx(Ae,{fw:500,children:m.title}),m.description&&o.jsx("div",{children:m.description}),o.jsxs("div",{children:["Last edited by ",o.jsx(Lc,{value:(E=y==null?void 0:y.meta)==null?void 0:E.author})," on ",gr((R=y==null?void 0:y.meta)==null?void 0:R.lastUpdated)]}),o.jsxs("div",{children:["Status: ",o.jsx(om,{status:(y==null?void 0:y.status)||"unknown"})]})]}),o.jsxs(or.Col,{span:2,p:"md",children:[b&&!S&&o.jsx(Ne,{onClick:()=>e.onStart(y,b),children:"Start"}),b&&S&&o.jsx(Ne,{onClick:()=>e.onEdit(y,b,S),children:"Edit"})]})]},`action-${g}`)})});function u(m){var y;const g=[];if(m.action)for(const b of m.action)(y=b.resource)!=null&&y.reference&&g.push({request:{method:"GET",url:b.resource.reference}});return{resourceType:"Bundle",type:"batch",entry:g}}function f(m){for(const g of(s==null?void 0:s.entry)??[])if(g.resource&&m.reference===zt(g.resource))return g.resource}}function fk(e,t){const n=sY(e,t);return lY(n,e,t)}function sY(e,t){const n=e.length,r=t.length,i=n+r+1,s=1+2*i,c=s/2|0,u=new Array(s);u[c+1]={i:0,j:-1,prev:void 0,snake:!0};for(let f=0;f<i;f++){for(let h=-f;h<=f;h+=2){const m=c+h,g=m+1,y=m-1,b=u[g],S=u[y];let j,C=0;h===-f||h!==f&&S.i<b.i?(C=b.i,j=b):(C=S.i+1,j=S),u[y]=void 0;let T=C-h,D={i:C,j:T,prev:cY(j),snake:!1};for(;C<n&&T<r&&e[C]===t[T];)C++,T++;if(C>D.i&&(D={i:C,j:T,prev:D,snake:!0}),u[m]=D,C>=n&&T>=r)return u[m]}u[c+f-1]=void 0}}function lY(e,t,n){const r=[];let i=e;for(i.snake&&(i=i.prev);i!=null&&i.prev&&i.prev.j>=0;){const s=i.i,c=i.j;i=i.prev;const u=i.i,f=i.j,h={position:u,lines:t.slice(u,s)},m={position:f,lines:n.slice(f,c)};let g;h.lines.length===0&&m.lines.length>0?g="insert":h.lines.length>0&&m.lines.length===0?g="delete":g="change",r.push({original:h,revised:m,type:g}),i.snake&&(i=i.prev)}return r}function cY(e){return e&&!e.snake&&e.prev?e.prev:e}function uY(e){const t=(e.entry??[]).filter(r=>!!r.resource).map(r=>{var i;return{meta:(i=r.resource)==null?void 0:i.meta,lines:Ii(r.resource,!0).match(/[^\r\n]+/g)}}).sort((r,i)=>r.meta.lastUpdated.localeCompare(i.meta.lastUpdated));if(!t.length)return[];const n=t[0].lines.map(r=>({id:t[0].meta.versionId,meta:t[0].meta,value:r,span:1}));return dY(n,t),fY(n),n}function dY(e,t){for(let n=1;n<t.length;n++){const r=fk(t[n-1].lines,t[n].lines);for(const i of r){const s=i.original.position,c=i.original.lines,u=i.revised.lines;if((i.type==="delete"||i.type==="change")&&e.splice(s,c.length),i.type==="insert"||i.type==="change")for(let f=0;f<i.revised.lines.length;f++)e.splice(s+f,0,{id:t[n].meta.versionId,meta:t[n].meta,value:u[f],span:1})}}}function fY(e){let t=0;for(;t<e.length;){let n=t;for(;n<e.length&&e[n].id===e[t].id;)e[n].span=-1,n++;e[t].span=n-t,t=n}}const hY="_container_1oj0p_1",pY="_root_1oj0p_5",mY="_startRow_1oj0p_20",gY="_normalRow_1oj0p_24",vY="_author_1oj0p_28",yY="_dateTime_1oj0p_32",xY="_lineNumber_1oj0p_37",bY="_line_1oj0p_37",SY="_pre_1oj0p_52",Oa={container:hY,root:pY,startRow:mY,normalRow:gY,author:vY,dateTime:yY,lineNumber:xY,line:bY,pre:SY};function wY(e,t){return`/${e.resourceType}/${e.id}/_history/${t}`}function jY(e){const t=Math.floor((Date.now()-Date.parse(e))/1e3),n=Math.floor(t/31536e3);if(n>0)return Zl(n,"year");const r=Math.floor(t/2592e3);if(r>0)return Zl(r,"month");const i=Math.floor(t/86400);if(i>0)return Zl(i,"day");const s=Math.floor(t/3600);if(s>0)return Zl(s,"hour");const c=Math.floor(t/60);return c>0?Zl(c,"minute"):Zl(t,"second")}function Zl(e,t){return`${e} ${e===1?t:t+"s"} ago`}function CY(e){var c,u;const t=_e(),[n,r]=v.useState(e.history);if(v.useEffect(()=>{!e.history&&e.resourceType&&e.id&&t.readHistory(e.resourceType,e.id).then(r).catch(console.log)},[t,e.history,e.resourceType,e.id]),!n)return o.jsx("div",{children:"Loading..."});const i=(u=(c=n.entry)==null?void 0:c[0])==null?void 0:u.resource;if(!i)return null;const s=uY(n);return o.jsx("div",{className:Oa.container,children:o.jsx("table",{className:Oa.root,children:o.jsx("tbody",{children:s.map((f,h)=>o.jsxs("tr",{className:f.span>0?Oa.startRow:Oa.normalRow,children:[f.span>0&&o.jsxs(o.Fragment,{children:[o.jsx("td",{className:Oa.author,rowSpan:f.span,children:o.jsx(oc,{value:f.meta.author,link:!0})}),o.jsx("td",{className:Oa.dateTime,rowSpan:f.span,children:o.jsx(mt,{to:wY(i,f.meta.versionId),children:jY(f.meta.lastUpdated)})})]}),o.jsx("td",{className:Oa.lineNumber,children:h+1}),o.jsx("td",{className:Oa.line,children:o.jsx("pre",{className:Oa.pre,children:f.value})})]},"row-"+h))})})})}const EY="_removed_el5zk_1",TY="_added_el5zk_6",lT={removed:EY,added:TY};function RY(e){let t=e.original,n=e.revised;e.ignoreMeta&&(t={...t,meta:void 0},n={...n,meta:void 0});const r=Ii(t,!0).match(/[^\r\n]+/g),i=Ii(n,!0).match(/[^\r\n]+/g),s=fk(r,i);return o.jsx("pre",{style:{color:"gray"},children:s.map((c,u)=>o.jsx(DY,{delta:c},"delta"+u))})}function DY(e){return o.jsxs(o.Fragment,{children:["...",o.jsx("br",{}),e.delta.original.lines.length>0&&o.jsx("div",{className:lT.removed,children:e.delta.original.lines.join(`
|
|
537
537
|
`)}),e.delta.revised.lines.length>0&&o.jsx("div",{className:lT.added,children:e.delta.revised.lines.join(`
|
|
538
538
|
`)}),"...",o.jsx("br",{})]})}const AY="_splitButton_1i0gi_1",_Y="_menuControl_1i0gi_6",cT={splitButton:AY,menuControl:_Y};function Yh(e){const{outcome:t}=e,n=_e(),r=Qt(e.defaultValue),i=r==null?void 0:r.resourceType,[s,c]=v.useState(!1),[u,f]=v.useState(),h=n.getAccessPolicy(),m=Sn();v.useEffect(()=>{if(r)if(e.profileUrl){const b=e.profileUrl;n.requestProfileSchema(e.profileUrl,{expandProfile:!0}).then(()=>{const S=Pc(b);if(S){c(!0);const j=xV(r,S);f(j)}else console.error(`Schema not found for ${b}`)}).catch(S=>{console.error("Error in requestProfileSchema",S)})}else n.requestSchema(i).then(()=>{f(r),c(!0)}).catch(console.log)},[n,r,i,e.profileUrl]);const g=v.useMemo(()=>r&&IA(r,Ns.READ,h),[h,r]),y=v.useMemo(()=>n.isSuperAdmin()||!h||!Tn(u==null?void 0:u.resourceType)?!0:SB(h,u==null?void 0:u.resourceType),[n,h,u==null?void 0:u.resourceType]);return!s||!u?o.jsx("div",{children:"Loading..."}):y?o.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:b=>{b.preventDefault(),e.onSubmit&&e.onSubmit(u)},children:[o.jsxs(Ge,{mb:"xl",children:[o.jsx($t,{title:"Resource Type",htmlFor:"resourceType",outcome:t,children:o.jsx(ze,{name:"resourceType",defaultValue:u.resourceType,disabled:!0})}),o.jsx($t,{title:"ID",htmlFor:"id",outcome:t,children:o.jsx(ze,{name:"id",defaultValue:u.id,disabled:!0})})]}),o.jsx(kb,{path:u.resourceType,valuePath:u.resourceType,typeName:i,defaultValue:u,outcome:t,onChange:f,profileUrl:e.profileUrl,accessPolicyResource:g}),o.jsxs(Ce,{justify:"flex-end",mt:"xl",wrap:"nowrap",gap:0,children:[o.jsx(Ne,{type:"submit",className:Ut((e.onPatch||e.onDelete)&&cT.splitButton),children:r!=null&&r.id?"Update":"Create"}),(e.onPatch||e.onDelete)&&o.jsxs(je,{transitionProps:{transition:"pop"},position:"bottom-end",withinPortal:!0,children:[o.jsx(je.Target,{children:o.jsx(_n,{variant:"filled",color:m.primaryColor,size:36,className:cT.menuControl,"aria-label":"More actions",children:o.jsx(mb,{size:14,stroke:1.5})})}),o.jsxs(je.Dropdown,{children:[e.onPatch&&o.jsx(je.Item,{leftSection:o.jsx(e_,{size:14,stroke:1.5}),onClick:()=>{e.onPatch(u)},children:"Patch"}),e.onDelete&&o.jsx(je.Item,{color:"red",leftSection:o.jsx(xb,{size:14,stroke:1.5,color:"red"}),onClick:()=>{e.onDelete(u)},children:"Delete"})]})]})]})]}):o.jsxs(Ya,{color:"red",title:"Permission denied",icon:o.jsx(rl,{}),children:["Your access level prevents you from editing and creating ",u.resourceType," resources."]})}function kY(e){var i;const t=_e(),[n,r]=v.useState(e.history);return v.useEffect(()=>{!e.history&&e.resourceType&&e.id&&t.readHistory(e.resourceType,e.id).then(r).catch(console.log)},[t,e.history,e.resourceType,e.id]),n?o.jsxs(ye,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[o.jsx(ye.Thead,{children:o.jsxs(ye.Tr,{children:[o.jsx(ye.Th,{children:"Author"}),o.jsx(ye.Th,{children:"Date"}),o.jsx(ye.Th,{children:"Version"})]})}),o.jsx(ye.Tbody,{children:(i=n.entry)==null?void 0:i.map((s,c)=>o.jsx(PY,{entry:s},"entry-"+c))})]}):o.jsx("div",{children:"Loading..."})}function PY(e){var r,i,s;const{response:t,resource:n}=e.entry;return n?o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:o.jsx(oc,{value:(r=n.meta)==null?void 0:r.author,link:!0})}),o.jsx(ye.Td,{children:gr((i=n.meta)==null?void 0:i.lastUpdated)}),o.jsx(ye.Td,{children:o.jsx(mt,{to:NY(n),children:(s=n.meta)==null?void 0:s.versionId})})]}):o.jsx(ye.Tr,{children:o.jsx(ye.Td,{colSpan:3,children:Ye(t==null?void 0:t.outcome)})})}function NY(e){var t;return`/${e.resourceType}/${e.id}/_history/${(t=e.meta)==null?void 0:t.versionId}`}function OY(e){const{serviceRequest:t,...n}=e;return o.jsx(sm,{value:t,loadTimelineResources:async(r,i,s)=>{const c=`${i}/${s}`,u=100;return Promise.allSettled([r.readHistory("ServiceRequest",s),r.search("Communication",{"based-on":c,_count:u}),r.search("DiagnosticReport",{"based-on":c,_count:u}),r.search("Media",{"based-on":c,_count:u}),r.search("DocumentReference",{related:c,_count:u}),r.search("Task",{_filter:`based-on eq ${c} or focus eq ${c} or subject eq ${c}`,_count:u})])},createCommunication:(r,i,s)=>({resourceType:"Communication",status:"completed",basedOn:[on(r)],subject:r.subject,sender:on(i),sent:new Date().toISOString(),payload:[{contentString:s}]}),createMedia:(r,i,s)=>({resourceType:"Media",status:"completed",basedOn:[on(r)],subject:r.subject,operator:on(i),issued:new Date().toISOString(),content:s}),...n})}function MY(e){const t=_e(),{client:n,patient:r,encounter:i,children:s,...c}=e;function u(){t.createResource({resourceType:"SmartAppLaunch",patient:r,encounter:i}).then(f=>{const h=new URL(n.launchUri);h.searchParams.set("iss",tb(t.fhirUrl().toString())),h.searchParams.set("launch",f.id),window.location.assign(h.toString())}).catch(f=>Oe({color:"red",message:Ye(f),autoClose:!1}))}return o.jsx(Nt,{onClick:()=>u(),...c,children:s})}var ny={exports:{}},$u={},ry={exports:{}},iy={};/**
|
|
539
539
|
* @license React
|
|
@@ -582,5 +582,5 @@ Please change the parent <Route path="${D}"> to <Route path="${D==="/"?"*":`${D}
|
|
|
582
582
|
"family": "Smith"
|
|
583
583
|
}
|
|
584
584
|
]
|
|
585
|
-
}`,YJ="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 KJ(){const e=_e(),{id:t}=qt(),[n,r]=v.useState(),[i,s]=v.useState(),[c,u]=v.useState(WJ),[f,h]=v.useState(YJ),[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 XJ(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(QJ,{iframeRef:y,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:i,minHeight:"528px"}),o.jsxs(Ce,{justify:"flex-end",gap:"xs",children:[o.jsx(Ne,{type:"button",onClick:E,loading:S,leftSection:o.jsx(JV,{size:"1rem"}),children:"Save"}),o.jsx(Ne,{type:"button",onClick:R,loading:S,leftSection:o.jsx(gb,{size:"1rem"}),children:"Deploy"}),o.jsx(Ne,{type:"button",onClick:A,loading:S,leftSection:o.jsx(pF,{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:qJ.hl7Input,value:f,onChange:k=>h(k.currentTarget.value),rows:15})]}),o.jsx(mr,{m:2,p:"xs",shadow:"md",children:o.jsx(GJ,{iframeRef:b,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function XJ(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(SA);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 ZJ(){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(WQ,{value:r,onSubmit:i})});case"Questionnaire":return o.jsx(ot,{children:o.jsx(MW,{questionnaire:r,onSubmit:i})});default:return null}}function JJ(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t}),r=wn();return n?o.jsx(ot,{children:o.jsx(oY,{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 eee(){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 tee="_selectProfileBtn_tbaz6_1",nee="_chevron_tbaz6_13",JT={selectProfileBtn:tee,chevron:nee};function ree(){var f,h;const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t}),[r,i]=v.useState(),s=xd({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])},[(h=n==null?void 0:n.meta)==null?void 0:h.profile]),!n)return null;let u;return Tn(c)&&(u=o.jsx(Ce,{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(f0,{fw:"bold",fs:"sm",className:JT.selectProfileBtn,children:[o.jsx("span",{children:"Pick profile"}),o.jsx(mb,{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(Nb,{value:n,profileUrl:r})]})})}function iee(){const e=_e(),{resourceType:t,id:n}=qt(),[r,i]=v.useState(),[s,c]=v.useState(),u=wn(),[f,h]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(b=>{i(Qr(b)),c(Qr(b))}).catch(b=>{h(Zt(b)),Oe({color:"red",message:Ye(b),autoClose:!1})})},[e,t,n]);const m=v.useCallback(b=>{h(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=>{h(Zt(S)),Oe({color:"red",message:Ye(S),autoClose:!1})})},[e,t,n,u]),g=v.useCallback(b=>{h(void 0);const S=L_.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=>{h(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 aee(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t});return n?o.jsx(ot,{maw:700,children:n.resourceType==="Patient"?o.jsx(VQ,{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 n4({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(cq))}).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(h=>h.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),h=f?"This profile is present in this resource's meta.profile property.":"This profile is not included in this resource's meta.profile property.";return o.jsx(Et.Tab,{value:u.url,title:h,rightSection:f&&o.jsx(G0,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:o.jsx(TF,{size:"90%"})}),children:u.title||u.name},u.url)})})})}function r4(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 py(){const{resourceType:e}=qt(),t=Mr(),[n,r]=v.useState(),{defaultValue:i,handleSubmit:s}=r4(e,r),[c,u]=v.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),h=v.useCallback(m=>{const g=sl(m);c&&TA(g,c.url),s(g)},[c,s]);return f?o.jsx(ot,{children:o.jsxs(Ge,{children:[o.jsx(n4,{resource:i,currentProfile:c,onChange:u}),c?o.jsx(Yh,{defaultValue:i,onSubmit:h,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 oee(){const e=_e(),{resourceType:t,id:n}=qt(),r=e.readHistory(t,n).read();return o.jsx(ot,{children:o.jsx(kY,{history:r})})}function see(){const{resourceType:e}=qt(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:i}=r4(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(Ce,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:o.jsx(Ne,{type:"submit",children:"OK"})})]})]})}function lee(){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 h;c(void 0),(h=i(`/${t}/${n}/details`))==null||h.catch(console.error),Oe({color:"green",message:"Success"})}).catch(h=>{Oe({color:"red",message:Ye(h),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(Ce,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:o.jsx(Ne,{type:"submit",children:"OK"})})]})]}):null}function cee(){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(ck,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function uee(){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(n4,{resource:r,currentProfile:s,onChange:c}),s?o.jsx(dee,{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 dee=({profile:e,resource:t,onResourceUpdated:n})=>{const r=_e(),[i,s]=v.useState(),[c,u]=v.useState(()=>{var h,m;return(m=(h=t.meta)==null?void 0:h.profile)==null?void 0:m.includes(e.url)}),f=v.useCallback(h=>{s(void 0);const m=sl(h);c?TA(m,e.url):nU(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(Cd,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:h=>u(h.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:h=>{h.preventDefault(),f(t)},children:o.jsx(Ce,{justify:"flex-end",mt:"xl",children:o.jsx(Ne,{type:"submit",children:"OK"})})})]})},i4={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},fee=Object.keys(i4);function hee(){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),h=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>pee(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:[h.length===0&&o.jsx("p",{children:"No bots found."}),h.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(md,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),o.jsxs(Ce,{children:[o.jsx(il,{name:"bot",resourceType:"Bot",onChange:g=>i(g)}),o.jsx(Ne,{onClick:m,children:"Connect"})]}),o.jsx(Ce,{children:o.jsx(ln,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:fee,onChange:g=>c(i4[g.target.value])})})]}),o.jsx("div",{style:{display:"none"},children:u})]})}function pee(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 mee(){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 gee(){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(ZW,{onSubmit:i,definition:r})}):null}function vee(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t});return n?o.jsx(ot,{children:e==="MeasureReport"?o.jsx(UQ,{measureReport:n}):o.jsx(Pb,{value:n})}):null}const yee="_container_1ue98_1",xee="_entry_1ue98_14",bee="_active_1ue98_21",my={container:yee,entry:xee,active:bee};function See(e){const t=_e(),n=Qt(e.value),[r,i]=v.useState();return v.useEffect(()=>{if(!n)return;const s=r1(n);if(!s)return;const c="reference"in s?s.reference:zt(s);t.search("ServiceRequest","subject="+c).then(u=>{const h=(u.entry??[]).map(m=>m.resource);z_(h),h.reverse(),i(h)}).catch(u=>Oe({color:"red",message:Ye(u),autoClose:!1}))},[t,n]),r?o.jsx("div",{"data-testid":"quick-service-requests",className:my.container,children:r.map(s=>{var c,u,f,h,m,g,y;return o.jsxs("div",{className:Ut(my.entry,{[my.active]:s.id===(n==null?void 0:n.id)}),children:[o.jsx("p",{children:o.jsx(mt,{to:s,children:wee(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=(h=s.code)==null?void 0:h.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:jee(s)})]},s.id)})}):null}function wee(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function jee(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const Cee="_container_1l2dh_1",Eee={container:Cee};function Tee(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:Eee.container,children:o.jsx(ln,{defaultValue:e.defaultValue,onChange:f=>e.onChange(f.currentTarget.value),data:n})})}function Ree(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:Dee(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:Aee(t)})]}):o.jsx(o.Fragment,{})]}):null}function Dee(e){var i;const t=(i=e.collection)==null?void 0:i.collectedDateTime;if(!t)return;const n=new Date(t);return a4(o4(n,new Date))}function Aee(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 a4(o4(t,n))}function a4(e){return e.toString().padStart(3,"0")+"D"}function o4(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function _ee(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 kee(){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=_ee(t),[h,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 u$(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&&r1(u),C=u&&YZ(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(Tee,{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(See,{value:u}),u&&o.jsxs(mr,{children:[j&&o.jsx(G_,{patient:j}),C&&o.jsx(Ree,{specimen:C}),t!=="Patient"&&o.jsx(Yk,{resource:r}),o.jsx(Yr,{children:o.jsx(Et,{value:h.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(Kb,{})]})}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,h]=v.useState(),[m,g]=v.useState();if(v.useEffect(()=>{g(void 0),u(!0),s.readHistory(t,n).then(A=>h(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(RY,{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 Pee(){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(CQ,{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 Nee(e){const t=_e(),{resource:n,opened:r,onClose:i}=e,[s,c]=v.useState(!1),[u,f]=v.useState(),[h,m]=v.useState(!1),g=v.useCallback(async()=>{if(n!=null&&n.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:s&&u?zt(u):void 0,verbose:h}),Oe({color:"green",message:"Done"}),i()}catch(y){Oe({color:"red",message:Ye(y),autoClose:!1})}},[t,n,i,s,u,h]);return o.jsx($n,{opened:r,onClose:i,title:"Resend Subscriptions",children:o.jsx(pt,{onSubmit:g,children:o.jsxs(Ge,{children:[o.jsx(Fn,{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(Fn,{label:"Verbose mode",onChange:y=>m(y.currentTarget.checked)}),o.jsx(Ce,{justify:"flex-end",children:o.jsx(Ne,{type:"submit",children:"Resend"})})]})})})}function tR(){const e=_e(),t=em(),{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 h(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,Z=sJ()&&(R.resourceType==="DocumentReference"||R.resourceType==="Media");return o.jsxs(je.Dropdown,{children:[o.jsx(je.Label,{children:"Resource"}),M&&o.jsx(je.Item,{leftSection:o.jsx(fF,{size:14}),onClick:()=>h(R,A),"aria-label":`Pin ${zt(R)}`,children:"Pin"}),I&&o.jsx(je.Item,{leftSection:o.jsx(hF,{size:14}),onClick:()=>m(R,A),"aria-label":`Unpin ${zt(R)}`,children:"Unpin"}),V&&o.jsx(je.Item,{leftSection:o.jsx(ME,{size:14}),onClick:()=>g(R),"aria-label":`Details ${zt(R)}`,children:"Details"}),$&&o.jsx(je.Item,{leftSection:o.jsx(ME,{size:14}),onClick:()=>j(R),"aria-label":`Details ${zt(R)}`,children:"Details"}),Y&&o.jsx(je.Item,{leftSection:o.jsx(e_,{size:14}),onClick:()=>y(R),"aria-label":`Edit ${zt(R)}`,children:"Edit"}),J&&o.jsxs(o.Fragment,{children:[o.jsx(je.Divider,{}),o.jsx(je.Label,{children:"Admin"}),G&&o.jsx(je.Item,{leftSection:o.jsx(gF,{size:14}),onClick:()=>S(R),"aria-label":`Resend Subscriptions ${zt(R)}`,children:"Resend Subscriptions"})]}),Z&&o.jsxs(o.Fragment,{children:[o.jsx(je.Divider,{}),o.jsx(je.Label,{children:"AWS AI"}),o.jsx(je.Item,{leftSection:o.jsx(CF,{size:14}),onClick:()=>C(R,A),"aria-label":`AWS Textract ${zt(R)}`,children:"AWS Textract"})]}),Q&&o.jsxs(o.Fragment,{children:[o.jsx(je.Divider,{}),o.jsx(je.Label,{children:"Danger zone"}),o.jsx(je.Item,{color:"red",leftSection:o.jsx(xb,{size:14}),onClick:()=>b(R),"aria-label":`Delete ${zt(R)}`,children:"Delete"})]})]})}return o.jsxs(o.Fragment,{children:[n==="Encounter"&&o.jsx(PG,{encounter:i,getMenu:T}),n==="Patient"&&o.jsx(qQ,{patient:i,getMenu:T}),n==="ServiceRequest"&&o.jsx(OY,{serviceRequest:i,getMenu:T}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&o.jsx(kG,{resource:i,getMenu:T}),o.jsx(Nee,{resource:s,opened:u[0],onClose:u[1].close},`resend-subscriptions-${s==null?void 0:s.id}`)]})}function Oee(e){const{opened:t,close:n,version:r,loadingStatus:i,handleStatus:s,handleUpgrade:c}=e,[u,f]=v.useState();return v.useEffect(()=>{t&&(u||EV("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.jsx(Ne,{onClick:()=>{c(),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"})]}):o.jsx(gi,{})}function Mee(){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),[h,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 Z,P,L,z,H,O;m((P=(Z=G.parameter)==null?void 0:Z.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 Z=G.host,P=G.pingCount||1;Z&&(D(!0),e.pushToAgent(n,Z,`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(()=>{f(!0),e.get(e.fhirUrl("Agent",t,"$upgrade"),{cache:"reload"}).then(G=>{Q("Agent upgraded successfully.")}).catch(G=>J(Ye(G))).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($n,{opened:A,onClose:M,title:"Upgrade Agent",centered:!0,children:o.jsx(Oee,{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&&h&&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(om,{status:h})})]}),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(Ce,{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(yF,{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 Iee(){return o.jsx(fX,{children:o.jsxs(Fe,{errorElement:o.jsx(WZ,{}),children:[o.jsx(Fe,{path:"/signin",element:o.jsx(hJ,{})}),o.jsx(Fe,{path:"/oauth",element:o.jsx(lJ,{})}),o.jsx(Fe,{path:"/resetpassword",element:o.jsx(uJ,{})}),o.jsx(Fe,{path:"/setpassword/:id/:secret",element:o.jsx(fJ,{})}),o.jsx(Fe,{path:"/register",element:o.jsx(cJ,{})}),o.jsx(Fe,{path:"/changepassword",element:o.jsx(qZ,{})}),o.jsx(Fe,{path:"/security",element:o.jsx(dJ,{})}),o.jsx(Fe,{path:"/mfa",element:o.jsx(oJ,{})}),o.jsx(Fe,{path:"/batch",element:o.jsx(FZ,{})}),o.jsx(Fe,{path:"/bulk/:resourceType",element:o.jsx(HZ,{})}),o.jsx(Fe,{path:"/smart",element:o.jsx(pJ,{})}),o.jsx(Fe,{path:"/forms/:id",element:o.jsx(KZ,{})}),o.jsx(Fe,{path:"/admin/super",element:o.jsx(NJ,{})}),o.jsx(Fe,{path:"/admin/super/asyncjob",element:o.jsx(RJ,{})}),o.jsx(Fe,{path:"/admin/config",element:o.jsx(jJ,{})}),o.jsxs(Fe,{path:"/admin",element:o.jsx(CJ,{}),children:[o.jsx(Fe,{path:"patients",element:o.jsx(wJ,{})}),o.jsx(Fe,{path:"bots/new",element:o.jsx(vJ,{})}),o.jsx(Fe,{path:"bots",element:o.jsx(mJ,{})}),o.jsx(Fe,{path:"clients/new",element:o.jsx(yJ,{})}),o.jsx(Fe,{path:"clients",element:o.jsx(gJ,{})}),o.jsx(Fe,{path:"details",element:o.jsx(WT,{})}),o.jsx(Fe,{path:"invite",element:o.jsx(SJ,{})}),o.jsx(Fe,{path:"users",element:o.jsx(MJ,{})}),o.jsx(Fe,{path:"project",element:o.jsx(WT,{})}),o.jsx(Fe,{path:"secrets",element:o.jsx(EJ,{})}),o.jsx(Fe,{path:"sites",element:o.jsx(TJ,{})}),o.jsx(Fe,{path:"members/:membershipId",element:o.jsx(bJ,{})})]}),o.jsx(Fe,{path:"/lab/assays",element:o.jsx(IJ,{})}),o.jsx(Fe,{path:"/lab/panels",element:o.jsx(LJ,{})}),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(QZ,{}),children:[o.jsx(Fe,{index:!0,element:o.jsx(py,{})}),o.jsx(Fe,{path:"form",element:o.jsx(py,{})}),o.jsx(Fe,{path:"json",element:o.jsx(see,{})}),o.jsx(Fe,{path:"profiles",element:o.jsx(py,{})})]}),o.jsxs(Fe,{path:"/:resourceType/:id",element:o.jsx(kee,{}),children:[o.jsx(Fe,{index:!0,element:o.jsx(tR,{})}),o.jsx(Fe,{path:"apply",element:o.jsx($J,{})}),o.jsx(Fe,{path:"apps",element:o.jsx(UJ,{})}),o.jsx(Fe,{path:"event",element:o.jsx(VJ,{})}),o.jsx(Fe,{path:"blame",element:o.jsx(FJ,{})}),o.jsx(Fe,{path:"bots",element:o.jsx(hee,{})}),o.jsx(Fe,{path:"builder",element:o.jsx(ZJ,{})}),o.jsx(Fe,{path:"checklist",element:o.jsx(JJ,{})}),o.jsx(Fe,{path:"delete",element:o.jsx(eee,{})}),o.jsx(Fe,{path:"details",element:o.jsx(ree,{})}),o.jsx(Fe,{path:"edit",element:o.jsx(iee,{})}),o.jsx(Fe,{path:"editor",element:o.jsx(KJ,{})}),o.jsx(Fe,{path:"history",element:o.jsx(oee,{})}),o.jsx(Fe,{path:"json",element:o.jsx(lee,{})}),o.jsx(Fe,{path:"preview",element:o.jsx(cee,{})}),o.jsx(Fe,{path:"responses",element:o.jsx(mee,{})}),o.jsx(Fe,{path:"report",element:o.jsx(vee,{})}),o.jsx(Fe,{path:"ranges",element:o.jsx(gee,{})}),o.jsx(Fe,{path:"subscriptions",element:o.jsx(Pee,{})}),o.jsx(Fe,{path:"timeline",element:o.jsx(tR,{})}),o.jsx(Fe,{path:"tools",element:o.jsx(Mee,{})}),o.jsx(Fe,{path:"profiles",element:o.jsx(uee,{})}),o.jsx(Fe,{path:"export",element:o.jsx(aee,{})})]}),o.jsx(Fe,{path:"/:resourceType",element:o.jsx(QT,{})}),o.jsx(Fe,{path:"/",element:o.jsx(QT,{})})]})})}function Lee(){const e=_e(),t=e.getUserConfiguration(),n=Mr(),[r]=Jb();return e.isLoading()?o.jsx(gi,{}):o.jsx(yH,{logo:o.jsx(Ui,{size:24}),pathname:n.pathname,searchParams:r,version:FA,menus:zee(t),displayAddBookmark:!!(t!=null&&t.id),children:o.jsx(v.Suspense,{fallback:o.jsx(gi,{}),children:o.jsx(Iee,{})})})}function zee(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:$ee(s.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:o.jsx(oF,{})}]}),t}const nR={Patient:SF,Practitioner:iF,Organization:WV,ServiceRequest:mF,DiagnosticReport:vF,Questionnaire:rF,admin:qV,AccessPolicy:aF,Subscription:EF,batch:dF,Observation:cF};function $ee(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 Uee(){const e=Vd(),t=new HA({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=LX([{path:"*",element:o.jsx(Lee,{})}]),i=c=>r.navigate(c);UY.createRoot(document.getElementById("root")).render(o.jsx(v.StrictMode,{children:o.jsx(TV,{medplum:t,navigate:i,children:o.jsxs(RR,{theme:n,children:[o.jsx(Za,{position:"bottom-right"}),o.jsx(lX,{router:r})]})})}))}Uee().catch(console.error);
|
|
586
|
-
//# sourceMappingURL=index-
|
|
585
|
+
}`,YJ="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 KJ(){const e=_e(),{id:t}=qt(),[n,r]=v.useState(),[i,s]=v.useState(),[c,u]=v.useState(WJ),[f,h]=v.useState(YJ),[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 XJ(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(QJ,{iframeRef:y,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:i,minHeight:"528px"}),o.jsxs(Ce,{justify:"flex-end",gap:"xs",children:[o.jsx(Ne,{type:"button",onClick:E,loading:S,leftSection:o.jsx(JV,{size:"1rem"}),children:"Save"}),o.jsx(Ne,{type:"button",onClick:R,loading:S,leftSection:o.jsx(gb,{size:"1rem"}),children:"Deploy"}),o.jsx(Ne,{type:"button",onClick:A,loading:S,leftSection:o.jsx(pF,{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:qJ.hl7Input,value:f,onChange:k=>h(k.currentTarget.value),rows:15})]}),o.jsx(mr,{m:2,p:"xs",shadow:"md",children:o.jsx(GJ,{iframeRef:b,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function XJ(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(SA);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 ZJ(){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(WQ,{value:r,onSubmit:i})});case"Questionnaire":return o.jsx(ot,{children:o.jsx(MW,{questionnaire:r,onSubmit:i})});default:return null}}function JJ(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t}),r=wn();return n?o.jsx(ot,{children:o.jsx(oY,{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 eee(){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 tee="_selectProfileBtn_tbaz6_1",nee="_chevron_tbaz6_13",JT={selectProfileBtn:tee,chevron:nee};function ree(){var f,h;const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t}),[r,i]=v.useState(),s=xd({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])},[(h=n==null?void 0:n.meta)==null?void 0:h.profile]),!n)return null;let u;return Tn(c)&&(u=o.jsx(Ce,{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(f0,{fw:"bold",fs:"sm",className:JT.selectProfileBtn,children:[o.jsx("span",{children:"Pick profile"}),o.jsx(mb,{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(Nb,{value:n,profileUrl:r})]})})}function iee(){const e=_e(),{resourceType:t,id:n}=qt(),[r,i]=v.useState(),[s,c]=v.useState(),u=wn(),[f,h]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(b=>{i(Qr(b)),c(Qr(b))}).catch(b=>{h(Zt(b)),Oe({color:"red",message:Ye(b),autoClose:!1})})},[e,t,n]);const m=v.useCallback(b=>{h(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=>{h(Zt(S)),Oe({color:"red",message:Ye(S),autoClose:!1})})},[e,t,n,u]),g=v.useCallback(b=>{h(void 0);const S=L_.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=>{h(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 aee(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t});return n?o.jsx(ot,{maw:700,children:n.resourceType==="Patient"?o.jsx(VQ,{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 n4({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(cq))}).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(h=>h.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),h=f?"This profile is present in this resource's meta.profile property.":"This profile is not included in this resource's meta.profile property.";return o.jsx(Et.Tab,{value:u.url,title:h,rightSection:f&&o.jsx(G0,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:o.jsx(TF,{size:"90%"})}),children:u.title||u.name},u.url)})})})}function r4(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 py(){const{resourceType:e}=qt(),t=Mr(),[n,r]=v.useState(),{defaultValue:i,handleSubmit:s}=r4(e,r),[c,u]=v.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),h=v.useCallback(m=>{const g=sl(m);c&&TA(g,c.url),s(g)},[c,s]);return f?o.jsx(ot,{children:o.jsxs(Ge,{children:[o.jsx(n4,{resource:i,currentProfile:c,onChange:u}),c?o.jsx(Yh,{defaultValue:i,onSubmit:h,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 oee(){const e=_e(),{resourceType:t,id:n}=qt(),r=e.readHistory(t,n).read();return o.jsx(ot,{children:o.jsx(kY,{history:r})})}function see(){const{resourceType:e}=qt(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:i}=r4(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(Ce,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:o.jsx(Ne,{type:"submit",children:"OK"})})]})]})}function lee(){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 h;c(void 0),(h=i(`/${t}/${n}/details`))==null||h.catch(console.error),Oe({color:"green",message:"Success"})}).catch(h=>{Oe({color:"red",message:Ye(h),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(Ce,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:o.jsx(Ne,{type:"submit",children:"OK"})})]})]}):null}function cee(){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(ck,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function uee(){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(n4,{resource:r,currentProfile:s,onChange:c}),s?o.jsx(dee,{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 dee=({profile:e,resource:t,onResourceUpdated:n})=>{const r=_e(),[i,s]=v.useState(),[c,u]=v.useState(()=>{var h,m;return(m=(h=t.meta)==null?void 0:h.profile)==null?void 0:m.includes(e.url)}),f=v.useCallback(h=>{s(void 0);const m=sl(h);c?TA(m,e.url):nU(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(Cd,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:h=>u(h.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:h=>{h.preventDefault(),f(t)},children:o.jsx(Ce,{justify:"flex-end",mt:"xl",children:o.jsx(Ne,{type:"submit",children:"OK"})})})]})},i4={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},fee=Object.keys(i4);function hee(){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),h=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>pee(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:[h.length===0&&o.jsx("p",{children:"No bots found."}),h.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(md,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),o.jsxs(Ce,{children:[o.jsx(il,{name:"bot",resourceType:"Bot",onChange:g=>i(g)}),o.jsx(Ne,{onClick:m,children:"Connect"})]}),o.jsx(Ce,{children:o.jsx(ln,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:fee,onChange:g=>c(i4[g.target.value])})})]}),o.jsx("div",{style:{display:"none"},children:u})]})}function pee(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 mee(){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 gee(){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(ZW,{onSubmit:i,definition:r})}):null}function vee(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t});return n?o.jsx(ot,{children:e==="MeasureReport"?o.jsx(UQ,{measureReport:n}):o.jsx(Pb,{value:n})}):null}const yee="_container_1ue98_1",xee="_entry_1ue98_14",bee="_active_1ue98_21",my={container:yee,entry:xee,active:bee};function See(e){const t=_e(),n=Qt(e.value),[r,i]=v.useState();return v.useEffect(()=>{if(!n)return;const s=r1(n);if(!s)return;const c="reference"in s?s.reference:zt(s);t.search("ServiceRequest","subject="+c).then(u=>{const h=(u.entry??[]).map(m=>m.resource);z_(h),h.reverse(),i(h)}).catch(u=>Oe({color:"red",message:Ye(u),autoClose:!1}))},[t,n]),r?o.jsx("div",{"data-testid":"quick-service-requests",className:my.container,children:r.map(s=>{var c,u,f,h,m,g,y;return o.jsxs("div",{className:Ut(my.entry,{[my.active]:s.id===(n==null?void 0:n.id)}),children:[o.jsx("p",{children:o.jsx(mt,{to:s,children:wee(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=(h=s.code)==null?void 0:h.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:jee(s)})]},s.id)})}):null}function wee(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function jee(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const Cee="_container_1l2dh_1",Eee={container:Cee};function Tee(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:Eee.container,children:o.jsx(ln,{defaultValue:e.defaultValue,onChange:f=>e.onChange(f.currentTarget.value),data:n})})}function Ree(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:Dee(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:Aee(t)})]}):o.jsx(o.Fragment,{})]}):null}function Dee(e){var i;const t=(i=e.collection)==null?void 0:i.collectedDateTime;if(!t)return;const n=new Date(t);return a4(o4(n,new Date))}function Aee(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 a4(o4(t,n))}function a4(e){return e.toString().padStart(3,"0")+"D"}function o4(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function _ee(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 kee(){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=_ee(t),[h,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 u8(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&&r1(u),C=u&&YZ(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(Tee,{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(See,{value:u}),u&&o.jsxs(mr,{children:[j&&o.jsx(G_,{patient:j}),C&&o.jsx(Ree,{specimen:C}),t!=="Patient"&&o.jsx(Yk,{resource:r}),o.jsx(Yr,{children:o.jsx(Et,{value:h.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(Kb,{})]})}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,h]=v.useState(),[m,g]=v.useState();if(v.useEffect(()=>{g(void 0),u(!0),s.readHistory(t,n).then(A=>h(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(RY,{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 Pee(){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(CQ,{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 Nee(e){const t=_e(),{resource:n,opened:r,onClose:i}=e,[s,c]=v.useState(!1),[u,f]=v.useState(),[h,m]=v.useState(!1),g=v.useCallback(async()=>{if(n!=null&&n.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:s&&u?zt(u):void 0,verbose:h}),Oe({color:"green",message:"Done"}),i()}catch(y){Oe({color:"red",message:Ye(y),autoClose:!1})}},[t,n,i,s,u,h]);return o.jsx($n,{opened:r,onClose:i,title:"Resend Subscriptions",children:o.jsx(pt,{onSubmit:g,children:o.jsxs(Ge,{children:[o.jsx(Fn,{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(Fn,{label:"Verbose mode",onChange:y=>m(y.currentTarget.checked)}),o.jsx(Ce,{justify:"flex-end",children:o.jsx(Ne,{type:"submit",children:"Resend"})})]})})})}function tR(){const e=_e(),t=em(),{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 h(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,Z=sJ()&&(R.resourceType==="DocumentReference"||R.resourceType==="Media");return o.jsxs(je.Dropdown,{children:[o.jsx(je.Label,{children:"Resource"}),M&&o.jsx(je.Item,{leftSection:o.jsx(fF,{size:14}),onClick:()=>h(R,A),"aria-label":`Pin ${zt(R)}`,children:"Pin"}),I&&o.jsx(je.Item,{leftSection:o.jsx(hF,{size:14}),onClick:()=>m(R,A),"aria-label":`Unpin ${zt(R)}`,children:"Unpin"}),V&&o.jsx(je.Item,{leftSection:o.jsx(ME,{size:14}),onClick:()=>g(R),"aria-label":`Details ${zt(R)}`,children:"Details"}),$&&o.jsx(je.Item,{leftSection:o.jsx(ME,{size:14}),onClick:()=>j(R),"aria-label":`Details ${zt(R)}`,children:"Details"}),Y&&o.jsx(je.Item,{leftSection:o.jsx(e_,{size:14}),onClick:()=>y(R),"aria-label":`Edit ${zt(R)}`,children:"Edit"}),J&&o.jsxs(o.Fragment,{children:[o.jsx(je.Divider,{}),o.jsx(je.Label,{children:"Admin"}),G&&o.jsx(je.Item,{leftSection:o.jsx(gF,{size:14}),onClick:()=>S(R),"aria-label":`Resend Subscriptions ${zt(R)}`,children:"Resend Subscriptions"})]}),Z&&o.jsxs(o.Fragment,{children:[o.jsx(je.Divider,{}),o.jsx(je.Label,{children:"AWS AI"}),o.jsx(je.Item,{leftSection:o.jsx(CF,{size:14}),onClick:()=>C(R,A),"aria-label":`AWS Textract ${zt(R)}`,children:"AWS Textract"})]}),Q&&o.jsxs(o.Fragment,{children:[o.jsx(je.Divider,{}),o.jsx(je.Label,{children:"Danger zone"}),o.jsx(je.Item,{color:"red",leftSection:o.jsx(xb,{size:14}),onClick:()=>b(R),"aria-label":`Delete ${zt(R)}`,children:"Delete"})]})]})}return o.jsxs(o.Fragment,{children:[n==="Encounter"&&o.jsx(PG,{encounter:i,getMenu:T}),n==="Patient"&&o.jsx(qQ,{patient:i,getMenu:T}),n==="ServiceRequest"&&o.jsx(OY,{serviceRequest:i,getMenu:T}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&o.jsx(kG,{resource:i,getMenu:T}),o.jsx(Nee,{resource:s,opened:u[0],onClose:u[1].close},`resend-subscriptions-${s==null?void 0:s.id}`)]})}function Oee(e){const{opened:t,close:n,version:r,loadingStatus:i,handleStatus:s,handleUpgrade:c}=e,[u,f]=v.useState();return v.useEffect(()=>{t&&(u||EV("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.jsx(Ne,{onClick:()=>{c(),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"})]}):o.jsx(gi,{})}function Mee(){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),[h,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 Z,P,L,z,H,O;m((P=(Z=G.parameter)==null?void 0:Z.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 Z=G.host,P=G.pingCount||1;Z&&(D(!0),e.pushToAgent(n,Z,`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(()=>{f(!0),e.get(e.fhirUrl("Agent",t,"$upgrade"),{cache:"reload"}).then(G=>{Q("Agent upgraded successfully.")}).catch(G=>J(Ye(G))).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($n,{opened:A,onClose:M,title:"Upgrade Agent",centered:!0,children:o.jsx(Oee,{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&&h&&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(om,{status:h})})]}),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(Ce,{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(yF,{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 Iee(){return o.jsx(fX,{children:o.jsxs(Fe,{errorElement:o.jsx(WZ,{}),children:[o.jsx(Fe,{path:"/signin",element:o.jsx(hJ,{})}),o.jsx(Fe,{path:"/oauth",element:o.jsx(lJ,{})}),o.jsx(Fe,{path:"/resetpassword",element:o.jsx(uJ,{})}),o.jsx(Fe,{path:"/setpassword/:id/:secret",element:o.jsx(fJ,{})}),o.jsx(Fe,{path:"/register",element:o.jsx(cJ,{})}),o.jsx(Fe,{path:"/changepassword",element:o.jsx(qZ,{})}),o.jsx(Fe,{path:"/security",element:o.jsx(dJ,{})}),o.jsx(Fe,{path:"/mfa",element:o.jsx(oJ,{})}),o.jsx(Fe,{path:"/batch",element:o.jsx(FZ,{})}),o.jsx(Fe,{path:"/bulk/:resourceType",element:o.jsx(HZ,{})}),o.jsx(Fe,{path:"/smart",element:o.jsx(pJ,{})}),o.jsx(Fe,{path:"/forms/:id",element:o.jsx(KZ,{})}),o.jsx(Fe,{path:"/admin/super",element:o.jsx(NJ,{})}),o.jsx(Fe,{path:"/admin/super/asyncjob",element:o.jsx(RJ,{})}),o.jsx(Fe,{path:"/admin/config",element:o.jsx(jJ,{})}),o.jsxs(Fe,{path:"/admin",element:o.jsx(CJ,{}),children:[o.jsx(Fe,{path:"patients",element:o.jsx(wJ,{})}),o.jsx(Fe,{path:"bots/new",element:o.jsx(vJ,{})}),o.jsx(Fe,{path:"bots",element:o.jsx(mJ,{})}),o.jsx(Fe,{path:"clients/new",element:o.jsx(yJ,{})}),o.jsx(Fe,{path:"clients",element:o.jsx(gJ,{})}),o.jsx(Fe,{path:"details",element:o.jsx(WT,{})}),o.jsx(Fe,{path:"invite",element:o.jsx(SJ,{})}),o.jsx(Fe,{path:"users",element:o.jsx(MJ,{})}),o.jsx(Fe,{path:"project",element:o.jsx(WT,{})}),o.jsx(Fe,{path:"secrets",element:o.jsx(EJ,{})}),o.jsx(Fe,{path:"sites",element:o.jsx(TJ,{})}),o.jsx(Fe,{path:"members/:membershipId",element:o.jsx(bJ,{})})]}),o.jsx(Fe,{path:"/lab/assays",element:o.jsx(IJ,{})}),o.jsx(Fe,{path:"/lab/panels",element:o.jsx(LJ,{})}),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(QZ,{}),children:[o.jsx(Fe,{index:!0,element:o.jsx(py,{})}),o.jsx(Fe,{path:"form",element:o.jsx(py,{})}),o.jsx(Fe,{path:"json",element:o.jsx(see,{})}),o.jsx(Fe,{path:"profiles",element:o.jsx(py,{})})]}),o.jsxs(Fe,{path:"/:resourceType/:id",element:o.jsx(kee,{}),children:[o.jsx(Fe,{index:!0,element:o.jsx(tR,{})}),o.jsx(Fe,{path:"apply",element:o.jsx($J,{})}),o.jsx(Fe,{path:"apps",element:o.jsx(UJ,{})}),o.jsx(Fe,{path:"event",element:o.jsx(VJ,{})}),o.jsx(Fe,{path:"blame",element:o.jsx(FJ,{})}),o.jsx(Fe,{path:"bots",element:o.jsx(hee,{})}),o.jsx(Fe,{path:"builder",element:o.jsx(ZJ,{})}),o.jsx(Fe,{path:"checklist",element:o.jsx(JJ,{})}),o.jsx(Fe,{path:"delete",element:o.jsx(eee,{})}),o.jsx(Fe,{path:"details",element:o.jsx(ree,{})}),o.jsx(Fe,{path:"edit",element:o.jsx(iee,{})}),o.jsx(Fe,{path:"editor",element:o.jsx(KJ,{})}),o.jsx(Fe,{path:"history",element:o.jsx(oee,{})}),o.jsx(Fe,{path:"json",element:o.jsx(lee,{})}),o.jsx(Fe,{path:"preview",element:o.jsx(cee,{})}),o.jsx(Fe,{path:"responses",element:o.jsx(mee,{})}),o.jsx(Fe,{path:"report",element:o.jsx(vee,{})}),o.jsx(Fe,{path:"ranges",element:o.jsx(gee,{})}),o.jsx(Fe,{path:"subscriptions",element:o.jsx(Pee,{})}),o.jsx(Fe,{path:"timeline",element:o.jsx(tR,{})}),o.jsx(Fe,{path:"tools",element:o.jsx(Mee,{})}),o.jsx(Fe,{path:"profiles",element:o.jsx(uee,{})}),o.jsx(Fe,{path:"export",element:o.jsx(aee,{})})]}),o.jsx(Fe,{path:"/:resourceType",element:o.jsx(QT,{})}),o.jsx(Fe,{path:"/",element:o.jsx(QT,{})})]})})}function Lee(){const e=_e(),t=e.getUserConfiguration(),n=Mr(),[r]=Jb();return e.isLoading()?o.jsx(gi,{}):o.jsx(yH,{logo:o.jsx(Ui,{size:24}),pathname:n.pathname,searchParams:r,version:FA,menus:zee(t),displayAddBookmark:!!(t!=null&&t.id),children:o.jsx(v.Suspense,{fallback:o.jsx(gi,{}),children:o.jsx(Iee,{})})})}function zee(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:$ee(s.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:o.jsx(oF,{})}]}),t}const nR={Patient:SF,Practitioner:iF,Organization:WV,ServiceRequest:mF,DiagnosticReport:vF,Questionnaire:rF,admin:qV,AccessPolicy:aF,Subscription:EF,batch:dF,Observation:cF};function $ee(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 Uee(){const e=Vd(),t=new HA({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=LX([{path:"*",element:o.jsx(Lee,{})}]),i=c=>r.navigate(c);UY.createRoot(document.getElementById("root")).render(o.jsx(v.StrictMode,{children:o.jsx(TV,{medplum:t,navigate:i,children:o.jsxs(RR,{theme:n,children:[o.jsx(Za,{position:"bottom-right"}),o.jsx(lX,{router:r})]})})}))}Uee().catch(console.error);
|
|
586
|
+
//# sourceMappingURL=index-CYUp9CLo.js.map
|