@medplum/app 4.4.3 → 4.5.0

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.
@@ -84,7 +84,7 @@ function F3(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
84
84
  *
85
85
  * Copy of "partysocket" from Partykit team, a fork of the original "Reconnecting WebSocket"
86
86
  * https://github.com/partykit/partykit/blob/main/packages/partysocket
87
- */const Ec={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let XE=!1;function IV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Ec.Event=globalThis.Event,Ec.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Ec.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function zV(e,t){if(!e)throw new Error(t)}function Sh(e){return new e.constructor(e.type,e)}const $s={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let ZE=!1;class Za extends vm{constructor(t,n,r={}){XE||(IV(),XE=!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=o=>{this._debug("open event");const{minUptime:l=$s.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),l),zV(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(c=>this._ws?.send(c)),this._messageQueue=[],this.onopen&&this.onopen(o),this.dispatchEvent(Sh(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(Sh(o))},this._handleError=o=>{this._debug("error event",o.message),this._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(o),this._debug("exec error listeners"),this.dispatchEvent(Sh(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(Sh(o))},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 Za.CONNECTING}get OPEN(){return Za.OPEN}get CLOSING(){return Za.CLOSING}get CLOSED(){return Za.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,r)=>(typeof r=="string"?n+=r.length:r instanceof Blob?n+=r.size:n+=r.byteLength,n),0)+(this._ws?.bufferedAmount??0)}get extensions(){return this._ws?.extensions??""}get protocol(){return this._ws?.protocol??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?Za.CLOSED:Za.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=$s.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=$s.reconnectionDelayGrowFactor,minReconnectionDelay:n=$s.minReconnectionDelay,maxReconnectionDelay:r=$s.maxReconnectionDelay}=this._options;let o=0;return this._retryCount>0&&(o=n*Math.pow(t,this._retryCount-1),o>r&&(o=r)),this._debug("next delay",o),o}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=$s.maxRetries,connectionTimeout:n=$s.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"&&!ZE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),ZE=!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 Ec.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Ec.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Ec.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 $V=5e3;class ux extends vm{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 UV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new ux(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class BV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof bA))throw new ft(gn("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new ft(gn("Not a valid URL"))}const l=r?.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger}):new Za(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger});this.medplum=t,this.ws=l,this.masterSubEmitter=new ux,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=r?.pingIntervalMs??$V,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{try{const r=JSON.parse(n.data);if(r.type==="pong"){this.waitingForPong=!1;return}const o=r,l=o?.entry?.[0]?.resource;if(l.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:o});return}if(l.type==="handshake"){const d=rl(l.subscription),f={type:"connect",payload:{subscriptionId:d}};this.masterSubEmitter?.dispatchEvent(f);const p=this.criteriaEntriesBySubscriptionId.get(d);if(!p){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}p.connecting=!1,p.emitter.dispatchEvent({...f});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:o});const c=this.criteriaEntriesBySubscriptionId.get(rl(l.subscription));if(!c){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}c.emitter.dispatchEvent({type:"message",payload:o})}catch(r){console.error(r);const o={type:"error",payload:r};this.masterSubEmitter?.dispatchEvent(o);for(const l of this.getAllCriteriaEmitters())l.dispatchEvent({...o})}}),t.addEventListener("error",()=>{const n={type:"error",payload:new ft(K$(new Error("WebSocket error")))};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n})}),t.addEventListener("close",()=>{const n={type:"close"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),t.addEventListener("open",()=>{const n={type:"open"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&this.currentProfile?.id!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){const r={type:"error",payload:n};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){const{subscriptionId:n}=t;if(n){const r={type:"disconnect",payload:{subscriptionId:n}};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){let n=t?.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${_t(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),o=r?.find(c=>c.name==="token")?.valueString,l=r?.find(c=>c.name==="websocket-url")?.valueUrl;if(!o)throw new ft(gn("Failed to get token"));if(!l)throw new ft(gn("Failed to get URL from $get-ws-binding-token"));return[n,o]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const o of r.criteriaWithProps)if(Co(n,o.subscriptionProps))return o}}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 o;this.criteriaEntries.has(n)?o=this.criteriaEntries.get(n):(o={criteriaWithProps:[]},this.criteriaEntries.set(n,o)),r?o.criteriaWithProps.push(t):o.bareCriteria=t}removeCriteriaEntry(t){const{criteria:n,subscriptionProps:r,subscriptionId:o,token:l}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(d=>{const f=d.subscriptionProps;return!Co(r,f)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),this.masterSubEmitter?._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),l&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:l}}))}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 o=new UV(t,n);return this.addCriteriaEntry(o),this.subscribeToCriteria(o).catch(console.error),o.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 ux(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const xA="4.4.3-216abf674",VV=ln.FHIR_JSON+", */*; q=0.1",FV="https://api.medplum.com/",HV=1e3,qV=6e4,GV=0,QV=3e5,WV="Binary/",JE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},vc={ClientCredentials:"client_credentials",AuthorizationCode:"authorization_code",RefreshToken:"refresh_token",JwtBearer:"urn:ietf:params:oauth:grant-type:jwt-bearer",TokenExchange:"urn:ietf:params:oauth:grant-type:token-exchange"},YV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},KV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class bA extends vm{constructor(t){if(super(),this.initComplete=!0,t?.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=t?.fetch??XV(),this.storage=t?.storage??new MV,this.createPdfImpl=t?.createPdf,this.baseUrl=wb(t?.baseUrl??FV),this.fhirBaseUrl=fo(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=fo(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=fo(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=fo(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=fo(this.baseUrl,t?.fhircastHubUrl??"fhircast/STU3"),this.clientId=t?.clientId??"",this.clientSecret=t?.clientSecret??"",this.credentialsInHeader=t?.authCredentialsMethod==="header",this.defaultHeaders=t?.defaultHeaders??{},this.onUnauthenticated=t?.onUnauthenticated,this.refreshGracePeriod=t?.refreshGracePeriod??QV,this.cacheTime=t?.cacheTime??(po()?qV:GV),this.cacheTime>0?this.requestCache=new AD(t?.resourceCacheSize??HV):this.requestCache=void 0,t?.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t?.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}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(),po()&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),this.requestCache?.delete(t)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(t){const n=fo(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 o;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?o=new Promise((c,d)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:d}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const l=new Fi(o);return this.setCacheEntry(t,l),l}post(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("POST",t,o)}put(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("PUT",t,o)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,ln.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:o}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:o},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(Xn.getSearch()).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){Xn.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,o,l=!0){let c=o;l&&(c=await this.ensureCodeChallenge(o)),Xn.assign(this.getExternalAuthRedirectUri(t,n,r,c,l))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:vc.TokenExchange,subject_token_type:YV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,o,l=!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",o.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(o)),l){const{codeChallenge:d,codeChallengeMethod:f}=o;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!d)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",d)}return c.toString()}fhirUrl(...t){return new URL(fo(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=VU(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),l="search-"+o.toString(),c=this.getCacheEntry(l,r);if(c)return c.value;const d=this.getBundle(o,r);return this.setCacheEntry(l,d),d}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const l="searchOne-"+o.toString(),c=this.getCacheEntry(l,r);if(c)return c.value;const d=new Fi(this.search(t,o.searchParams,r).then(f=>f.entry?.[0]?.resource));return this.setCacheEntry(l,d),d}searchResources(t,n,r){const l="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(l,r);if(c)return c.value;const d=new Fi(this.search(t,n,r).then(tT));return this.setCacheEntry(l,d),d}async*searchResourcePages(t,n,r){let o=this.fhirSearchUrl(t,n);for(;o;){const l=new URL(o).searchParams;l.has("_count")||l.set("_count","1000");const c=await this.search(t,l,r),d=c.link?.find(f=>f.relation==="next");if(!c.entry?.length&&!d)break;yield tT(c),o=d?.url?new URL(d.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){const r=this.requestCache?.get(this.fhirUrl(t,n).toString())?.value;return r?.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return JE;const[r,o]=n.split("/");if(!(!r||!o))return this.getCached(r,o)}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 Fi(Promise.reject(new Error("Missing reference")));if(r==="system")return new Fi(Promise.resolve(JE));const[o,l]=r.split("/");return!o||!l?new Fi(Promise.reject(new Error("Invalid reference"))):this.readResource(o,l,n)}requestSchema(t){if(ID(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Fi((async()=>{const l=`{
87
+ */const Ec={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let XE=!1;function IV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Ec.Event=globalThis.Event,Ec.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Ec.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function zV(e,t){if(!e)throw new Error(t)}function Sh(e){return new e.constructor(e.type,e)}const $s={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let ZE=!1;class Za extends vm{constructor(t,n,r={}){XE||(IV(),XE=!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=o=>{this._debug("open event");const{minUptime:l=$s.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),l),zV(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(c=>this._ws?.send(c)),this._messageQueue=[],this.onopen&&this.onopen(o),this.dispatchEvent(Sh(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(Sh(o))},this._handleError=o=>{this._debug("error event",o.message),this._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(o),this._debug("exec error listeners"),this.dispatchEvent(Sh(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(Sh(o))},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 Za.CONNECTING}get OPEN(){return Za.OPEN}get CLOSING(){return Za.CLOSING}get CLOSED(){return Za.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,r)=>(typeof r=="string"?n+=r.length:r instanceof Blob?n+=r.size:n+=r.byteLength,n),0)+(this._ws?.bufferedAmount??0)}get extensions(){return this._ws?.extensions??""}get protocol(){return this._ws?.protocol??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?Za.CLOSED:Za.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=$s.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=$s.reconnectionDelayGrowFactor,minReconnectionDelay:n=$s.minReconnectionDelay,maxReconnectionDelay:r=$s.maxReconnectionDelay}=this._options;let o=0;return this._retryCount>0&&(o=n*Math.pow(t,this._retryCount-1),o>r&&(o=r)),this._debug("next delay",o),o}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=$s.maxRetries,connectionTimeout:n=$s.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"&&!ZE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),ZE=!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 Ec.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Ec.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Ec.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 $V=5e3;class ux extends vm{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 UV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new ux(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class BV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof bA))throw new ft(gn("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new ft(gn("Not a valid URL"))}const l=r?.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger}):new Za(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger});this.medplum=t,this.ws=l,this.masterSubEmitter=new ux,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=r?.pingIntervalMs??$V,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{try{const r=JSON.parse(n.data);if(r.type==="pong"){this.waitingForPong=!1;return}const o=r,l=o?.entry?.[0]?.resource;if(l.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:o});return}if(l.type==="handshake"){const d=rl(l.subscription),f={type:"connect",payload:{subscriptionId:d}};this.masterSubEmitter?.dispatchEvent(f);const p=this.criteriaEntriesBySubscriptionId.get(d);if(!p){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}p.connecting=!1,p.emitter.dispatchEvent({...f});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:o});const c=this.criteriaEntriesBySubscriptionId.get(rl(l.subscription));if(!c){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}c.emitter.dispatchEvent({type:"message",payload:o})}catch(r){console.error(r);const o={type:"error",payload:r};this.masterSubEmitter?.dispatchEvent(o);for(const l of this.getAllCriteriaEmitters())l.dispatchEvent({...o})}}),t.addEventListener("error",()=>{const n={type:"error",payload:new ft(K$(new Error("WebSocket error")))};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n})}),t.addEventListener("close",()=>{const n={type:"close"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),t.addEventListener("open",()=>{const n={type:"open"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&this.currentProfile?.id!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){const r={type:"error",payload:n};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){const{subscriptionId:n}=t;if(n){const r={type:"disconnect",payload:{subscriptionId:n}};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){let n=t?.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${_t(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),o=r?.find(c=>c.name==="token")?.valueString,l=r?.find(c=>c.name==="websocket-url")?.valueUrl;if(!o)throw new ft(gn("Failed to get token"));if(!l)throw new ft(gn("Failed to get URL from $get-ws-binding-token"));return[n,o]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const o of r.criteriaWithProps)if(Co(n,o.subscriptionProps))return o}}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 o;this.criteriaEntries.has(n)?o=this.criteriaEntries.get(n):(o={criteriaWithProps:[]},this.criteriaEntries.set(n,o)),r?o.criteriaWithProps.push(t):o.bareCriteria=t}removeCriteriaEntry(t){const{criteria:n,subscriptionProps:r,subscriptionId:o,token:l}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(d=>{const f=d.subscriptionProps;return!Co(r,f)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),this.masterSubEmitter?._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),l&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:l}}))}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 o=new UV(t,n);return this.addCriteriaEntry(o),this.subscribeToCriteria(o).catch(console.error),o.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 ux(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const xA="4.5.0-e2f7d4ec4",VV=ln.FHIR_JSON+", */*; q=0.1",FV="https://api.medplum.com/",HV=1e3,qV=6e4,GV=0,QV=3e5,WV="Binary/",JE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},vc={ClientCredentials:"client_credentials",AuthorizationCode:"authorization_code",RefreshToken:"refresh_token",JwtBearer:"urn:ietf:params:oauth:grant-type:jwt-bearer",TokenExchange:"urn:ietf:params:oauth:grant-type:token-exchange"},YV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},KV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class bA extends vm{constructor(t){if(super(),this.initComplete=!0,t?.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=t?.fetch??XV(),this.storage=t?.storage??new MV,this.createPdfImpl=t?.createPdf,this.baseUrl=wb(t?.baseUrl??FV),this.fhirBaseUrl=fo(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=fo(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=fo(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=fo(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=fo(this.baseUrl,t?.fhircastHubUrl??"fhircast/STU3"),this.clientId=t?.clientId??"",this.clientSecret=t?.clientSecret??"",this.credentialsInHeader=t?.authCredentialsMethod==="header",this.defaultHeaders=t?.defaultHeaders??{},this.onUnauthenticated=t?.onUnauthenticated,this.refreshGracePeriod=t?.refreshGracePeriod??QV,this.cacheTime=t?.cacheTime??(po()?qV:GV),this.cacheTime>0?this.requestCache=new AD(t?.resourceCacheSize??HV):this.requestCache=void 0,t?.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t?.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}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(),po()&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),this.requestCache?.delete(t)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(t){const n=fo(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 o;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?o=new Promise((c,d)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:d}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const l=new Fi(o);return this.setCacheEntry(t,l),l}post(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("POST",t,o)}put(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("PUT",t,o)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,ln.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:o}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:o},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(Xn.getSearch()).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){Xn.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,o,l=!0){let c=o;l&&(c=await this.ensureCodeChallenge(o)),Xn.assign(this.getExternalAuthRedirectUri(t,n,r,c,l))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:vc.TokenExchange,subject_token_type:YV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,o,l=!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",o.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(o)),l){const{codeChallenge:d,codeChallengeMethod:f}=o;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!d)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",d)}return c.toString()}fhirUrl(...t){return new URL(fo(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=VU(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),l="search-"+o.toString(),c=this.getCacheEntry(l,r);if(c)return c.value;const d=this.getBundle(o,r);return this.setCacheEntry(l,d),d}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const l="searchOne-"+o.toString(),c=this.getCacheEntry(l,r);if(c)return c.value;const d=new Fi(this.search(t,o.searchParams,r).then(f=>f.entry?.[0]?.resource));return this.setCacheEntry(l,d),d}searchResources(t,n,r){const l="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(l,r);if(c)return c.value;const d=new Fi(this.search(t,n,r).then(tT));return this.setCacheEntry(l,d),d}async*searchResourcePages(t,n,r){let o=this.fhirSearchUrl(t,n);for(;o;){const l=new URL(o).searchParams;l.has("_count")||l.set("_count","1000");const c=await this.search(t,l,r),d=c.link?.find(f=>f.relation==="next");if(!c.entry?.length&&!d)break;yield tT(c),o=d?.url?new URL(d.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){const r=this.requestCache?.get(this.fhirUrl(t,n).toString())?.value;return r?.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return JE;const[r,o]=n.split("/");if(!(!r||!o))return this.getCached(r,o)}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 Fi(Promise.reject(new Error("Missing reference")));if(r==="system")return new Fi(Promise.resolve(JE));const[o,l]=r.split("/");return!o||!l?new Fi(Promise.reject(new Error("Invalid reference"))):this.readResource(o,l,n)}requestSchema(t){if(ID(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Fi((async()=>{const l=`{
88
88
  StructureDefinitionList(_filter: "name eq ${t}") {
89
89
  resourceType,
90
90
  name,
@@ -542,7 +542,7 @@ function F3(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
542
542
  display
543
543
  }
544
544
  }
545
- }`.replace(/\s+/g," ")}function PG(e,t){const n=[];return e.data.Patients1&&n.push(...e.data.Patients1),e.data.Patients2&&n.push(...e.data.Patients2),e.data.ServiceRequestList&&n.push(...e.data.ServiceRequestList),NG(kG(n),t).slice(0,5)}function kG(e){const t=new Set,n=[];for(const r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function NG(e,t){return e.sort((n,r)=>mT(r,t)-mT(n,t))}function mT(e,t){let n=0;if(e.identifier)for(const r of e.identifier)n=Math.max(n,gT(r.value,t));if(e.resourceType==="Patient"&&e.name)for(const r of e.name)n=Math.max(n,gT(Jc(r),t));return n}function gT(e,t){if(!e)return 0;const n=e.toLowerCase().indexOf(t.toLowerCase());return n<0?0:100-n}function OG(e){const t=Sm(),[n,r]=v.useState(!1);return a.jsx(Vr.Header,{p:8,style:{zIndex:101},children:a.jsxs(ye,{justify:"space-between",children:[a.jsxs(ye,{gap:"xs",children:[a.jsx(sr,{className:wh.logoButton,onClick:e.navbarToggle,children:e.logo}),!e.headerSearchDisabled&&a.jsx(_G,{pathname:e.pathname,searchParams:e.searchParams})]}),a.jsxs(ye,{gap:"lg",pr:"sm",children:[e.notifications,a.jsxs(je,{width:260,shadow:"xl",position:"bottom-end",transitionProps:{transition:"pop-top-right"},opened:n,onClose:()=>r(!1),children:[a.jsx(je.Target,{children:a.jsx(sr,{className:Ot(wh.user,{[wh.userActive]:n}),onClick:()=>r(o=>!o),children:a.jsxs(ye,{gap:7,children:[a.jsx(gs,{value:t,radius:"xl",size:24}),a.jsx(Te,{size:"sm",className:wh.userName,children:Jc(t?.name?.[0])}),a.jsx(zb,{size:12,stroke:1.5})]})})}),a.jsx(je.Dropdown,{children:a.jsx(bG,{version:e.version})})]})]})]})})}const qb=v.createContext({submitting:!1});qb.displayName="FormContext";function MG(e){const t={};for(const n of Array.from(e.elements))n instanceof HTMLInputElement?LG(t,n):n instanceof HTMLTextAreaElement?t[n.name]=n.value:n instanceof HTMLSelectElement&&IG(t,n);return t}function LG(e,t){t.disabled||(t.type==="checkbox"||t.type==="radio")&&!t.checked||(e[t.name]=t.value)}function IG(e,t){e[t.name]=t.value}function ut(e){const[t,n]=v.useState(!1);return a.jsx(qb.Provider,{value:{submitting:t},children:a.jsx("form",{style:e.style,"data-testid":e.testid,onSubmit:r=>{r.preventDefault();const o=MG(r.target);if(e.onSubmit){n(!0);const l=e.onSubmit(o);l?.then?l.catch(console.error).finally(()=>{n(!1)}):n(!1)}},children:e.children})})}function vr(e){const{children:t,...n}=e,{submitting:r}=v.useContext(qb);return a.jsx(ke,{type:"submit",loading:r,...n,children:t})}function zG(e){const t=Re(),n=t.getUserConfiguration();function r(o){const{menuname:l,bookmarkname:c}=o,d=`${e.pathname}?${e.searchParams.toString()}`,f=ii(n);f.menu?.find(({title:m})=>m===l)?.link?.push({name:c,target:d}),t.updateResource(f).then(m=>{n.menu=m.menu,t.dispatchEvent({type:"change"}),Ne({color:"green",message:"Success"}),e.onOk()}).catch(m=>{Ne({color:"red",message:Ye(m)})})}return a.jsx(Un,{title:"Add Bookmark",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:e.onCancel,children:a.jsx(ut,{onSubmit:r,children:a.jsxs(Be,{children:[a.jsx($G,{config:n}),a.jsx(Ve,{label:"Bookmark Name",type:"text",name:"bookmarkname",placeholder:"Bookmark Name",withAsterisk:!0}),a.jsx(ye,{justify:"flex-end",children:a.jsx(vr,{mt:"sm",children:"OK"})})]})})})}function $G(e){function t(r){return r?.menu?.map(o=>o.title)}const n=t(e.config);return a.jsx(on,{name:"menuname",defaultValue:n[0],label:"Select Menu Option",data:n,withAsterisk:!0})}function QA(e){return typeof e.code=="string"?e.code:JSON.stringify(e)}function UG(e){return typeof e.display=="string"?e.display:QA(e)}function BG(e){return{value:QA(e),label:UG(e),resource:e}}function VG(e){return{code:e,display:e}}function jm(e){const t=Re(),{binding:n,creatable:r,clearable:o,expandParams:l,withHelpText:c,...d}=e,f=v.useCallback(async(p,m)=>{if(!n)return[];const x=(await t.valueSetExpand({...l,url:n,filter:p,count:10},{signal:m})).expansion?.contains??[],b=[];for(const w of x)w.code&&!b.some(j=>j.code===w.code)&&b.push(w);return b},[t,l,n]);return a.jsx(Hb,{...d,creatable:r??!0,clearable:o??!0,toOption:BG,loadOptions:f,onCreate:VG,itemComponent:c?FG:void 0})}const FG=v.forwardRef(({label:e,resource:t,active:n,...r},o)=>a.jsx("div",{ref:o,...r,children:a.jsxs(ye,{wrap:"nowrap",gap:"xs",children:[n&&a.jsx(Po,{size:12}),a.jsxs("div",{children:[a.jsx(Te,{children:e}),a.jsx(Te,{size:"xs",c:"dimmed",children:`${t.system}#${t.code}`})]})]})}));function WA(e){const{defaultValue:t,onChange:n,withHelpText:r,...o}=e,[l,c]=v.useState(t);function d(f){const p=f[0],m=qG(p);c(m),n&&n(m)}return a.jsx(jm,{defaultValue:HG(l),onChange:d,withHelpText:r??!0,...o})}function HG(e){return e?{code:e}:void 0}function qG(e){return e?.code}function Gb(e){const[t,n]=v.useState(e.defaultValue),r=e.onChange,o=v.useCallback(l=>{n(l),r&&r(l)},[r]);return a.jsx(WA,{disabled:e.disabled,"data-autofocus":e.autoFocus,"data-testid":e.testId,defaultValue:t,onChange:o,name:e.name,placeholder:e.placeholder,binding:"https://medplum.com/fhir/ValueSet/resource-types",creatable:!1,maxValues:e.maxValues??1,clearable:!1,withHelpText:!1})}const GG="_menuTitle_9g6l5_1",QG="_link_9g6l5_9",WG="_linkActive_9g6l5_38",mx={menuTitle:GG,link:QG,linkActive:WG};function YG(e){const t=bm(),n=ZG(e.pathname,e.searchParams,e.menus),[r,o]=v.useState(!1);function l(d,f){d.stopPropagation(),d.preventDefault(),t(f),window.innerWidth<768&&e.closeNavbar()}function c(d){d&&t(`/${d}`)}return a.jsxs(a.Fragment,{children:[a.jsx(Vr.Navbar,{children:a.jsxs(ai,{p:"xs",children:[!e.resourceTypeSearchDisabled&&a.jsx(Vr.Section,{mb:"sm",children:a.jsx(Gb,{name:"resourceType",placeholder:"Resource Type",maxValues:0,onChange:d=>c(d)},window.location.pathname)}),a.jsxs(Vr.Section,{grow:!0,children:[e.menus?.map(d=>a.jsxs(v.Fragment,{children:[a.jsx(Te,{className:mx.menuTitle,children:d.title}),d.links?.map(f=>a.jsxs(KG,{to:f.href,active:f.href===n?.href,onClick:p=>l(p,f.href),children:[a.jsx(XG,{icon:f.icon}),a.jsx("span",{children:f.label})]},f.href))]},`menu-${d.title}`)),e.displayAddBookmark&&a.jsx(ke,{variant:"subtle",size:"xs",mt:"xl",leftSection:a.jsx(UA,{size:"0.75rem"}),onClick:()=>o(!0),children:"Add Bookmark"})]})]})}),e.pathname&&e.searchParams&&a.jsx(zG,{pathname:e.pathname,searchParams:e.searchParams,visible:r,onOk:()=>o(!1),onCancel:()=>o(!1)})]})}function KG(e){return a.jsx(mt,{onClick:e.onClick,to:e.to,className:Ot(mx.link,{[mx.linkActive]:e.active}),children:e.children})}function XG(e){return e.icon?e.icon:a.jsx(cm,{w:30})}function ZG(e,t,n){if(!e||!t||!n)return;let r,o=0;for(const l of n)if(l.links)for(const c of l.links){const d=JG(e,t,c.href);d>o&&(o=d,r=c)}return r}function JG(e,t,n){const r=new URL(n,"https://example.com");if(e!==r.pathname)return 0;const o=["_count","_offset"];for(const[c,d]of r.searchParams.entries())if(!o.includes(c)&&t.get(c)!==d)return 0;let l=1;for(const[c,d]of t.entries())o.includes(c)||r.searchParams.get(c)===d&&l++;return l}function eQ(e){const[t,n]=v.useState(localStorage.navbarOpen==="true"),r=Re(),o=Sm();v.useEffect(()=>{function f(){Ne({id:"offline",color:"red",message:"No connection to server",autoClose:!1})}return r.addEventListener("offline",f),()=>r.removeEventListener("offline",f)},[r]);function l(f){localStorage.navbarOpen=f.toString(),n(f)}function c(){l(!1)}function d(){l(!t)}return r.isLoading()?a.jsx(Di,{}):a.jsxs(Vr,{header:{height:60},navbar:{width:250,breakpoint:"sm",collapsed:{desktop:!o||!t,mobile:!o||!t}},padding:0,children:[o&&a.jsx(OG,{pathname:e.pathname,searchParams:e.searchParams,headerSearchDisabled:e.headerSearchDisabled,logo:e.logo,version:e.version,navbarToggle:d,notifications:e.notifications}),o&&t?a.jsx(YG,{pathname:e.pathname,searchParams:e.searchParams,menus:e.menus,closeNavbar:c,displayAddBookmark:e.displayAddBookmark,resourceTypeSearchDisabled:e.resourceTypeSearchDisabled}):void 0,a.jsx(Vr.Main,{className:uG.main,children:a.jsx(VA,{children:a.jsx(v.Suspense,{fallback:a.jsx(Di,{}),children:e.children})})})]})}const tQ="https://ccda.medplum.com",nQ="https://ccda-validator.medplum.com/";function rQ(e){const{url:t}=e,[n,r]=v.useState(!1),o=v.useRef(null),[l,c]=v.useState(),[d,f]=v.useState(!1);v.useEffect(()=>{t&&n&&o.current&&(id(o.current,{command:"loadCcdaXml",value:t}).catch(console.error),r(!1))},[t,n]);const p=async()=>{if(t)try{f(!0);const b=await(await fetch(t)).text(),w=new FormData;w.append("ccdaFile",new Blob([b],{type:"text/xml"}),"ccda.xml");const j=`${nQ}referenceccdaservice/?validationObjective=C-CDA_IG_Plus_Vocab&referenceFileName=No%20scenario%20File&curesUpdate=true&severityLevel=WARNING`,C=await fetch(j,{method:"POST",body:w,credentials:"omit",redirect:"manual"});if(!C.ok)throw new Error(`Validation failed: ${C.status} ${C.statusText}`);const T=await C.json();c(T)}catch(x){c(void 0),console.error("CCDA validation error:",x)}finally{f(!1)}},m=()=>{if(!l)return;const x=JSON.stringify(l,null,2);qA(x,"ccda-validation-results")},g=()=>l?l.resultsMetaData.resultMetaData.filter(x=>x?.type.includes("Error")).reduce((x,b)=>x+(b.count||0),0):0;return t?a.jsxs("div",{"data-testid":"ccda-iframe",style:{maxWidth:e.maxWidth},children:[a.jsx("div",{style:{minHeight:400},children:a.jsx("iframe",{title:"C-CDA Viewer",width:"100%",height:"400",ref:o,src:tQ,allowFullScreen:!0,frameBorder:0,seamless:!0,onLoad:()=>r(!0)})}),a.jsxs("div",{style:{marginTop:"10px",marginBottom:"10px",display:"flex",alignItems:"center"},children:[a.jsx(ke,{type:"button",onClick:p,disabled:d,children:d?"Validating...":"Validate"}),l&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{style:{marginLeft:"15px"},children:[a.jsx("strong",{children:"Validation Results:"})," ",g()," errors found"]}),a.jsx(ke,{type:"button",onClick:m,color:"green",style:{marginLeft:"auto"},children:"Download Full Results"})]})]})]}):null}function Qd(e){const{contentType:t,url:n,title:r}=e.value??{},o=TA(n);return o?a.jsxs("div",{"data-testid":"attachment-display",children:[t?.startsWith("image/")&&a.jsx("img",{"data-testid":"attachment-image",style:{maxWidth:e.maxWidth},src:o,alt:r}),t?.startsWith("video/")&&a.jsx("video",{"data-testid":"attachment-video",style:{maxWidth:e.maxWidth},controls:!0,children:a.jsx("source",{type:t,src:o})}),(t?.startsWith("text/")||t==="application/json"||t==="application/pdf")&&a.jsx("div",{"data-testid":"attachment-iframe",style:{maxWidth:e.maxWidth,minHeight:400},children:a.jsx("iframe",{title:"Attachment",width:"100%",height:"400",src:o+"#navpanes=0",allowFullScreen:!0,frameBorder:0,seamless:!0})}),t===ln.CDA_XML&&a.jsx(rQ,{url:o}),a.jsx("div",{"data-testid":"download-link",style:{padding:"2px 16px 16px 16px"},children:a.jsx(Dt,{href:n,"data-testid":"attachment-details",target:"_blank",rel:"noopener noreferrer",download:iQ(r),children:r||"Download"})})]}):null}function iQ(e){return e?.includes(".")?e:void 0}const oQ="_root_17n8t_1",aQ="_compact_17n8t_25",vT={root:oQ,compact:aQ};function Cm(e){const{children:t,compact:n}=e;return a.jsx("dl",{className:Ot(vT.root,{[vT.compact]:n}),children:t})}function Ti(e){return a.jsxs(a.Fragment,{children:[a.jsx("dt",{children:e.term}),a.jsx("dd",{children:e.children})]})}function sQ(e){const t=e.values?.map((r,o)=>a.jsx("div",{children:a.jsx(Qd,{value:r,maxWidth:e.maxWidth})},"attatchment-"+o));let n;if(e.includeDescriptionListEntry){if(e.property===void 0)throw new Error("props.property is required when includeDescriptionListEntry is true");if(!Rn(e.path))throw new Error("props.path is required when includeDescriptionListEntry is true");const r=e.path.split(".").pop();n=a.jsx(Ti,{term:ol(r),children:t})}else n=a.jsx(a.Fragment,{children:t});return n}function Qb(e){const t=Re(),n=v.useRef(null);function r(c){cn(c),n.current?.click()}function o(c){cn(c);const d=c.target.files;d&&Array.from(d).forEach(l)}function l(c){!c||!c.name||(e.onUploadStart&&e.onUploadStart(),t.createAttachment({data:c,contentType:c.type||"application/octet-stream",filename:c.name,securityContext:e.securityContext,onProgress:e.onUploadProgress}).then(f=>e.onUpload(f)).catch(f=>{e.onUploadError&&e.onUploadError(qt(f))}))}return a.jsxs(a.Fragment,{children:[a.jsx("input",{disabled:e.disabled,type:"file","data-testid":"upload-file-input",style:{display:"none"},ref:n,onChange:c=>o(c)}),e.children({onClick:r,disabled:e.disabled})]})}function lQ(e){const[t,n]=v.useState(e.defaultValue??[]),r=v.useRef(t);r.current=t;function o(l){n(l),e.onChange&&e.onChange(l)}return a.jsxs("table",{style:{width:"100%"},children:[a.jsxs("colgroup",{children:[a.jsx("col",{width:"97%"}),a.jsx("col",{width:"3%"})]}),a.jsxs("tbody",{children:[t.map((l,c)=>a.jsxs("tr",{children:[a.jsx("td",{children:a.jsx(Qd,{value:l,maxWidth:200})}),a.jsx("td",{children:a.jsx(bn,{disabled:e.disabled,title:"Remove",variant:"subtle",size:"sm",color:"gray",onClick:d=>{cn(d);const f=t.slice();f.splice(c,1),o(f)},children:a.jsx(lp,{})})})]},`${c}-${t.length}`)),a.jsxs("tr",{children:[a.jsx("td",{}),a.jsx("td",{children:a.jsx(Qb,{disabled:e.disabled,onUpload:l=>{o([...r.current,l])},children:l=>a.jsx(bn,{...l,title:"Add",variant:"subtle",size:"sm",color:l.disabled?"gray":"green",children:a.jsx($b,{})})})})]})]})]})}function YA(e){const[t,n]=v.useState(e.defaultValue);function r(o){n(o),e.onChange&&e.onChange(o)}return t?a.jsxs(a.Fragment,{children:[a.jsx(Qd,{value:t,maxWidth:200}),a.jsx(ke,{disabled:e.disabled,onClick:o=>{cn(o),r(void 0)},children:"Remove"})]}):a.jsx(Qb,{disabled:e.disabled,securityContext:e.securityContext,onUpload:r,children:o=>a.jsx(ke,{...o,children:"Upload..."})})}function Mi(e){return a.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 180 180",style:{width:e.size,height:e.size},children:[a.jsx("title",{children:"Medplum Logo"}),a.jsx("path",{fill:e.fill??"#9c36b5",d:"M84 56c-3-15-15-24-23-28l5-10c8 2 14 8 20 14 0-12 1-16 5-21 8-9 13-9 41-9 0 7 1 18-3 24-7 9-16 7-41 8 5 8 7 14 8 22 36-24 74-7 74 39 0 42-40 83-80 83s-80-41-80-83c0-46 38-63 74-39Zm-3 43H65c-4 0-7 3-7 7v4c0 4 3 7 7 7h16v16c0 4 3 7 7 7h4c4 0 7-3 7-7v-16h16c4 0 7-3 7-7v-4c0-4-3-7-7-7H99V83c0-4-3-7-7-7h-4c-4 0-7 3-7 7z"})]})}function up(e){const[t,n]=v.useState();return a.jsx(ut,{onSubmit:r=>{n(void 0),e.onSubmit(r)?.catch(o=>n(Ye(o)))},children:a.jsxs(Be,{children:[a.jsxs(ar,{style:{flexDirection:"column"},children:[a.jsx(Mi,{size:32}),a.jsx(Ie,{children:e.title})]}),t&&a.jsx(ya,{icon:a.jsx(bl,{size:16}),title:"Error",color:"red",children:t}),e.qrCodeUrl&&a.jsxs(Be,{align:"center",children:[a.jsx(Te,{children:"Scan this QR code with your authenticator app."}),a.jsx("img",{src:e.qrCodeUrl,alt:"Multi Factor Auth QR Code"})]}),a.jsx(Be,{children:a.jsx(Ve,{name:"token",label:"MFA code",required:!0,autoFocus:!0})}),a.jsx(ye,{justify:"flex-end",mt:"xl",children:a.jsx(vr,{children:e.buttonText})})]})})}const cQ="_root_1vii2_1",uQ={root:cQ};function eu(e){const{children:t,...n}=e;return a.jsx(kd,{className:uQ.root,...n,children:t})}const dQ="_paper_1igaj_1",fQ="_fill_1igaj_20",yT={paper:dQ,fill:fQ};function Sl(e){const{width:t,fill:n,className:r,children:o,...l}=e,c=t?{maxWidth:t}:void 0;return a.jsx(Tr,{className:Ot(yT.paper,n&&yT.fill,r),style:c,shadow:"sm",radius:"sm",withBorder:!0,...l,children:o})}function lt(e){const{children:t,...n}=e;return a.jsx(eu,{children:a.jsx(Sl,{...n,children:t})})}function At(e,t){return e?.issue?.filter(n=>KA(n.expression?.[0],t))?.map(n=>n.details?.text)?.join(`
545
+ }`.replace(/\s+/g," ")}function PG(e,t){const n=[];return e.data.Patients1&&n.push(...e.data.Patients1),e.data.Patients2&&n.push(...e.data.Patients2),e.data.ServiceRequestList&&n.push(...e.data.ServiceRequestList),NG(kG(n),t).slice(0,5)}function kG(e){const t=new Set,n=[];for(const r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function NG(e,t){return e.sort((n,r)=>mT(r,t)-mT(n,t))}function mT(e,t){let n=0;if(e.identifier)for(const r of e.identifier)n=Math.max(n,gT(r.value,t));if(e.resourceType==="Patient"&&e.name)for(const r of e.name)n=Math.max(n,gT(Jc(r),t));return n}function gT(e,t){if(!e)return 0;const n=e.toLowerCase().indexOf(t.toLowerCase());return n<0?0:100-n}function OG(e){const t=Sm(),[n,r]=v.useState(!1);return a.jsx(Vr.Header,{p:8,style:{zIndex:101},children:a.jsxs(ye,{justify:"space-between",children:[a.jsxs(ye,{gap:"xs",children:[a.jsx(sr,{className:wh.logoButton,onClick:e.navbarToggle,children:e.logo}),!e.headerSearchDisabled&&a.jsx(_G,{pathname:e.pathname,searchParams:e.searchParams})]}),a.jsxs(ye,{gap:"lg",pr:"sm",children:[e.notifications,a.jsxs(je,{width:260,shadow:"xl",position:"bottom-end",transitionProps:{transition:"pop-top-right"},opened:n,onClose:()=>r(!1),children:[a.jsx(je.Target,{children:a.jsx(sr,{className:Ot(wh.user,{[wh.userActive]:n}),onClick:()=>r(o=>!o),children:a.jsxs(ye,{gap:7,children:[a.jsx(gs,{value:t,radius:"xl",size:24}),a.jsx(Te,{size:"sm",className:wh.userName,children:Jc(t?.name?.[0])}),a.jsx(zb,{size:12,stroke:1.5})]})})}),a.jsx(je.Dropdown,{children:a.jsx(bG,{version:e.version})})]})]})]})})}const qb=v.createContext({submitting:!1});qb.displayName="FormContext";function MG(e){const t={};for(const n of Array.from(e.elements))n instanceof HTMLInputElement?LG(t,n):n instanceof HTMLTextAreaElement?t[n.name]=n.value:n instanceof HTMLSelectElement&&IG(t,n);return t}function LG(e,t){t.disabled||(t.type==="checkbox"||t.type==="radio")&&!t.checked||(e[t.name]=t.value)}function IG(e,t){e[t.name]=t.value}function ut(e){const[t,n]=v.useState(!1);return a.jsx(qb.Provider,{value:{submitting:t},children:a.jsx("form",{style:e.style,"data-testid":e.testid,onSubmit:r=>{r.preventDefault();const o=MG(r.target);if(e.onSubmit){n(!0);const l=e.onSubmit(o);l?.then?l.catch(console.error).finally(()=>{n(!1)}):n(!1)}},children:e.children})})}function vr(e){const{children:t,...n}=e,{submitting:r}=v.useContext(qb);return a.jsx(ke,{type:"submit",loading:r,...n,children:t})}function zG(e){const t=Re(),n=t.getUserConfiguration();function r(o){const{menuname:l,bookmarkname:c}=o,d=`${e.pathname}?${e.searchParams.toString()}`,f=ii(n);f.menu?.find(({title:m})=>m===l)?.link?.push({name:c,target:d}),t.updateResource(f).then(m=>{n.menu=m.menu,t.dispatchEvent({type:"change"}),Ne({color:"green",message:"Success"}),e.onOk()}).catch(m=>{Ne({color:"red",message:Ye(m)})})}return a.jsx(Un,{title:"Add Bookmark",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:e.onCancel,children:a.jsx(ut,{onSubmit:r,children:a.jsxs(Be,{children:[a.jsx($G,{config:n}),a.jsx(Ve,{label:"Bookmark Name",type:"text",name:"bookmarkname",placeholder:"Bookmark Name",withAsterisk:!0}),a.jsx(ye,{justify:"flex-end",children:a.jsx(vr,{mt:"sm",children:"OK"})})]})})})}function $G(e){function t(r){return r?.menu?.map(o=>o.title)}const n=t(e.config);return a.jsx(on,{name:"menuname",defaultValue:n[0],label:"Select Menu Option",data:n,withAsterisk:!0})}function QA(e){return typeof e.code=="string"?e.code:JSON.stringify(e)}function UG(e){return typeof e.display=="string"?e.display:QA(e)}function BG(e){return{value:QA(e),label:UG(e),resource:e}}function VG(e){return{code:e,display:e}}function jm(e){const t=Re(),{binding:n,creatable:r,clearable:o,expandParams:l,withHelpText:c,...d}=e,f=v.useCallback(async(p,m)=>{if(!n)return[];const x=(await t.valueSetExpand({...l,url:n,filter:p,count:10},{signal:m})).expansion?.contains??[],b=[];for(const w of x)w.code&&!b.some(j=>j.code===w.code)&&b.push(w);return b},[t,l,n]);return a.jsx(Hb,{...d,creatable:r??!0,clearable:o??!0,toOption:BG,loadOptions:f,onCreate:VG,itemComponent:c?FG:void 0})}const FG=v.forwardRef(({label:e,resource:t,active:n,...r},o)=>a.jsx("div",{ref:o,...r,children:a.jsxs(ye,{wrap:"nowrap",gap:"xs",children:[n&&a.jsx(Po,{size:12}),a.jsxs("div",{children:[a.jsx(Te,{children:e}),a.jsx(Te,{size:"xs",c:"dimmed",children:`${t.system}#${t.code}`})]})]})}));function WA(e){const{defaultValue:t,onChange:n,withHelpText:r,...o}=e,[l,c]=v.useState(t);function d(f){const p=f[0],m=qG(p);c(m),n&&n(m)}return a.jsx(jm,{defaultValue:HG(l),onChange:d,withHelpText:r??!0,...o})}function HG(e){return e?{code:e}:void 0}function qG(e){return e?.code}function Gb(e){const[t,n]=v.useState(e.defaultValue),r=e.onChange,o=v.useCallback(l=>{n(l),r&&r(l)},[r]);return a.jsx(WA,{disabled:e.disabled,"data-autofocus":e.autoFocus,"data-testid":e.testId,defaultValue:t,onChange:o,name:e.name,placeholder:e.placeholder,binding:"https://medplum.com/fhir/ValueSet/resource-types",creatable:!1,maxValues:e.maxValues??1,clearable:!1,withHelpText:!1})}const GG="_menuTitle_9g6l5_1",QG="_link_9g6l5_9",WG="_linkActive_9g6l5_38",mx={menuTitle:GG,link:QG,linkActive:WG};function YG(e){const t=bm(),n=ZG(e.pathname,e.searchParams,e.menus),[r,o]=v.useState(!1);function l(d,f){d.stopPropagation(),d.preventDefault(),t(f),window.innerWidth<768&&e.closeNavbar()}function c(d){d&&t(`/${d}`)}return a.jsxs(a.Fragment,{children:[a.jsx(Vr.Navbar,{children:a.jsxs(ai,{p:"xs",children:[!e.resourceTypeSearchDisabled&&a.jsx(Vr.Section,{mb:"sm",children:a.jsx(Gb,{name:"resourceType",placeholder:"Resource Type",maxValues:0,onChange:d=>c(d)},window.location.pathname)}),a.jsxs(Vr.Section,{grow:!0,children:[e.menus?.map(d=>a.jsxs(v.Fragment,{children:[a.jsx(Te,{className:mx.menuTitle,children:d.title}),d.links?.map(f=>a.jsxs(KG,{to:f.href,active:f.href===n?.href,onClick:p=>l(p,f.href),children:[a.jsx(XG,{icon:f.icon}),a.jsx("span",{children:f.label})]},f.href))]},`menu-${d.title}`)),e.displayAddBookmark&&a.jsx(ke,{variant:"subtle",size:"xs",mt:"xl",leftSection:a.jsx(UA,{size:"0.75rem"}),onClick:()=>o(!0),children:"Add Bookmark"})]})]})}),e.pathname&&e.searchParams&&a.jsx(zG,{pathname:e.pathname,searchParams:e.searchParams,visible:r,onOk:()=>o(!1),onCancel:()=>o(!1)})]})}function KG(e){return a.jsx(mt,{onClick:e.onClick,to:e.to,className:Ot(mx.link,{[mx.linkActive]:e.active}),children:e.children})}function XG(e){return e.icon?e.icon:a.jsx(cm,{w:30})}function ZG(e,t,n){if(!e||!t||!n)return;let r,o=0;for(const l of n)if(l.links)for(const c of l.links){const d=JG(e,t,c.href);d>o&&(o=d,r=c)}return r}function JG(e,t,n){const r=new URL(n,"https://example.com");if(e!==r.pathname)return 0;const o=["_count","_offset"];for(const[c,d]of r.searchParams.entries())if(!o.includes(c)&&t.get(c)!==d)return 0;let l=1;for(const[c,d]of t.entries())o.includes(c)||r.searchParams.get(c)===d&&l++;return l}function eQ(e){const[t,n]=v.useState(localStorage.navbarOpen==="true"),r=Re(),o=Sm();v.useEffect(()=>{function f(){Ne({id:"offline",color:"red",message:"No connection to server",autoClose:!1})}return r.addEventListener("offline",f),()=>r.removeEventListener("offline",f)},[r]);function l(f){localStorage.navbarOpen=f.toString(),n(f)}function c(){l(!1)}function d(){l(!t)}return r.isLoading()?a.jsx(Di,{}):a.jsxs(Vr,{header:{height:60},navbar:{width:250,breakpoint:"sm",collapsed:{desktop:!o||!t,mobile:!o||!t}},padding:0,children:[o&&a.jsx(OG,{pathname:e.pathname,searchParams:e.searchParams,headerSearchDisabled:e.headerSearchDisabled,logo:e.logo,version:e.version,navbarToggle:d,notifications:e.notifications}),o&&t?a.jsx(YG,{pathname:e.pathname,searchParams:e.searchParams,menus:e.menus,closeNavbar:c,displayAddBookmark:e.displayAddBookmark,resourceTypeSearchDisabled:e.resourceTypeSearchDisabled}):void 0,a.jsx(Vr.Main,{className:uG.main,children:a.jsx(VA,{children:a.jsx(v.Suspense,{fallback:a.jsx(Di,{}),children:e.children})})})]})}const tQ="https://ccda.medplum.com",nQ="https://ccda-validator.medplum.com/";function rQ(e){const{url:t}=e,[n,r]=v.useState(!1),o=v.useRef(null),[l,c]=v.useState(),[d,f]=v.useState(!1);v.useEffect(()=>{t&&n&&o.current&&(id(o.current,{command:"loadCcdaXml",value:t}).catch(console.error),r(!1))},[t,n]);const p=async()=>{if(t)try{f(!0);const b=await(await fetch(t)).text(),w=new FormData;w.append("ccdaFile",new Blob([b],{type:"text/xml"}),"ccda.xml");const j=`${nQ}referenceccdaservice/?validationObjective=C-CDA_IG_Plus_Vocab&referenceFileName=No%20scenario%20File&curesUpdate=true&severityLevel=WARNING`,C=await fetch(j,{method:"POST",body:w,credentials:"omit",redirect:"manual"});if(!C.ok)throw new Error(`Validation failed: ${C.status} ${C.statusText}`);const T=await C.json();c(T)}catch(x){c(void 0),console.error("CCDA validation error:",x)}finally{f(!1)}},m=()=>{if(!l)return;const x=JSON.stringify(l,null,2);qA(x,"ccda-validation-results")},g=()=>l?l.resultsMetaData.resultMetaData.filter(x=>x?.type.includes("Error")).reduce((x,b)=>x+(b.count||0),0):0;return t?a.jsxs("div",{"data-testid":"ccda-iframe",style:{maxWidth:e.maxWidth},children:[a.jsx("div",{style:{minHeight:400},children:a.jsx("iframe",{title:"C-CDA Viewer",width:"100%",height:"400",ref:o,src:tQ,allowFullScreen:!0,frameBorder:0,seamless:!0,onLoad:()=>r(!0)})}),a.jsxs("div",{style:{marginTop:"10px",marginBottom:"10px",display:"flex",alignItems:"center"},children:[a.jsx(ke,{type:"button",onClick:p,disabled:d,children:d?"Validating...":"Validate"}),l&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{style:{marginLeft:"15px"},children:[a.jsx("strong",{children:"Validation Results:"})," ",g()," errors found"]}),a.jsx(ke,{type:"button",onClick:m,color:"green",style:{marginLeft:"auto"},children:"Download Full Results"})]})]})]}):null}function Qd(e){const{contentType:t,url:n,title:r}=e.value??{},o=TA(n);return o?a.jsxs("div",{"data-testid":"attachment-display",children:[t?.startsWith("image/")&&a.jsx("img",{"data-testid":"attachment-image",style:{maxWidth:e.maxWidth},src:o,alt:r}),t?.startsWith("video/")&&a.jsx("video",{"data-testid":"attachment-video",style:{maxWidth:e.maxWidth},controls:!0,children:a.jsx("source",{type:t,src:o})}),(t?.startsWith("text/")||t==="application/json"||t==="application/pdf")&&a.jsx("div",{"data-testid":"attachment-iframe",style:{maxWidth:e.maxWidth,minHeight:400},children:a.jsx("iframe",{title:"Attachment",width:"100%",height:"400",src:o+"#navpanes=0",allowFullScreen:!0,frameBorder:0,seamless:!0})}),t===ln.CDA_XML&&a.jsx(rQ,{url:o}),a.jsx("div",{"data-testid":"download-link",style:{padding:"2px 16px 16px 16px"},children:a.jsx(Dt,{href:n,"data-testid":"attachment-details",target:"_blank",rel:"noopener noreferrer",download:iQ(r),children:r||"Download"})})]}):null}function iQ(e){return e?.includes(".")?e:void 0}const oQ="_root_17n8t_1",aQ="_compact_17n8t_25",vT={root:oQ,compact:aQ};function Cm(e){const{children:t,compact:n}=e;return a.jsx("dl",{className:Ot(vT.root,{[vT.compact]:n}),children:t})}function Ti(e){return a.jsxs(a.Fragment,{children:[a.jsx("dt",{children:e.term}),a.jsx("dd",{children:e.children})]})}function sQ(e){const t=e.values?.map((r,o)=>a.jsx("div",{children:a.jsx(Qd,{value:r,maxWidth:e.maxWidth})},"attatchment-"+o));let n;if(e.includeDescriptionListEntry){if(e.property===void 0)throw new Error("props.property is required when includeDescriptionListEntry is true");if(!Rn(e.path))throw new Error("props.path is required when includeDescriptionListEntry is true");const r=e.path.split(".").pop();n=a.jsx(Ti,{term:ol(r),children:t})}else n=a.jsx(a.Fragment,{children:t});return n}function Qb(e){const t=Re(),n=v.useRef(null);function r(c){cn(c),n.current?.click()}function o(c){cn(c);const d=c.target.files;d&&Array.from(d).forEach(l)}function l(c){!c||!c.name||(e.onUploadStart&&e.onUploadStart(),t.createAttachment({data:c,contentType:c.type||"application/octet-stream",filename:c.name,securityContext:e.securityContext,onProgress:e.onUploadProgress}).then(f=>e.onUpload(f)).catch(f=>{e.onUploadError&&e.onUploadError(qt(f))}))}return a.jsxs(a.Fragment,{children:[a.jsx("input",{disabled:e.disabled,type:"file","data-testid":"upload-file-input",style:{display:"none"},ref:n,onChange:c=>o(c)}),e.children({onClick:r,disabled:e.disabled})]})}function lQ(e){const[t,n]=v.useState(e.defaultValue??[]),r=v.useRef(t);r.current=t;function o(l){n(l),e.onChange&&e.onChange(l)}return a.jsxs("table",{style:{width:"100%"},children:[a.jsxs("colgroup",{children:[a.jsx("col",{width:"97%"}),a.jsx("col",{width:"3%"})]}),a.jsxs("tbody",{children:[t.map((l,c)=>a.jsxs("tr",{children:[a.jsx("td",{children:a.jsx(Qd,{value:l,maxWidth:200})}),a.jsx("td",{children:a.jsx(bn,{disabled:e.disabled,title:"Remove",variant:"subtle",size:"sm",color:"gray",onClick:d=>{cn(d);const f=t.slice();f.splice(c,1),o(f)},children:a.jsx(lp,{})})})]},`${c}-${t.length}`)),a.jsxs("tr",{children:[a.jsx("td",{}),a.jsx("td",{children:a.jsx(Qb,{disabled:e.disabled,onUpload:l=>{o([...r.current,l])},children:l=>a.jsx(bn,{...l,title:"Add",variant:"subtle",size:"sm",color:l.disabled?"gray":"green",children:a.jsx($b,{})})})})]})]})]})}function YA(e){const[t,n]=v.useState(e.defaultValue);function r(o){n(o),e.onChange&&e.onChange(o)}return t?a.jsxs(a.Fragment,{children:[a.jsx(Qd,{value:t,maxWidth:200}),a.jsx(ke,{disabled:e.disabled,onClick:o=>{cn(o),r(void 0)},children:"Remove"})]}):a.jsx(Qb,{disabled:e.disabled,securityContext:e.securityContext,onUpload:r,children:o=>a.jsx(ke,{...o,children:"Upload..."})})}function Mi(e){return a.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 180 180",style:{width:e.size,height:e.size},children:[a.jsx("title",{children:"Medplum Logo"}),a.jsx("path",{fill:e.fill??"#9c36b5",d:"M84 56c-3-15-15-24-23-28l5-10c8 2 14 8 20 14 0-12 1-16 5-21 8-9 13-9 41-9 0 7 1 18-3 24-7 9-16 7-41 8 5 8 7 14 8 22 36-24 74-7 74 39 0 42-40 83-80 83s-80-41-80-83c0-46 38-63 74-39Zm-3 43H65c-4 0-7 3-7 7v4c0 4 3 7 7 7h16v16c0 4 3 7 7 7h4c4 0 7-3 7-7v-16h16c4 0 7-3 7-7v-4c0-4-3-7-7-7H99V83c0-4-3-7-7-7h-4c-4 0-7 3-7 7z"})]})}function up(e){const[t,n]=v.useState();return a.jsx(ut,{onSubmit:r=>{n(void 0),e.onSubmit(r)?.catch(o=>n(Ye(o)))},children:a.jsxs(Be,{children:[a.jsxs(ar,{style:{flexDirection:"column"},children:[a.jsx(Mi,{size:32}),a.jsx(Ie,{children:e.title})]}),t&&a.jsx(ya,{icon:a.jsx(bl,{size:16}),title:"Error",color:"red",children:t}),e.qrCodeUrl&&a.jsxs(Be,{align:"center",children:[a.jsx(Te,{children:"Scan this QR code with your authenticator app."}),a.jsx("img",{src:e.qrCodeUrl,alt:"Multi Factor Auth QR Code"})]}),a.jsx(Be,{children:a.jsx(Ve,{name:"token",label:"MFA code",autoComplete:"one-time-code",required:!0,autoFocus:!0})}),a.jsx(ye,{justify:"flex-end",mt:"xl",children:a.jsx(vr,{children:e.buttonText})})]})})}const cQ="_root_1vii2_1",uQ={root:cQ};function eu(e){const{children:t,...n}=e;return a.jsx(kd,{className:uQ.root,...n,children:t})}const dQ="_paper_1igaj_1",fQ="_fill_1igaj_20",yT={paper:dQ,fill:fQ};function Sl(e){const{width:t,fill:n,className:r,children:o,...l}=e,c=t?{maxWidth:t}:void 0;return a.jsx(Tr,{className:Ot(yT.paper,n&&yT.fill,r),style:c,shadow:"sm",radius:"sm",withBorder:!0,...l,children:o})}function lt(e){const{children:t,...n}=e;return a.jsx(eu,{children:a.jsx(Sl,{...n,children:t})})}function At(e,t){return e?.issue?.filter(n=>KA(n.expression?.[0],t))?.map(n=>n.details?.text)?.join(`
546
546
  `)}function tu(e,t){return e?.issue?.filter(n=>KA(n.expression?.[0],t))}const jh=/\[\d+\]/;function KA(e,t){const n=typeof e=="string"&&jh.test(e),r=typeof t=="string"&&jh.test(t);if(n!==r&&(e=e?.replace(jh,""),t=t?.replace(jh,"")),e===t)return!0;if(!e||!t)return!1;const o=e.indexOf(".");if(o>=0&&e.substring(o+1)===t)return!0;const l=t.indexOf(".");return l>=0&&t.substring(l+1)===e}function XA(e){const t=Re(),[n,r]=v.useState();return a.jsxs(ut,{onSubmit:async o=>{try{e.handleAuthResponse(await t.startNewProject({login:e.login,projectName:o.projectName}))}catch(l){r(qt(l))}},children:[a.jsxs(ar,{style:{flexDirection:"column"},children:[a.jsx(Mi,{size:32}),a.jsx(Ie,{children:"Create project"})]}),a.jsxs(Be,{gap:"xl",children:[a.jsx(Ve,{name:"projectName",label:"Project Name",placeholder:"My Project",required:!0,autoFocus:!0,error:At(n,"projectName")}),a.jsxs(Te,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",a.jsx(Dt,{href:"https://www.medplum.com/privacy",children:"Privacy Policy"})," and ",a.jsx(Dt,{href:"https://www.medplum.com/terms",children:"Terms of Service"}),"."]})]}),a.jsx(ye,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(vr,{children:"Create project"})})]})}function ZA(e,t){const n=document.getElementsByTagName("head")[0],r=document.createElement("script");r.async=!0,r.src=e,r.onload=t??null,n.appendChild(r)}function JA(e){const t=Re(),{googleClientId:n,handleGoogleCredential:r}=e,o=v.useRef(null),[l,c]=v.useState(typeof google<"u"),[d,f]=v.useState(!1),[p,m]=v.useState(!1);return v.useEffect(()=>{if(typeof google>"u"){ZA("https://accounts.google.com/gsi/client",()=>c(!0));return}d||(google.accounts.id.initialize({client_id:n,callback:r}),f(!0)),o.current&&!p&&(google.accounts.id.renderButton(o.current,{}),m(!0))},[t,n,d,l,o,p,r]),n?a.jsx("div",{ref:o}):null}function eP(e){if(e)return e;const t=Xn.getOrigin();if(t&&[].includes(t))return"__GOOGLE_CLIENT_ID__"}function yr(e){const t=e.outcome?.issue||e.issues;return!t||t.length===0?null:a.jsx(ya,{icon:a.jsx(bl,{size:16}),color:"red",children:t.map(n=>a.jsx("div",{"data-testid":"text-field-error",children:OD(n)},n.details?.text))})}function tP(e){typeof grecaptcha>"u"&&ZA("https://www.google.com/recaptcha/api.js?render="+e)}function nP(e){return new Promise((t,n)=>{grecaptcha.ready(async()=>{try{t(await grecaptcha.execute(e,{action:"submit"}))}catch(r){n(r)}})})}function hQ(e){const t=eP(e.googleClientId),n=e.recaptchaSiteKey,r=Re(),[o,l]=v.useState(),c=tu(o,void 0);return v.useEffect(()=>{n&&tP(n)},[n]),a.jsxs(ut,{onSubmit:async d=>{l(void 0);try{let f="";n&&(f=await nP(n)),e.handleAuthResponse(await r.startNewUser({projectId:e.projectId,clientId:e.clientId,firstName:d.firstName,lastName:d.lastName,email:d.email,password:d.password,remember:d.remember==="true",recaptchaSiteKey:n,recaptchaToken:f}))}catch(f){l(qt(f))}},children:[a.jsx(ar,{style:{flexDirection:"column"},children:e.children}),a.jsx(yr,{issues:c}),t&&a.jsxs(a.Fragment,{children:[a.jsx(ye,{justify:"center",p:"xl",style:{height:70},children:a.jsx(JA,{googleClientId:t,handleGoogleCredential:async d=>{try{e.handleAuthResponse(await r.startGoogleLogin({googleClientId:d.clientId,googleCredential:d.credential,projectId:e.projectId,createUser:!0}))}catch(f){l(qt(f))}}})}),a.jsx(pn,{label:"or",labelPosition:"center",my:"lg"})]}),a.jsxs(Be,{gap:"xl",children:[a.jsx(Ve,{name:"firstName",type:"text",label:"First name",placeholder:"First name",required:!0,autoFocus:!0,error:At(o,"firstName")}),a.jsx(Ve,{name:"lastName",type:"text",label:"Last name",placeholder:"Last name",required:!0,error:At(o,"lastName")}),a.jsx(Ve,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,error:At(o,"email")}),a.jsx(Qi,{name:"password",label:"Password",autoComplete:"off",required:!0,error:At(o,"password")}),a.jsxs(Te,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",a.jsx(Dt,{href:"https://www.medplum.com/privacy",children:"Privacy Policy"})," and ",a.jsx(Dt,{href:"https://www.medplum.com/terms",children:"Terms of Service"}),"."]}),a.jsxs(Te,{c:"dimmed",size:"xs",children:["This site is protected by reCAPTCHA and the Google"," ",a.jsx(Dt,{href:"https://policies.google.com/privacy",children:"Privacy Policy"})," and ",a.jsx(Dt,{href:"https://policies.google.com/terms",children:"Terms of Service"})," apply."]})]}),a.jsxs(ye,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[a.jsx(Pn,{name:"remember",label:"Remember me",size:"xs"}),a.jsx(vr,{children:"Create account"})]})]})}function pQ(e){const{type:t,projectId:n,clientId:r,googleClientId:o,recaptchaSiteKey:l,onSuccess:c}=e,d=Re(),[f,p]=v.useState(),[m,g]=v.useState();v.useEffect(()=>{t==="patient"&&f&&d.startNewPatient({login:f,projectId:n}).then(b=>d.processCode(b.code)).then(()=>c()).catch(b=>g(qt(b)))},[d,t,n,f,c]);function x(b){b.code?d.processCode(b.code).then(()=>c()).catch(console.log):b.login&&p(b.login)}return a.jsxs(lt,{width:450,children:[m&&a.jsx("pre",{children:JSON.stringify(m,null,2)}),!f&&a.jsx(hQ,{projectId:n,clientId:r,googleClientId:o,recaptchaSiteKey:l,handleAuthResponse:x,children:e.children}),f&&t==="project"&&a.jsx(XA,{login:f,handleAuthResponse:x})]})}function mQ(e){const[t,n]=v.useState();return t?a.jsx(vQ,{email:t,...e}):a.jsx(gQ,{setEmail:n,...e})}function gQ(e){const{setEmail:t,onRegister:n,handleAuthResponse:r,children:o,disableEmailAuth:l,...c}=e,d=Re(),f=!e.disableGoogleAuth&&eP(e.googleClientId),[p,m]=v.useState(),g=tu(p,void 0),x=v.useCallback(async j=>{if(!j.authorizeUrl)return!1;const C=JSON.stringify({...await d.ensureCodeChallenge(c),domain:j.domain}),T=new URL(j.authorizeUrl);return T.searchParams.set("state",C),Xn.assign(T.toString()),!0},[d,c]),b=v.useCallback(async j=>{const C=await d.post("auth/method",{email:j.email});await x(C)||t(j.email)},[d,x,t]),w=v.useCallback(async j=>{try{const C=await d.startGoogleLogin({...c,googleCredential:j.credential});await x(C)||r(C)}catch(C){m(qt(C))}},[d,c,x,r]);return a.jsxs(ut,{onSubmit:b,children:[a.jsx(ar,{style:{flexDirection:"column"},children:o}),a.jsx(yr,{issues:g}),f&&a.jsxs(a.Fragment,{children:[a.jsx(ye,{justify:"center",p:"xl",style:{height:70},children:a.jsx(JA,{googleClientId:f,handleGoogleCredential:w})}),!l&&a.jsx(pn,{label:"or",labelPosition:"center",my:"lg"})]}),!l&&a.jsx(Ve,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:At(p,"email")}),a.jsxs(ye,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[a.jsx("div",{children:n&&a.jsx(Dt,{component:"button",type:"button",c:"dimmed",onClick:n,size:"xs","data-dashlane-ignore":"true","data-lp-ignore":"true","data-no-autofill":"true","data-form-type":"navigation",children:"Register"})}),!l&&a.jsx(vr,{children:"Next"})]})]})}function vQ(e){const{onForgotPassword:t,handleAuthResponse:n,children:r,...o}=e,l=Re(),[c,d]=v.useState(),f=tu(c,void 0),p=v.useCallback(m=>{l.startLogin({...o,password:m.password,remember:m.remember==="on"}).then(n).catch(g=>d(qt(g)))},[l,o,n]);return a.jsxs(ut,{onSubmit:p,children:[a.jsx(ar,{style:{flexDirection:"column"},children:r}),a.jsx(yr,{issues:f}),a.jsx(Be,{gap:"xl",children:a.jsx(Qi,{name:"password",label:"Password",autoComplete:"off",required:!0,autoFocus:!0,error:At(c,"password")})}),a.jsxs(ye,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[t&&a.jsx(Dt,{component:"button",type:"button",c:"dimmed",onClick:t,size:"xs",children:"Forgot password"}),a.jsx(Pn,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1}}),a.jsx(vr,{children:"Sign in"})]})]})}function yQ(e){const t=Re(),n=gl(),[r,o]=v.useState(""),[l,c]=v.useState();function d(g){return!!g?.toLowerCase()?.includes(r.toLowerCase())}function f(g){return d(g.profile?.display)||d(g.project?.display)}function p(g){t.post("auth/profile",{login:e.login,profile:g}).then(e.handleAuthResponse).catch(x=>c(qt(x)))}const m=e.memberships.filter(f).slice(0,10).map(g=>a.jsx(Xe.Option,{value:g.id,children:a.jsx(xQ,{...g})},g.id));return a.jsxs(Be,{children:[a.jsxs(jo,{gap:"md",mb:"md",justify:"center",align:"center",direction:"column",wrap:"nowrap",children:[a.jsx(Mi,{size:32}),a.jsx(Ie,{order:3,children:"Choose profile"})]}),a.jsx(yr,{outcome:l}),a.jsxs(Xe,{store:n,onOptionSubmit:p,children:[a.jsx(Xe.EventsTarget,{children:a.jsx(Ve,{placeholder:"Search",value:r,onChange:g=>{o(g.currentTarget.value),n.updateSelectedOptionIndex()}})}),a.jsx("div",{children:a.jsx(Xe.Options,{children:m.length>0?m:a.jsx(Xe.Empty,{children:"Nothing found..."})})})]})]})}function xQ(e){return a.jsxs(ye,{children:[a.jsx(nl,{radius:"xl"}),a.jsxs("div",{children:[a.jsx(Te,{fz:"sm",fw:500,children:e.profile?.display}),a.jsx(Te,{fz:"xs",opacity:.6,children:e.project?.display})]})]})}const bQ=/^patient\/Condition\.(?:\*|c?r?u?d?s?)$/,SQ="?category=http://terminology.hl7.org/CodeSystem/condition-category|encounter-diagnosis",wQ="?category=http://terminology.hl7.org/CodeSystem/condition-category|problem-list-item",jQ="?category=http://hl7.org/fhir/us/core/CodeSystem/condition-category|health-concern",CQ=/^patient\/Observation\.(?:\*|c?r?u?d?s?)$/,EQ="?category=http://hl7.org/fhir/us/core/CodeSystem/us-core-observation-category|clinical-test",TQ="?category=http://terminology.hl7.org/CodeSystem/observation-category|laboratory",RQ="?category=http://terminology.hl7.org/CodeSystem/observation-category|social-history",_Q="?category=http://hl7.org/fhir/us/core/CodeSystem/us-core-category|sdoh",DQ="?category=http://terminology.hl7.org/CodeSystem/observation-category|survey",AQ="?category=http://terminology.hl7.org/CodeSystem/observation-category|vital-signs";function PQ(e){const t=Re();return a.jsx(ut,{onSubmit:n=>{t.post("auth/scope",{login:e.login,scope:Object.keys(n).join(" ")}).then(e.handleAuthResponse).catch(console.log)},children:a.jsxs(Be,{children:[a.jsxs(ar,{style:{flexDirection:"column"},children:[a.jsx(Mi,{size:32}),a.jsx(Ie,{children:"Choose scope"})]}),a.jsx(Be,{children:(e.scope??"openid").split(" ").map(n=>{let r;return bQ.test(n)?r=[n+SQ,n+wQ,n+jQ]:CQ.test(n)&&(r=[n+EQ,n+TQ,n+RQ,n+_Q,n+DQ,n+AQ]),a.jsxs(a.Fragment,{children:[a.jsx(Pn,{id:n,name:n,label:n,defaultChecked:!0},n),r?.map(o=>a.jsx(Pn,{id:o,name:o,label:o},o))]},n+"_group")})}),a.jsx(ye,{justify:"flex-end",mt:"xl",children:a.jsx(vr,{children:"Set scope"})})]})})}function rP(e){const{login:t,chooseScopes:n,onSuccess:r,onForgotPassword:o,onRegister:l,onCode:c,...d}=e,f=Re(),[p,m]=v.useState(),g=v.useRef(!1),[x,b]=v.useState(!1),[w,j]=v.useState(),[C,T]=v.useState(!1),[E,R]=v.useState(),D=v.useCallback(k=>{c?c(k):f.processCode(k).then(()=>{r&&r()}).catch(M=>Ne({color:"red",message:Ye(M)}))},[f,c,r]),P=v.useCallback(k=>{b(!!k.mfaEnrollRequired),j(k.enrollQrCode),T(!!k.mfaRequired),k.login&&m(k.login),k.memberships&&R(k.memberships),k.code&&(n?R(void 0):D(k.code))},[n,D]),A=v.useCallback(k=>{D(k.code)},[D]);return v.useEffect(()=>{t&&!g.current&&!p&&(g.current=!0,f.get("auth/login/"+t).then(P).catch(k=>Ne({color:"red",message:Ye(k)})))},[f,t,g,p,P]),a.jsx(lt,{width:450,px:"sm",py:"md",children:p?x&&w?a.jsx(up,{title:"Enroll in MFA",buttonText:"Enroll",qrCodeUrl:w,onSubmit:async k=>{const M=await f.post("auth/mfa/login-enroll",{login:p,token:k.token});P(M)}}):C?a.jsx(up,{title:"Enter MFA code",buttonText:"Submit code",onSubmit:async k=>{const M=await f.post("auth/mfa/verify",{login:p,token:k.token});P(M)}}):E?a.jsx(yQ,{login:p,memberships:E,handleAuthResponse:P}):e.projectId==="new"?a.jsx(XA,{login:p,handleAuthResponse:P}):e.chooseScopes?a.jsx(PQ,{login:p,scope:e.scope,handleAuthResponse:A}):a.jsx("div",{children:"Success"}):a.jsx(mQ,{onForgotPassword:o,onRegister:l,handleAuthResponse:P,disableGoogleAuth:e.disableGoogleAuth,disableEmailAuth:e.disableEmailAuth,...d,children:e.children})})}function bo(e){return a.jsx(a.Fragment,{children:ls(e.value)})}function kQ(e){return a.jsx(a.Fragment,{children:Hd(e.value)})}function iP(e){const t=e.value;if(!t)return null;const n=[];return t.value&&n.push(t.value),(t.use||t.system)&&(n.push(" ["),t.use&&n.push(t.use),t.use&&t.system&&n.push(" "),t.system&&n.push(t.system),n.push("]")),a.jsx(a.Fragment,{children:n.join("").trim()})}function NQ(e){const t=e.value;return t?a.jsxs(a.Fragment,{children:[t.name,t.name&&": ",t.telecom?.map(n=>a.jsx(iP,{value:n},`telecom-${t.name}-${n.value}`))]}):null}function Em(e,t,n){const r=Lc(e,t,{profileUrl:n});return r?Array.isArray(r)?[r.map(o=>o.value),r[0].type]:[r.value,r.type]:[void 0,"undefined"]}function OQ(e,t,n){const r=UD(e,t,n);return r?Array.isArray(r)?[r.map(o=>o.value),r[0].type]:[r.value,r.type]:[void 0,"undefined"]}function MQ(e){const{elementDefinitionType:t}=e,n=Re(),r=v.useContext(an),[o,l]=v.useState(zD("Extension")),c=v.useMemo(()=>{if(Rn(t?.profile))return t.profile[0]},[t]),[d,f]=v.useState(c!==void 0);if(v.useEffect(()=>{c&&(f(!0),n.requestProfileSchema(c).then(()=>{const g=Zc(c);f(!1),g&&l(g)}).catch(g=>{f(!1),console.warn(g)}))},[n,c]),c&&(d||!vb(c)))return a.jsx("div",{children:"Loading..."});if(o.elements["value[x]"]?.max!==0){const[g,x]=Em({type:"Extension",value:e.value},"value[x]",c??r.profileUrl);return a.jsx(Xi,{propertyType:x,value:g})}return a.jsx(fp,{path:e.path,value:{type:o.type,value:e.value},compact:e.compact,ignoreMissingValues:e.ignoreMissingValues,link:e.link,profileUrl:c})}function LQ(e){return a.jsxs("div",{children:[e.value?.system,": ",e.value?.value]})}function IQ(e){return a.jsx(a.Fragment,{children:XU(e.value)})}function vd(e){return a.jsx(a.Fragment,{children:Ks(e.value)})}function Wb(e){return a.jsx(a.Fragment,{children:md(e.value)})}function zQ(e){const t=e.value;return t?a.jsxs(a.Fragment,{children:[a.jsx(vd,{value:t.numerator})," / ",a.jsx(vd,{value:t.denominator})]}):null}function dp(e){if(!e.value)return null;const t=e.value.display||e.value.reference||Ki(e.value);return e.link!==!1&&e.value.reference?a.jsx(mt,{to:e.value,children:t}):a.jsx(a.Fragment,{children:t})}function oP(e,t,n,r){if(!Rn(n?.slices))return[e];const o=new Array(t.length+1);for(let l=0;l<o.length;l++)o[l]=[];for(const l of e){const c=wA(l,t,n.discriminator,r);let d=c?t.findIndex(f=>f.name===c):-1;d===-1&&(d=t.length),o[d].push(l)}return o}async function aP({medplum:e,property:t}){return new Promise((n,r)=>{if(!t.slicing){n([]);return}const o=[],l=[],c=[];for(const d of t.slicing.slices){if(!SA(d)){console.debug("Unsupported slice definition",d);continue}let f;Rn(d.elements)||(f=d.type[0]?.profile?.[0]),o.push(d),l.push(f),f&&c.push(e.requestProfileSchema(f))}Promise.all(c).then(()=>{for(let d=0;d<o.length;d++){const f=o[d],p=l[d];if(p){const m=Zc(p);f.typeSchema=m}}n(o)}).catch(r)})}function Tm(e,t,n){return t!==void 0?a.jsx(e,{value:t,children:n}):n}function $Q(e){const{slice:t,property:n}=e,r=t.typeSchema?.elements??t.elements,o=v.useContext(an),l=v.useMemo(()=>{if(Rn(r))return zc({parentContext:o,elements:r,path:e.path,profileUrl:t.typeSchema?.url})},[o,e.path,t.typeSchema?.url,r]);return Tm(an.Provider,l,a.jsx(a.Fragment,{children:e.value.map((c,d)=>a.jsx("div",{children:a.jsx(Xi,{property:n,path:e.path,arrayElement:!0,elementDefinitionType:t.type[0],propertyType:t.type[0].code,value:c,ignoreMissingValues:e.ignoreMissingValues,link:e.link})},`${d}-${e.value.length}`))}))}const xT=50;function UQ(e){const{property:t,propertyType:n}=e,r=Re(),o=v.useMemo(()=>Array.isArray(e.values)?e.values:[],[e.values]),[l,c]=v.useState(!0),[d,f]=v.useState([]),[p,m]=v.useState(()=>[o]),[g,x]=v.useState(0),b=v.useContext(an);if(v.useEffect(()=>{aP({medplum:r,property:t}).then(C=>{x(o.length),f(C);const T=o.slice(0,xT),E=oP(T,C,t.slicing,b.profileUrl);m(E),c(!1)}).catch(C=>{console.error(C),c(!1)})},[r,t,b.profileUrl,m,o]),l)return a.jsx("div",{children:"Loading..."});let w;if(t.type[0]?.code!=="Extension"){const C=p[d.length],T=C.map((E,R)=>a.jsx("div",{children:a.jsx(Xi,{path:e.path,arrayElement:!0,property:t,propertyType:n,value:E,ignoreMissingValues:e.ignoreMissingValues,link:e.link})},`${R}-${C.length}`));if(e.includeDescriptionListEntry){if(!Rn(e.path))throw new Error("props.path is required when includeDescriptionListEntry is true");const E=e.path.split(".").pop();w=a.jsx(Ti,{term:ol(E),children:T})}else w=a.jsx(a.Fragment,{children:T})}return a.jsxs(a.Fragment,{children:[d.map((C,T)=>{if(!e.path)throw Error(`Displaying a resource property with slices of type ${e.propertyType} requires path`);let E=a.jsx($Q,{path:e.path,slice:C,property:t,value:p[T],ignoreMissingValues:e.ignoreMissingValues,link:e.link},C.name);return e.includeDescriptionListEntry&&(E=a.jsx(Ti,{term:ol(C.name),children:E},C.name)),E}),w,g>xT&&a.jsx(ye,{justify:"right",children:a.jsxs(Te,{children:["... ",g," total values"]})})]})}function Xi(e){const{property:t,propertyType:n,value:r}=e;if(t?.path?.endsWith(".id"))return a.jsxs(jo,{gap:3,align:"center",children:[r,!vn(r)&&a.jsx(L0,{value:r,timeout:2e3,children:({copied:l,copy:c})=>a.jsx(ca,{label:l?"Copied":"Copy",withArrow:!0,position:"right",children:a.jsx(bn,{variant:"subtle",color:l?"teal":"gray",onClick:c,children:l?a.jsx(Po,{size:"1rem"}):a.jsx(Ub,{size:"1rem"})})})})]});if(t&&(t.isArray||t.max>1)&&!e.arrayElement)return n===re.Attachment?a.jsx(sQ,{values:r,maxWidth:e.maxWidth,includeDescriptionListEntry:e.includeArrayDescriptionListEntry,property:t,path:e.path}):a.jsx(UQ,{path:e.path,property:t,propertyType:n,values:r,includeDescriptionListEntry:e.includeArrayDescriptionListEntry,ignoreMissingValues:e.ignoreMissingValues,link:e.link});switch(n){case re.boolean:return a.jsx(a.Fragment,{children:r===void 0?"":(!!r).toString()});case re.SystemString:case re.string:return e.property?.path?.toLowerCase().includes("secret")?a.jsx(BQ,{value:r}):a.jsx("div",{style:{whiteSpace:"pre-wrap"},children:r});case re.code:case re.date:case re.decimal:case re.id:case re.integer:case re.positiveInt:case re.unsignedInt:case re.uri:case re.url:return a.jsx(a.Fragment,{children:r});case re.canonical:return a.jsx(dp,{value:{reference:r},link:e.link});case re.dateTime:case re.instant:return a.jsx(a.Fragment,{children:mr(r)});case re.markdown:return a.jsx("pre",{children:r});case re.Address:return a.jsx(KF,{value:r});case re.Annotation:return a.jsx(a.Fragment,{children:r?.text});case re.Attachment:return a.jsx(Qd,{value:r,maxWidth:e.maxWidth});case re.CodeableConcept:return a.jsx(bo,{value:r});case re.Coding:return a.jsx(kQ,{value:r});case re.ContactDetail:return a.jsx(NQ,{value:r});case re.ContactPoint:return a.jsx(iP,{value:r});case re.HumanName:return a.jsx(Fb,{value:r});case re.Identifier:return a.jsx(LQ,{value:r});case re.Money:return a.jsx(IQ,{value:r});case re.Period:return a.jsx(a.Fragment,{children:GU(r)});case re.Quantity:case re.Duration:return a.jsx(vd,{value:r});case re.Range:return a.jsx(Wb,{value:r});case re.Ratio:return a.jsx(zQ,{value:r});case re.Reference:return a.jsx(dp,{value:r,link:e.link});case re.Timing:return a.jsx(a.Fragment,{children:rA(r)});case re.Dosage:case re.UsageContext:if(!e.path)throw Error(`Displaying property of type ${e.propertyType} requires path`);return a.jsx(fp,{path:e.path,value:{type:n,value:r},compact:!0,ignoreMissingValues:e.ignoreMissingValues});case re.Extension:if(!e.path)throw Error(`Displaying property of type ${e.propertyType} requires path`);return a.jsx(MQ,{path:e.path,value:r,compact:!0,ignoreMissingValues:e.ignoreMissingValues,elementDefinitionType:e.elementDefinitionType});default:if(!t)throw Error(`Displaying property of type ${e.propertyType} requires element schema`);if(!e.path)throw Error(`Displaying property of type ${e.propertyType} requires path`);return a.jsx(fp,{path:e.path,value:{type:t.type[0].code,value:r},compact:!0,ignoreMissingValues:e.ignoreMissingValues})}}function BQ(e){const[t,n]=v.useState(!1),r=e.value??"",o=!vn(r),l="•".repeat(8);return a.jsxs(jo,{gap:3,align:"center",children:[t?a.jsx("div",{style:{whiteSpace:"pre-wrap"},children:r}):a.jsx("div",{style:{whiteSpace:"pre-wrap"},"aria-hidden":"true",children:o?l:""}),o&&a.jsxs(a.Fragment,{children:[a.jsx(L0,{value:e.value,timeout:2e3,children:({copied:c,copy:d})=>a.jsx(ca,{label:c?"Copied":"Copy secret",withArrow:!0,position:"right",children:a.jsx(bn,{variant:"subtle",color:c?"teal":"gray",onClick:d,"aria-label":c?"Copied":"Copy secret",children:c?a.jsx(Po,{size:"1rem"}):a.jsx(Ub,{size:"1rem"})})})}),a.jsx(ca,{label:t?"Hide secret":"Show secret",withArrow:!0,position:"right",children:a.jsx(bn,{variant:"subtle",color:"gray",onClick:()=>n(!t),"aria-label":t?"Hide secret":"Show secret",children:t?a.jsx(KH,{size:"1rem"}):a.jsx(ZH,{size:"1rem"})})})]})]})}const sP=["extension","modifierExtension"],VQ=MA.filter(e=>!sP.includes(e));function fp(e){const t=e.value,{value:n,type:r}=t,o=v.useContext(an),l=e.profileUrl??o?.profileUrl,c=v.useMemo(()=>dm(r,l),[l,r]),d=v.useMemo(()=>{if(c)return zc({parentContext:o,elements:c.elements,path:e.path,profileUrl:c.url,accessPolicyResource:e.accessPolicyResource})},[c,o,e.path,e.accessPolicyResource]);if(vn(n))return null;if(!c)return a.jsxs("div",{children:[r," not implemented"]});if(typeof n=="object"&&"name"in n&&Object.keys(n).length===1&&typeof n.name=="string")return a.jsx("div",{children:n.name});const f=d??o;return Tm(an.Provider,d,a.jsx(Cm,{compact:e.compact,children:Object.entries(f.elements).map(([p,m])=>{if(sP.includes(p)&&vn(m.slicing?.slices))return null;if(VQ.includes(p))return null;if(LA.includes(p)&&m.path.split(".").length===2||p.includes("."))return null;const[g,x]=Em(t,p,f.profileUrl);if((e.ignoreMissingValues||m.max===0)&&vn(g)||e.path.endsWith(".extension")&&(p==="url"||p==="id"))return null;const b=m.max>1||m.isArray,w=a.jsx(Xi,{property:m,propertyType:x,path:e.path+"."+p,value:g,ignoreMissingValues:e.ignoreMissingValues,includeArrayDescriptionListEntry:b,link:e.link},p);return b?w:a.jsx(Ti,{term:ol(p),children:w},p)})}))}const FQ="_dimmed_11me5_1",HQ="_preserveBreaks_11me5_5",gx={dimmed:FQ,preserveBreaks:HQ},lP="Read Only";function cP(e,t){return e?a.jsx(ca.Floating,{label:e,children:t}):t}function uP(e){const{debugMode:t}=v.useContext(an);let n;return t&&e.fhirPath?n=`${e.title} - ${e.fhirPath}`:n=e.title,cP(e?.readonly?lP:void 0,a.jsxs(ye,{wrap:"nowrap","data-testid":e.testId,children:[a.jsx("div",{children:e.children}),a.jsx("div",{children:a.jsx(un.Wrapper,{id:e.htmlFor,label:n,classNames:{label:e?.readonly?gx.dimmed:void 0},description:e.description,withAsterisk:e.withAsterisk,children:null})})]}))}function Pt(e){const{debugMode:t}=v.useContext(an);let n;return t&&e.fhirPath?n=`${e.title} - ${e.fhirPath}`:n=e.title,cP(e?.readonly?lP:void 0,a.jsx(un.Wrapper,{id:e.htmlFor,label:n,classNames:{label:Ot({[gx.dimmed]:e?.readonly},gx.preserveBreaks)},description:e.description,withAsterisk:e.withAsterisk,error:At(e.outcome,e.errorExpression??e.htmlFor),"data-testid":e.testId,children:e.children}))}function qQ(e,t,n,r,o){const l=r.type;if(l.length>1)for(const c of l){const d=t.replace("[x]",$n(c.code));d in e&&delete e[d]}return vn(o)?e[n]=void 0:e[n]=o,e}function GQ(e){return!!e&&!vn(e.url)&&!vn(e.name)}function QQ(e){const{defaultValue:t,onChange:n,withHelpText:r,outcome:o,path:l,valuePath:c,...d}=e,[f,p]=v.useState(t);function m(g){const x=YQ(g);p(x),n&&n(x)}return a.jsx(jm,{defaultValue:f&&WQ(f),onChange:m,withHelpText:r??!0,...d})}function WQ(e){return e.coding?.map(t=>({system:t.system,code:t.code,display:t.display}))}function YQ(e){if(e.length!==0)return{coding:e.map(t=>({system:t.system,code:t.code,display:t.display}))}}function KQ(e){const{defaultValue:t,onChange:n,withHelpText:r,response:o,...l}=e,[c,d]=v.useState(o?.answer?.[0]?.valueCoding??t);function f(p){const m=p[0],g=m&&ZQ(m);d(g),n&&n(g)}return a.jsx(jm,{defaultValue:c?XQ(c):void 0,maxValues:1,onChange:f,withHelpText:r??!0,...l})}function XQ(e){return{system:e.system,code:e.code,display:e.display}}function ZQ(e){return{system:e.system,code:e.code,display:e.display}}function dP(e){const{path:t,outcome:n}=e,{elementsByPath:r,getExtendedProps:o}=v.useContext(an),[l,c]=v.useState(e.defaultValue),d=v.useRef(l);d.current=l;const[f,p,m]=v.useMemo(()=>["system","use","value"].map(R=>r[t+"."+R]),[r,t]),[g,x,b]=v.useMemo(()=>["system","use","value"].map(R=>o(t+"."+R)),[o,t]);function w(R){R&&Object.keys(R).length===0&&(R=void 0),c(R),e.onChange&&e.onChange(R)}function j(R){const D={...d.current,system:R};R||delete D.system,w(D)}function C(R){const D={...d.current,use:R};R||delete D.use,w(D)}function T(R){const D={...d.current,value:R};R||delete D.value,w(D)}const E=e.valuePath??t;return a.jsxs(ye,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[a.jsx(on,{disabled:e.disabled||g?.readonly,"data-testid":"system",defaultValue:l?.system,required:(f?.min??0)>0,onChange:R=>j(R.currentTarget.value),data:["","email","phone","fax","pager","sms","other"],error:At(n,E+".system")}),a.jsx(on,{disabled:e.disabled||x?.readonly,"data-testid":"use",defaultValue:l?.use,required:(p?.min??0)>0,onChange:R=>C(R.currentTarget.value),data:["","home","work","temp","old","mobile"],error:At(n,E+".use")}),a.jsx(Ve,{disabled:e.disabled||b?.readonly,placeholder:"Value",defaultValue:l?.value,required:(m?.min??0)>0,onChange:R=>T(R.currentTarget.value),error:At(n,E+".value")})]})}function JQ(e){const[t,n]=v.useState(e.defaultValue),r=v.useRef(t);r.current=t;const{getExtendedProps:o}=v.useContext(an),[l,c]=v.useMemo(()=>["name","telecom"].map(m=>o(e.path+"."+m)),[o,e.path]);function d(m){n(m),e.onChange&&e.onChange(m)}function f(m){const g={...r.current,name:m};m||delete g.name,d(g)}function p(m){const g={...r.current,telecom:m&&[m]};m||delete g.telecom,d(g)}return a.jsxs(ye,{gap:"xs",grow:!0,wrap:"nowrap",children:[a.jsx(Ve,{disabled:e.disabled||l?.readonly,"data-testid":e.name+"-name",name:e.name+"-name",placeholder:"Name",style:{width:180},defaultValue:t?.name,onChange:m=>f(m.currentTarget.value)}),a.jsx(dP,{disabled:e.disabled||c?.readonly,name:e.name+"-telecom",path:e.path+".telecom",defaultValue:t?.telecom?.[0],onChange:p,outcome:e.outcome})]})}function eW(e){if(!e)return"";const t=new Date(e);return hm(t)?t.toLocaleDateString("sv")+"T"+t.toLocaleTimeString("sv"):""}function Yb(e){if(!e)return"";const t=new Date(e);return hm(t)?t.toISOString():""}function So(e){return a.jsx(Ve,{id:e.name,name:e.name,label:e.label,"data-autofocus":e.autoFocus,"data-testid":e["data-testid"]??e.name,placeholder:e.placeholder,required:e.required,disabled:e.disabled,type:tW(),step:1,defaultValue:eW(e.defaultValue),autoFocus:e.autoFocus,error:At(e.outcome,e.name),onChange:t=>{if(e.onChange){const n=t.currentTarget.value;e.onChange(Yb(n))}}})}function tW(){return"datetime-local"}function nW(e){const{propertyType:t}=e,n=Re(),r=v.useMemo(()=>{if(Rn(t.profile))return t.profile[0]},[t]),[o,l]=v.useState(r!==void 0);return v.useEffect(()=>{r&&(l(!0),n.requestProfileSchema(r).then(()=>l(!1)).catch(c=>{l(!1),console.warn(c)}))},[n,r]),r&&(o||!vb(r))?a.jsx("div",{children:"Loading..."}):a.jsx(Jb,{profileUrl:r,path:e.path,typeName:"Extension",defaultValue:e.defaultValue,onChange:e.onChange})}function rW(e){const{outcome:t,path:n}=e,[r,o]=v.useState(e.defaultValue),{getExtendedProps:l}=v.useContext(an),[c,d,f,p,m]=v.useMemo(()=>["use","prefix","given","family","suffix"].map(E=>l(e.path+"."+E)),[l,e.path]);function g(E){o(E),e.onChange&&e.onChange(E)}function x(E){g({...r,use:E||void 0})}function b(E){g({...r,prefix:E?E.split(" "):void 0})}function w(E){g({...r,given:E?E.split(" "):void 0})}function j(E){g({...r,family:E||void 0})}function C(E){g({...r,suffix:E?E.split(" "):void 0})}const T=e.valuePath??n;return a.jsxs(ye,{gap:"xs",grow:!0,wrap:"nowrap",children:[a.jsx(on,{disabled:e.disabled||c?.readonly,defaultValue:r?.use,name:e.name+"-use","data-testid":"use",onChange:E=>x(E.currentTarget.value),data:["","temp","old","usual","official","nickname","anonymous","maiden"],error:At(t,T+".use")}),a.jsx(Ve,{disabled:e.disabled||d?.readonly,placeholder:"Prefix",name:e.name+"-prefix",defaultValue:r?.prefix?.join(" "),onChange:E=>b(E.currentTarget.value),error:At(t,T+".prefix")}),a.jsx(Ve,{disabled:e.disabled||f?.readonly,placeholder:"Given",name:e.name+"-given",defaultValue:r?.given?.join(" "),onChange:E=>w(E.currentTarget.value),error:At(t,T+".given")}),a.jsx(Ve,{disabled:e.disabled||p?.readonly,name:e.name+"-family",placeholder:"Family",defaultValue:r?.family,onChange:E=>j(E.currentTarget.value),error:At(t,T+".family")}),a.jsx(Ve,{disabled:e.disabled||m?.readonly,placeholder:"Suffix",name:e.name+"-suffix",defaultValue:r?.suffix?.join(" "),onChange:E=>C(E.currentTarget.value),error:At(t,T+".suffix")})]})}function iW(e){const[t,n]=v.useState(e.defaultValue),{elementsByPath:r,getExtendedProps:o}=v.useContext(an),[l,c]=v.useMemo(()=>["system","value"].map(g=>r[e.path+"."+g]),[r,e.path]),[d,f]=v.useMemo(()=>["system","value"].map(g=>o(e.path+"."+g)),[o,e.path]);function p(g){n(g),e.onChange&&e.onChange(g)}const m=e.valuePath??e.path;return a.jsxs(ye,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[a.jsx(Ve,{disabled:e.disabled||d?.readonly,placeholder:"System",required:(l?.min??0)>0,defaultValue:t?.system,onChange:g=>p({...t,system:g.currentTarget.value}),error:At(e.outcome,m+".system")}),a.jsx(Ve,{disabled:e.disabled||f?.readonly,placeholder:"Value",required:(c?.min??0)>0,defaultValue:t?.value,onChange:g=>p({...t,value:g.currentTarget.value}),error:At(e.outcome,m+".value")})]})}const oW=["USD","EUR","CAD","GBP","AUD"];function aW(e){const{onChange:t}=e,[n,r]=v.useState(e.defaultValue),{getExtendedProps:o}=v.useContext(an),[l,c]=v.useMemo(()=>["currency","value"].map(g=>o(e.path+"."+g)),[o,e.path]),d=v.useCallback(g=>{r(g),t&&t(g)},[t]),f=v.useCallback(g=>{d({...n,currency:g.currentTarget.value})},[n,d]),p=v.useCallback(g=>{d({...n,value:g.currentTarget.valueAsNumber})},[n,d]),m=a.jsx(on,{disabled:e.disabled||l?.readonly,defaultValue:n?.currency,data:oW,styles:{input:{fontWeight:500,borderTopLeftRadius:0,borderBottomLeftRadius:0,width:92}},onChange:f});return a.jsx(Ve,{disabled:e.disabled||c?.readonly,type:"number",name:e.name,label:e.label,placeholder:e.placeholder??"Value",defaultValue:n?.value?.toString()??"USD",leftSection:a.jsx($H,{size:14}),rightSection:m,rightSectionWidth:92,onChange:p})}function sW(e){const[t,n]=v.useState(e.defaultValue),{getExtendedProps:r}=v.useContext(an),[o,l]=v.useMemo(()=>["start","end"].map(d=>r(e.path+"."+d)),[r,e.path]);function c(d){n(d),e.onChange&&e.onChange(d)}return a.jsxs(ye,{gap:"xs",grow:!0,wrap:"nowrap",children:[a.jsx(So,{disabled:e.disabled||o?.readonly,name:e.name+".start",placeholder:"Start",defaultValue:t?.start,onChange:d=>c({...t,start:d})}),a.jsx(So,{disabled:e.disabled||l?.readonly,name:e.name+".end",placeholder:"End",defaultValue:t?.end,onChange:d=>c({...t,end:d})})]})}function ll(e){const[t,n]=v.useState(e.defaultValue),{getExtendedProps:r}=v.useContext(an),[o,l,c]=v.useMemo(()=>["comparator","value","unit"].map(f=>r(e.path+"."+f)),[r,e.path]);function d(f){n(f),e.onChange&&e.onChange(f)}return a.jsxs(ye,{gap:"xs",grow:!0,wrap:"nowrap",children:[a.jsx(on,{disabled:e.disabled||o?.readonly,style:{width:80},"data-testid":e.name+"-comparator",defaultValue:t?.comparator,data:["","<","<=",">=",">"],onChange:f=>d({...t,comparator:f.currentTarget.value})}),a.jsx(Ve,{disabled:e.disabled||l?.readonly,id:e.name,name:e.name,required:e.required,"data-autofocus":e.autoFocus,"data-testid":e.name+"-value",type:"number",placeholder:"Value",defaultValue:t?.value,autoFocus:e.autoFocus,step:"any",onWheel:f=>{e.disableWheel&&f.currentTarget.blur()},onChange:f=>{d({...t,value:lW(f.currentTarget.value)})}}),a.jsx(Ve,{disabled:e.disabled||c?.readonly,placeholder:"Unit","data-testid":e.name+"-unit",defaultValue:t?.unit,onChange:f=>d({...t,unit:f.currentTarget.value})})]})}function lW(e){if(e)return parseFloat(e)}function Kb(e){const[t,n]=v.useState(e.defaultValue),{getExtendedProps:r}=v.useContext(an),[o,l]=v.useMemo(()=>["low","high"].map(d=>r(e.path+"."+d)),[r,e.path]);function c(d){n(d),e.onChange&&e.onChange(d)}return a.jsxs(ye,{gap:"xs",grow:!0,wrap:"nowrap",children:[a.jsx(ll,{path:e.path+".low",disabled:e.disabled||o?.readonly,name:e.name+"-low",defaultValue:t?.low,onChange:d=>c({...t,low:d})}),a.jsx(ll,{path:e.path+".high",disabled:e.disabled||l?.readonly,name:e.name+"-high",defaultValue:t?.high,onChange:d=>c({...t,high:d})})]})}function cW(e){const[t,n]=v.useState(e.defaultValue),{getExtendedProps:r}=v.useContext(an),[o,l]=v.useMemo(()=>["numerator","denominator"].map(d=>r(e.path+"."+d)),[r,e.path]);function c(d){n(d),e.onChange&&e.onChange(d)}return a.jsxs(ye,{gap:"xs",grow:!0,wrap:"nowrap",children:[a.jsx(ll,{path:e.path+".numerator",disabled:e.disabled||o?.readonly,name:e.name+"-numerator",defaultValue:t?.numerator,onChange:d=>c({...t,numerator:d})}),a.jsx(ll,{path:e.path+".denominator",disabled:e.disabled||l?.readonly,name:e.name+"-denominator",defaultValue:t?.denominator,onChange:d=>c({...t,denominator:d})})]})}const uW={Device:"device-name",Observation:"code",Subscription:"criteria",User:"email:contains"},dW=["AccessPolicy","Account","ActivityDefinition","Bot","CapabilityStatement","CareTeam","ClientApplication","CodeSystem","CompartmentDefinition","ConceptMap","EffectEvidenceSynthesis","Endpoint","EventDefinition","Evidence","EvidenceVariable","ExampleScenario","GraphDefinition","Group","HealthcareService","ImplementationGuide","InsurancePlan","Library","Location","Measure","MedicinalProduct","MessageDefinition","NamingSystem","OperationDefinition","Organization","Patient","Person","PlanDefinition","Practitioner","Project","Questionnaire","RelatedPerson","ResearchDefinition","ResearchElementDefinition","ResearchStudy","RiskEvidenceSynthesis","SearchParameter","StructureDefinition","StructureMap","TerminologyCapabilities","TestScript","UserConfiguration","ValueSet"];function fW(e){return{value:_t(e)??"",label:da(e),resource:e}}function wl(e){const t=Re(),{resourceType:n,searchCriteria:r}=e,[o,l]=v.useState(),c=Gt(e.defaultValue,l),d=e.itemComponent??hW,f=e.onChange,p=v.useCallback(async(g,x)=>{const b=pW(n),w=new URLSearchParams({[b]:g??"",_count:"10",...r});return await t.searchResources(n,w,{signal:x})},[t,n,r]),m=v.useCallback(g=>{f&&f(g[0])},[f]);return Rn(e.defaultValue)&&!o&&!c?null:a.jsx(Hb,{disabled:e.disabled,name:e.name,label:e.label,error:e.error,required:e.required,itemComponent:d,defaultValue:c,placeholder:e.placeholder,maxValues:1,toOption:fW,loadOptions:p,onChange:m,clearable:!0})}const hW=v.forwardRef(({label:e,resource:t,active:n,...r},o)=>a.jsx("div",{ref:o,...r,children:a.jsxs(ye,{wrap:"nowrap",children:[a.jsx(gs,{value:t}),a.jsxs("div",{children:[a.jsx(Te,{children:e}),a.jsx(Te,{size:"xs",c:"dimmed",children:t.birthDate||t.id})]})]})}));function pW(e){return uW[e]??(dW.includes(e)?"name":"_id")}function os(e){const{onChange:t}=e,n=Re(),[r,o]=v.useState(e.defaultValue),[l,c]=v.useState(()=>mW(e.targetTypes)),[d,f]=v.useState(()=>gW(e.defaultValue,l)),p=v.useRef(new AD),m=v.useMemo(()=>d?.type==="profile"?{...e.searchCriteria,_profile:d.value}:e.searchCriteria,[e.searchCriteria,d]);v.useEffect(()=>{let b=!1;const w=l?.map(j=>{if(!yW(j))return Promise.resolve(j);b=!0;const C=j.value,T=p.current.get(C);if(T)return T;const E=vW(n,j.value).then(D=>{const P={...j};return D?Rn(D.type)?(P.resourceType=D.type,P.name=D.name,P.title=D.title):(console.error(`StructureDefinition.type missing for ${j.value}`),P.error="StructureDefinition.type missing"):(console.error(`StructureDefinition not found for ${j.value}`),P.error="StructureDefinition not found"),P}).catch(D=>(console.error(D),{...j,error:D})),R=new Fi(E);return p.current.set(C,R),R});!w||!b||Promise.all(w).then(j=>{if(c(j),!d)return;const C=j.findIndex(T=>T.value===d.value||T.resourceType===d.resourceType);if(C===-1){console.debug(`defaultValue had unexpected resourceType: ${d.resourceType}`);return}f(j[C])}).catch(console.error)},[n,d,l]);const g=v.useCallback(b=>{const w=b?Ht(b):void 0;o(w),t&&t(w)},[t]),x=v.useMemo(()=>l?l.map(b=>({value:b.value,label:b.type==="profile"?b.title??b.name??b.resourceType??b.value:b.value})):[],[l]);return a.jsxs(a.Fragment,{children:[e.name&&a.jsx("input",{type:"hidden",name:e.name,value:r?.reference??""}),a.jsxs(ye,{gap:"xs",grow:!0,wrap:"nowrap",children:[l&&l.length>1&&a.jsx(on,{name:e.name+"-resourceType",disabled:e.disabled,"data-autofocus":e.autoFocus,"data-testid":"reference-input-resource-type-select",defaultValue:d?.resourceType,autoFocus:e.autoFocus,onChange:b=>{const w=b.currentTarget.value,j=l.find(C=>C.value===w);f(j)},data:x}),!l&&a.jsx(Gb,{disabled:e.disabled,autoFocus:e.autoFocus,testId:"reference-input-resource-type-input",defaultValue:d?.resourceType,onChange:b=>{f(b?{type:"resourceType",value:b,resourceType:b}:void 0)},name:e.name+"-resourceType",placeholder:"Resource Type"}),a.jsx(wl,{resourceType:d?.resourceType,name:e.name+"-id",required:e.required,placeholder:e.placeholder,defaultValue:r,searchCriteria:m,onChange:g,disabled:e.disabled})]})]})}function mW(e){if(!e||e.length===0||e.length===1&&e[0]==="Resource")return;const t=[];for(const n of e)n.includes("/")?t.push({type:"profile",value:n}):t.push({type:"resourceType",value:n,resourceType:n});return t}function gW(e,t){const n=e?.reference?.split("/")[0];if(n){const r=t?.find(o=>o.resourceType===n);return r||{type:"resourceType",value:n,resourceType:n}}if(t&&t.length>0)return t[0]}async function vW(e,t){const n=Zc(t);if(n)return{type:n.type,name:n.name,title:n.title};const r=`{
547
547
  StructureDefinitionList(url: "${t}", _sort: "_lastUpdated", _count: 1) {
548
548
  type,
@@ -604,4 +604,4 @@ Please change the parent <Route path="${E}"> to <Route path="${E==="/"?"*":`${E}
604
604
  }
605
605
  ]
606
606
  }`,kne="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 Nne(){const e=Re(),{id:t}=Ut(),[n,r]=v.useState(),[o,l]=v.useState(),[c,d]=v.useState(Pne),[f,p]=v.useState(kne),[m,g]=v.useState(ln.FHIR_JSON),x=v.useRef(null),b=v.useRef(null),[w,j]=v.useState(!1);v.useEffect(()=>{e.readResource("Bot",t).then(async A=>{r(A),l(await One(e,A))}).catch(A=>Ne({color:"red",message:Ye(A),autoClose:!1}))},[e,t]);const C=v.useCallback(async()=>id(x.current,{command:"getValue"}),[]),T=v.useCallback(async()=>id(x.current,{command:"getOutput"}),[]),E=v.useCallback(async()=>m===ln.FHIR_JSON?JSON.parse(c):f,[m,c,f]),R=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),j(!0);try{const k=await C(),M=await T(),$=await e.createAttachment({data:k,filename:"index.ts",contentType:"text/typescript"}),U=await e.createAttachment({data:M,filename:"index.js",contentType:"text/typescript"}),J=[{op:"add",path:"/sourceCode",value:$},{op:"add",path:"/executableCode",value:U}];await e.patchResource("Bot",t,J),Ne({color:"green",message:"Saved"})}catch(k){Ne({color:"red",message:Ye(k),autoClose:!1})}finally{j(!1)}},[e,t,C,T]),D=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),j(!0);try{await e.post(e.fhirUrl("Bot",t,"$deploy")),Ne({color:"green",message:"Deployed"})}catch(k){Ne({color:"red",message:Ye(k),autoClose:!1})}finally{j(!1)}},[e,t]),P=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),j(!0);try{const k=await E(),M=await e.post(e.fhirUrl("Bot",t,"$execute"),k,m);await id(b.current,{command:"setValue",value:M}),Ne({color:"green",message:"Success"})}catch(k){Ne({color:"red",message:Ye(k),autoClose:!1})}finally{j(!1)}},[e,t,E,m]);return!n||o===void 0?null:a.jsxs(hr,{m:0,gutter:0,style:{overflow:"hidden"},children:[a.jsx(hr.Col,{span:8,children:a.jsxs(Tr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[a.jsx(Ane,{iframeRef:x,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:o,minHeight:"528px"}),a.jsxs(ye,{justify:"flex-end",gap:"xs",children:[a.jsx(ke,{type:"button",onClick:R,loading:w,leftSection:a.jsx(FH,{size:"1rem"}),children:"Save"}),a.jsx(ke,{type:"button",onClick:D,loading:w,leftSection:a.jsx($b,{size:"1rem"}),children:"Deploy"}),a.jsx(ke,{type:"button",onClick:P,loading:w,leftSection:a.jsx(Aq,{size:"1rem"}),children:"Execute"})]})]})}),a.jsxs(hr.Col,{span:4,children:[a.jsxs(Tr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[a.jsx(on,{data:[{label:"FHIR",value:ln.FHIR_JSON},{label:"HL7",value:ln.HL7_V2}],onChange:A=>g(A.currentTarget.value)}),m===ln.FHIR_JSON?a.jsx(Wc,{value:c,onChange:A=>d(A),autosize:!0,minRows:15}):a.jsx("textarea",{className:_ne.hl7Input,value:f,onChange:A=>p(A.currentTarget.value),rows:15})]}),a.jsx(Tr,{m:2,p:"xs",shadow:"md",children:a.jsx(Dne,{iframeRef:b,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function One(e,t){if(t.sourceCode?.url){const n=t.sourceCode.url?.split("/")?.find(KD);return(await e.download(e.fhirUrl("Binary",n))).text()}return t.code??""}function Tl(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function Mne(){const e=Re(),{resourceType:t,id:n}=Ut(),r={reference:t+"/"+n},o=v.useCallback(l=>{e.updateResource(Tl(l)).then(()=>{Ne({color:"green",message:"Success"})}).catch(c=>{Ne({color:"red",message:Ye(c),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return a.jsx(lt,{children:a.jsx(PK,{value:r,onSubmit:o})});case"Questionnaire":return a.jsx(lt,{children:a.jsx(oX,{questionnaire:r,onSubmit:o})});default:return null}}function Lne(){const{resourceType:e,id:t}=Ut(),n=Gt({reference:e+"/"+t}),r=wn();return n?a.jsx(lt,{children:a.jsx(NX,{value:n,onStart:(o,l)=>r(`/forms/${rl(l)}`)?.catch(console.error),onEdit:(o,l,c)=>r(`/${c.reference}}`)?.catch(console.error)})}):null}function Ine(){const e=Re(),{resourceType:t,id:n}=Ut(),r=wn();return a.jsxs(lt,{children:[a.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),a.jsx(ke,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>r(`/${t}`)?.catch(console.error)).catch(o=>Ne({color:"red",message:Ye(o),autoClose:!1}))},children:"Delete"})]})}const zne="_selectProfileBtn_tbaz6_1",$ne="_chevron_tbaz6_13",ER={selectProfileBtn:zne,chevron:$ne};function Une(){const{resourceType:e,id:t}=Ut(),n=Gt({reference:e+"/"+t}),[r,o]=v.useState(),l=gl({onDropdownClose:()=>l.resetSelectedOption()}),c=v.useMemo(()=>{if(Rn(n?.meta?.profile))return[a.jsx(Xe.Option,{value:"",children:"None"},""),...n.meta.profile.map(f=>a.jsx(Xe.Option,{value:f,children:f},f))]},[n?.meta?.profile]);if(v.useEffect(()=>{n?.meta?.profile?.length===1&&o(n.meta.profile[0])},[n?.meta?.profile]),!n)return null;let d;return Rn(c)&&(d=a.jsx(ye,{justify:"flex-end",children:a.jsxs(Be,{align:"flex-end",gap:"xs",children:[a.jsxs(Xe,{store:l,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:f=>{o(f),l.closeDropdown()},children:[a.jsx(Xe.Target,{children:a.jsx(sr,{onClick:()=>l.toggleDropdown(),children:a.jsxs(Pd,{fw:"bold",fs:"sm",className:ER.selectProfileBtn,children:[a.jsx("span",{children:"Pick profile"}),a.jsx(zb,{stroke:1.5,className:ER.chevron})]})})}),a.jsx(Xe.Dropdown,{w:"max-content",children:a.jsx(Xe.Options,{children:c})})]}),a.jsx(ce,{children:r?a.jsxs(a.Fragment,{children:[a.jsx(Te,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),a.jsx(Te,{span:!0,size:"sm",children:r||"Nothing selected"})]}):a.jsx(Te,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),a.jsx(lt,{children:a.jsxs(Be,{gap:"xl",children:[d,a.jsx(tS,{value:n,profileUrl:r})]})})}function Bne(){const e=Re(),{resourceType:t,id:n}=Ut(),[r,o]=v.useState(),[l,c]=v.useState(),d=wn(),[f,p]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(b=>{o(ii(b)),c(ii(b))}).catch(b=>{p(qt(b)),Ne({color:"red",message:Ye(b),autoClose:!1})})},[e,t,n]);const m=v.useCallback(b=>{p(void 0),e.updateResource(Tl(b)).then(()=>{d(`/${t}/${n}/details`)?.catch(console.error),Ne({id:"succes",color:"green",message:"Success"})}).catch(w=>{p(qt(w)),Ne({color:"red",message:Ye(w),autoClose:!1})})},[e,t,n,d]),g=v.useCallback(b=>{p(void 0);const w=bP.createPatch(r,b);e.patchResource(t,n,w).then(()=>{d(`/${t}/${n}/details`)?.catch(console.error),Ne({id:"succes",color:"green",message:"Success"})}).catch(j=>{p(qt(j)),Ne({color:"red",message:Ye(j),autoClose:!1})})},[e,t,n,r,d]),x=v.useCallback(()=>d(`/${t}/${n}/delete`)?.catch(console.error),[d,t,n]);return l?a.jsx(lt,{children:a.jsx(vp,{defaultValue:l,onSubmit:m,onPatch:g,onDelete:x,outcome:f})}):null}function Vne(){const{resourceType:e,id:t}=Ut(),n=Gt({reference:e+"/"+t});return n?a.jsx(lt,{maw:700,children:n.resourceType==="Patient"?a.jsx(EK,{patient:n}):a.jsx(ya,{icon:a.jsx(bl,{size:16}),title:"Unsupported export type",color:"red",children:"This page is only supported for Patient resources"})}):null}function Pk({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,o=Re(),[l,c]=v.useState();return v.useEffect(()=>{o.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(d=>{c(d.filter(GQ))}).catch(console.error)},[o,n,r]),a.jsx(Tt,{value:t?.url,onChange:d=>{const f=l?.find(p=>p.url===d);f&&n(f)},children:a.jsx(Tt.List,{children:l?.map(d=>{const f=e.meta?.profile?.includes(d.url),p=f?"This profile is present in this resource's meta.profile property.":"This profile is not included in this resource's meta.profile property.";return a.jsx(Tt.Tab,{value:d.url,title:p,rightSection:f&&a.jsx(pb,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:a.jsx(lG,{size:"90%"})}),children:d.title||d.name},d.url)})})})}function kk(e,t){const n=Re(),r=wn();return{defaultValue:{resourceType:e},handleSubmit:c=>{t&&t(void 0),n.createResource(c).then(d=>r("/"+d.resourceType+"/"+d.id)).catch(d=>{t&&t(qt(d)),Ne({color:"red",message:Ye(d),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function Uy(){const{resourceType:e}=Ut(),t=Gr(),[n,r]=v.useState(),{defaultValue:o,handleSubmit:l}=kk(e,r),[c,d]=v.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),p=v.useCallback(m=>{const g=Tl(m);c&&tA(g,c.url),l(g)},[c,l]);return f?a.jsx(lt,{children:a.jsxs(Be,{children:[a.jsx(Pk,{resource:o,currentProfile:c,onChange:d}),c?a.jsx(vp,{defaultValue:o,onSubmit:p,outcome:n,profileUrl:c.url},c.url):a.jsx(Te,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):a.jsx(lt,{children:a.jsx(vp,{defaultValue:o,onSubmit:l,outcome:n})})}function TR(){const e=Re(),{resourceType:t,id:n}=Ut(),r=e.readHistory(t,n).read();return a.jsx(lt,{children:a.jsx(iZ,{history:r})})}function Fne(){const{resourceType:e}=Ut(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:o}=kk(e,n),l=v.useCallback(c=>{o(JSON.parse(c["new-resource"]))},[o]);return a.jsxs(lt,{children:[t&&a.jsx(yr,{outcome:t}),a.jsxs(ut,{onSubmit:l,children:[a.jsx(Wc,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:Ki(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),a.jsx(ye,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(ke,{type:"submit",children:"OK"})})]})]})}function Hne(){const e=Re(),{resourceType:t,id:n}=Ut(),r=Gt({reference:t+"/"+n}),o=wn(),[l,c]=v.useState(),d=v.useCallback(f=>{e.updateResource(Tl(JSON.parse(f.resource))).then(()=>{c(void 0),o(`/${t}/${n}/details`)?.catch(console.error),Ne({color:"green",message:"Success"})}).catch(p=>{Ne({color:"red",message:Ye(p),autoClose:!1})})},[e,t,n,o]);return r?a.jsxs(lt,{children:[l&&a.jsx(yr,{outcome:l}),a.jsxs(ut,{onSubmit:d,children:[a.jsx(Wc,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:Ki(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),a.jsx(ye,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(ke,{type:"submit",children:"OK"})})]})]}):null}function qne(){const{resourceType:e,id:t}=Ut();return Gt({reference:e+"/"+t})?a.jsxs(lt,{children:[a.jsxs(ya,{icon:a.jsx(bl,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",a.jsx("br",{}),a.jsx(Dt,{href:`/forms/${t}`,children:`/forms/${t}`})]}),a.jsx(UP,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function Gne(){const e=Re(),{resourceType:t,id:n}=Ut(),[r,o]=v.useState(),[l,c]=v.useState();return v.useEffect(()=>{e.readResource(t,n).then(d=>o(ii(d))).catch(d=>{Ne({color:"red",message:Ye(d)})})},[e,t,n]),r?a.jsxs(lt,{children:[a.jsxs(Ie,{order:2,children:["Available ",t," profiles"]}),a.jsx(Be,{children:a.jsxs(a.Fragment,{children:[a.jsx(Pk,{resource:r,currentProfile:l,onChange:c}),l?a.jsx(Qne,{profile:l,resource:r,onResourceUpdated:d=>o(d)},l.url):a.jsx(Te,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const Qne=({profile:e,resource:t,onResourceUpdated:n})=>{const r=Re(),[o,l]=v.useState(),[c,d]=v.useState(()=>t.meta?.profile?.includes(e.url)),f=v.useCallback(p=>{l(void 0);const m=Tl(p);c?tA(m,e.url):FU(m,e.url),r.updateResource(m).then(g=>{n(g),Ne({color:"green",message:"Success"})}).catch(g=>{l(qt(g)),Ne({color:"red",message:Ye(g),autoClose:!1})})},[r,e.url,n,c]);return a.jsxs(Be,{children:[a.jsx(zd,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:p=>d(p.currentTarget.checked),"data-testid":"profile-toggle"}),c?a.jsx(vp,{profileUrl:e.url,defaultValue:t,onSubmit:f,outcome:o}):a.jsx("form",{noValidate:!0,onSubmit:p=>{p.preventDefault(),f(t)},children:a.jsx(ye,{justify:"flex-end",mt:"xl",children:a.jsx(ke,{type:"submit",children:"OK"})})})]})},Nk={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},Wne=Object.keys(Nk);function Yne(){const e=Re(),{id:t}=Ut(),n=Gt({reference:`Questionnaire/${t}`}),[r,o]=v.useState(),[l,c]=v.useState("create"),[d,f]=v.useState(0),p=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>Kne(g,n));function m(){r&&n&&e.createResource({resourceType:"Subscription",status:"active",reason:`Connect bot ${r.name} to questionnaire responses`,criteria:`QuestionnaireResponse?questionnaire=${n.url?`${n.url},${_t(n)}`:_t(n)}`,channel:{type:"rest-hook",endpoint:_t(r)},...l?{extension:[{url:"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",valueCode:l}]}:void 0}).then(()=>{o(void 0),f(Date.now()),e.invalidateSearches("Subscription"),Ne({color:"green",message:"Success"})}).catch(g=>Ne({color:"red",message:Ye(g),autoClose:!1}))}return a.jsxs(lt,{children:[a.jsx(Ie,{children:"Bots"}),a.jsxs(Be,{children:[p.length===0&&a.jsx("p",{children:"No bots found."}),p.map(g=>a.jsxs("div",{children:[a.jsx("h3",{children:a.jsx(jl,{value:{reference:g.channel?.endpoint},link:!0})}),a.jsxs("p",{children:["Criteria: ",g.criteria]})]},g.id))]}),a.jsx(pn,{}),a.jsxs(Be,{mt:10,children:[a.jsx(Ed,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),a.jsxs(ye,{children:[a.jsx(wl,{name:"bot",resourceType:"Bot",onChange:g=>o(g)}),a.jsx(ke,{onClick:m,children:"Connect"})]}),a.jsx(ye,{children:a.jsx(on,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:Wne,onChange:g=>c(Nk[g.target.value])})})]}),a.jsx("div",{style:{display:"none"},children:d})]})}function Kne(e,t){if(!t)return!1;const n=e.criteria||"",r=e.channel?.endpoint||"";return n.startsWith("QuestionnaireResponse?")&&r.startsWith("Bot/")&&(n.includes(_t(t))||(t.url?n.includes(t.url):!1))}function Xne(){const{id:e}=Ut(),t=wn(),r=Re().readReference({reference:`Questionnaire/${e}`}).read(),[o,l]=v.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:de.EQUALS,value:r.url?`${r.url},Questionnaire/${e}`:`Questionnaire/${e}`}],fields:["id","_lastUpdated"]});return a.jsx(lt,{children:a.jsx(nu,{search:o,onClick:c=>t(`/${c.resource.resourceType}/${c.resource.id}`)?.catch(console.error),onChange:c=>l(c.definition),hideFilters:!0,hideToolbar:!0})})}function Zne(){const e=Re(),{resourceType:t,id:n}=Ut(),r=Gt({reference:t+"/"+n}),o=v.useCallback(l=>{e.updateResource(Tl(l)).then(()=>{Ne({color:"green",message:"Success"})}).catch(c=>{Ne({color:"red",message:Ye(c),autoClose:!1})})},[e]);return r?a.jsx(lt,{children:a.jsx(EX,{onSubmit:o,definition:r})}):null}function Jne(){const{resourceType:e,id:t}=Ut(),n=Gt({reference:e+"/"+t});return n?a.jsx(lt,{children:e==="MeasureReport"?a.jsx(jK,{measureReport:n}):a.jsx(eS,{value:n})}):null}const ere="_container_1ue98_1",tre="_entry_1ue98_14",nre="_active_1ue98_21",By={container:ere,entry:tre,active:nre};function rre(e){const t=Re(),n=Gt(e.value),[r,o]=v.useState();return v.useEffect(()=>{if(!n)return;const l=bS(n);if(!l)return;const c="reference"in l?l.reference:_t(l);t.search("ServiceRequest","subject="+c).then(d=>{const p=(d.entry??[]).map(m=>m.resource);SP(p),p.reverse(),o(p)}).catch(d=>Ne({color:"red",message:Ye(d),autoClose:!1}))},[t,n]),r?a.jsx("div",{"data-testid":"quick-service-requests",className:By.container,children:r.map(l=>a.jsxs("div",{className:Ot(By.entry,{[By.active]:l.id===n?.id}),children:[a.jsx("p",{children:a.jsx(mt,{to:l,children:ire(l)})}),l.category?.[0]?.text&&a.jsx("p",{children:l.category[0]?.text}),l.code?.coding?.[0]?.code&&a.jsx("p",{children:l.code.coding[0]?.code}),a.jsx("p",{children:ore(l)})]},l.id))}):null}function ire(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function ore(e){return e.authoredOn?e.authoredOn.substring(0,10):e.meta?.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const are="_container_1l2dh_1",sre={container:are};function lre(e){const t=Gt(e.valueSet);if(!t)return null;const n=[""],r=t.compose?.include?.[0]?.concept?.map(o=>o.code);return r&&n.push(...r),e.defaultValue&&!n.includes(e.defaultValue)&&n.push(e.defaultValue),a.jsx("div",{className:sre.container,children:a.jsx(on,{defaultValue:e.defaultValue,onChange:o=>e.onChange(o.currentTarget.value),data:n})})}function cre(e){const t=Gt(e.specimen);return t?a.jsxs(ht,{children:[a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Type"}),a.jsx(ht.Value,{children:"Specimen"})]}),a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Collected"}),a.jsx(ht.Value,{children:mr(t.collection?.collectedDateTime)})]}),a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Specimen Age"}),a.jsx(ht.Value,{children:ure(t)})]}),t.collection?.collectedDateTime&&t.receivedTime?a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Specimen Stability"}),a.jsx(ht.Value,{children:dre(t)})]}):a.jsx(a.Fragment,{})]}):null}function ure(e){const t=e.collection?.collectedDateTime;if(!t)return;const n=new Date(t);return Ok(Mk(n,new Date))}function dre(e){if(!e.collection?.collectedDateTime||!e.receivedTime)return;const t=new Date(e.collection.collectedDateTime),n=new Date(e.receivedTime);return Ok(Mk(t,n))}function Ok(e){return e.toString().padStart(3,"0")+"D"}function Mk(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function fre(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 hre(){const e=Re(),{resourceType:t,id:n}=Ut(),r={reference:t+"/"+n},o=wn(),[l,c]=v.useState(),d=Gt(r,c),f=fre(t),[p,m]=v.useState(()=>{const E=window.location.pathname.split("/").pop();return E&&f.map(R=>R.toLowerCase()).includes(E)?E:f[0].toLowerCase()});async function g(){const R=(await e.readHistory(t,n)).entry?.find(D=>!!D.resource)?.resource;R?x(R):Ne({color:"red",message:"No history to restore",autoClose:!1})}function x(E){e.updateResource(Tl(E)).then(()=>{c(void 0),Ne({color:"green",message:"Success"})}).catch(R=>{Ne({color:"red",message:Ye(R),autoClose:!1})})}if(l)return Z$(l)?a.jsxs(lt,{children:[a.jsx(Ie,{children:"Deleted"}),a.jsx("p",{children:"The resource was deleted."}),a.jsx(ke,{color:"red",onClick:g,children:"Restore"})]}):a.jsx(yr,{outcome:l});function b(E){E||(E=f[0].toLowerCase()),m(E),o(`/${t}/${n}/${E}`)?.catch(console.error)}function w(E){const R=d,D=R.orderDetail||[];D.length===0&&D.push({}),D[0].text!==E&&(D[0].text=E,x({...R,orderDetail:D}))}const j=d&&bS(d),C=d&&Tee(d),T=e.getUserConfiguration()?.option?.find(E=>E.id==="statusValueSet")?.valueString;return a.jsxs(a.Fragment,{children:[d?.resourceType==="ServiceRequest"&&T&&a.jsx(lre,{valueSet:{reference:T},defaultValue:d.orderDetail?.[0]?.text,onChange:w},_t(d)+"-"+d.orderDetail?.[0]?.text),d&&a.jsx(rre,{value:d}),d&&a.jsxs(Tr,{children:[j&&a.jsx(AP,{patient:j}),C&&a.jsx(cre,{specimen:C}),t!=="Patient"&&a.jsx(Rk,{resource:r}),a.jsx(ai,{children:a.jsx(Tt,{value:p.toLowerCase(),onChange:b,children:a.jsx(Tt.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:f.map(E=>a.jsx(Tt.Tab,{value:E.toLowerCase(),children:E},E))})})})]}),a.jsx(gS,{})]})}function Ah(){const e=wn(),{resourceType:t,id:n,versionId:r,tab:o}=Ut(),l=Re(),[c,d]=v.useState(!0),[f,p]=v.useState(),[m,g]=v.useState();if(v.useEffect(()=>{g(void 0),d(!0),l.readHistory(t,n).then(R=>p(R)).then(()=>d(!1)).catch(R=>{g(R),d(!1)})},[l,t,n]),c)return a.jsx(Di,{});const x=f?.entry??[],b=x.findIndex(R=>R.resource?.meta?.versionId===r);if(b===-1)return a.jsxs(lt,{children:[a.jsx(Ie,{children:"Version not found"}),a.jsx(mt,{to:`/${t}/${n}`,children:"Return to resource"})]});const w=x[b].resource,j=b<x.length-1?x[b+1].resource:void 0,C="diff",T=o||C,E=x.length-b;return a.jsx(kd,{maw:1200,children:a.jsx(Sl,{children:a.jsxs(Be,{gap:"lg",children:[m&&a.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)}),a.jsxs(lm,{cols:2,mb:"lg",children:[a.jsx(Oi,{total:x.length,value:E,getControlProps:TP,onChange:R=>e(`/${t}/${n}/_history/${x[x.length-R]?.resource?.meta?.versionId}/${T}`)?.catch(console.error)}),a.jsx(ye,{justify:"right",children:a.jsx(Id,{data:[{value:"diff",label:"Diff"},{value:"raw",label:"Raw"}],value:T,onChange:R=>e(`/${t}/${n}/_history/${r}/${R||C}`)?.catch(console.error)})})]}),a.jsx(ce,{mb:"lg",children:a.jsxs(Cm,{compact:!0,children:[a.jsx(Ti,{term:"Version ID",children:w.meta?.versionId}),a.jsx(Ti,{term:"Author",children:a.jsx(Tc,{value:w.meta?.author,link:!0},w.meta?.author?.reference)}),a.jsx(Ti,{term:"Date/Time",children:mr(w.meta?.lastUpdated)})]})}),T==="diff"&&a.jsx(eZ,{original:j??{resourceType:t,id:n},revised:w}),T==="raw"&&a.jsx("pre",{style:{fontSize:"9pt"},children:JSON.stringify(w,void 0,2)})]})})})}function pre(){const{resourceType:e,id:t}=Ut(),n=wn(),[r,o]=v.useState({resourceType:"Subscription",filters:[{code:"url",operator:de.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return a.jsx(lt,{children:a.jsx(sK,{search:r,onClick:l=>n(`/${l.resource.resourceType}/${l.resource.id}`)?.catch(console.error),onChange:l=>o(l.definition),hideFilters:!0})})}function mre(e){const t=Re(),{resource:n,opened:r,onClose:o}=e,[l,c]=v.useState(!1),[d,f]=v.useState(),[p,m]=v.useState(!1),g=v.useCallback(async()=>{if(n?.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:l&&d?_t(d):void 0,verbose:p}),Ne({color:"green",message:"Done"}),o()}catch(x){Ne({color:"red",message:Ye(x),autoClose:!1})}},[t,n,o,l,d,p]);return a.jsx(Un,{opened:r,onClose:o,title:"Resend Subscriptions",children:a.jsx(ut,{onSubmit:g,children:a.jsxs(Be,{children:[a.jsx(Pn,{label:"Choose subscription (all subscriptions by default)",onChange:x=>c(x.currentTarget.checked)}),l&&a.jsx(wl,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:f}),a.jsx(Pn,{label:"Verbose mode",onChange:x=>m(x.currentTarget.checked)}),a.jsx(ye,{justify:"flex-end",children:a.jsx(ke,{type:"submit",children:"Resend"})})]})})})}function RR(){const e=Re(),t=bm(),{resourceType:n,id:r}=Ut(),o={reference:n+"/"+r},[l,c]=v.useState(),d=wd(!1);function f(E,R){return e.updateResource({...E,priority:R})}function p(E,R){f(E,"stat").then(R).catch(console.error)}function m(E,R){f(E,"routine").then(R).catch(console.error)}function g(E){t(`/${E.resourceType}/${E.id}`)}function x(E){t(`/${E.resourceType}/${E.id}/edit`)}function b(E){t(`/${E.resourceType}/${E.id}/delete`)}function w(E){c(E),d[1].open()}function j(E){t(`/${E.resourceType}/${E.id}/_history/${E.meta?.versionId}`)}function C(E,R){const D="aws-textract";Ne({id:D,title:"AWS Textract in Progress",message:"Extracting text... This may take a moment...",loading:!0,autoClose:!1}),e.post(e.fhirUrl(E.resourceType,E.id,"$aws-textract"),{}).then(()=>{R(),Qs({id:D,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:a.jsx(Po,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(P=>Qs({id:D,title:"AWS Textract Error",color:"red",message:Ye(P),icon:a.jsx(sl,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function T(E){const{primaryResource:R,currentResource:D,reloadTimeline:P}=E,A=D.resourceType===R.resourceType&&D.id===R.id,k=D.resourceType==="Communication"&&D.priority!=="stat",M=D.resourceType==="Communication"&&D.priority==="stat",$=A,U=!A,J=!A,Z=!A,Y=e.getProjectMembership()?.admin,H=Y,Q=vne()&&(D.resourceType==="DocumentReference"||D.resourceType==="Media");return a.jsxs(je.Dropdown,{children:[a.jsx(je.Label,{children:"Resource"}),k&&a.jsx(je.Item,{leftSection:a.jsx(Tq,{size:14}),onClick:()=>p(D,P),"aria-label":`Pin ${_t(D)}`,children:"Pin"}),M&&a.jsx(je.Item,{leftSection:a.jsx(_q,{size:14}),onClick:()=>m(D,P),"aria-label":`Unpin ${_t(D)}`,children:"Unpin"}),U&&a.jsx(je.Item,{leftSection:a.jsx(dT,{size:14}),onClick:()=>g(D),"aria-label":`Details ${_t(D)}`,children:"Details"}),$&&a.jsx(je.Item,{leftSection:a.jsx(dT,{size:14}),onClick:()=>j(D),"aria-label":`Details ${_t(D)}`,children:"Details"}),J&&a.jsx(je.Item,{leftSection:a.jsx(IA,{size:14}),onClick:()=>x(D),"aria-label":`Edit ${_t(D)}`,children:"Edit"}),Y&&a.jsxs(a.Fragment,{children:[a.jsx(je.Divider,{}),a.jsx(je.Label,{children:"Admin"}),H&&a.jsx(je.Item,{leftSection:a.jsx(Lq,{size:14}),onClick:()=>w(D),"aria-label":`Resend Subscriptions ${_t(D)}`,children:"Resend Subscriptions"})]}),Q&&a.jsxs(a.Fragment,{children:[a.jsx(je.Divider,{}),a.jsx(je.Label,{children:"AWS AI"}),a.jsx(je.Item,{leftSection:a.jsx(tG,{size:14}),onClick:()=>C(D,P),"aria-label":`AWS Textract ${_t(D)}`,children:"AWS Textract"})]}),Z&&a.jsxs(a.Fragment,{children:[a.jsx(je.Divider,{}),a.jsx(je.Label,{children:"Danger zone"}),a.jsx(je.Item,{color:"red",leftSection:a.jsx(wm,{size:14}),onClick:()=>b(D),"aria-label":`Delete ${_t(D)}`,children:"Delete"})]})]})}return a.jsxs(a.Fragment,{children:[n==="Encounter"&&a.jsx(mY,{encounter:o,getMenu:T}),n==="Patient"&&a.jsx(_K,{patient:o,getMenu:T}),n==="ServiceRequest"&&a.jsx(sZ,{serviceRequest:o,getMenu:T}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&a.jsx(pY,{resource:o,getMenu:T}),a.jsx(mre,{resource:l,opened:d[0],onClose:d[1].close},`resend-subscriptions-${l?.id}`)]})}function gre(e){const{opened:t,close:n,version:r,loadingStatus:o,handleStatus:l,handleUpgrade:c}=e,[d,f]=v.useState(),[p,m]=v.useState(!1);return v.useEffect(()=>{t&&(d||SF("app-tools-page").then(f).catch(console.error),l())},[t,d,l]),d&&r&&!o?r==="unknown"?a.jsx("p",{children:"Unable to determine the current version of the agent. Check the network connectivity of the agent."}):r.startsWith(d)?a.jsxs("p",{children:["This agent is already on the latest version (",d,")."]}):a.jsxs(a.Fragment,{children:[a.jsxs("p",{children:["Are you sure you want to upgrade this agent from version ",r," to version ",d,"?"]}),a.jsxs(ye,{children:[a.jsx(ke,{onClick:()=>{c(p),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"}),a.jsx(Pn,{label:"Force",onChange:g=>m(g.currentTarget.checked)})]})]}):a.jsx(Di,{})}function vre(){const e=Re(),{id:t}=Ut(),n=v.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,o]=v.useState(!1),[l,c]=v.useState(!1),[d,f]=v.useState(!1),[p,m]=v.useState(!1),[g,x]=v.useState(),[b,w]=v.useState(),[j,C]=v.useState(),[T,E]=v.useState(),[R,D]=v.useState(!1),[P,A]=v.useState(!1),[k,M]=v.useState(),[$,{open:U,close:J}]=wd(!1);v.useEffect(()=>{if(r||l||d||R){A(!0);return}A(!1)},[r,l,d,R]);const Z=v.useCallback(()=>{o(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(F=>{x(F.parameter?.find(K=>K.name==="status")?.valueCode),w(F.parameter?.find(K=>K.name==="version")?.valueString),C(F.parameter?.find(K=>K.name==="lastUpdated")?.valueInstant)}).catch(F=>z(Ye(F))).finally(()=>o(!1))},[e,t]),Y=v.useCallback(F=>{const K=F.host,L=F.pingCount||1;K&&(D(!0),e.pushToAgent(n,K,`PING ${L}`,ln.PING,!0).then(q=>E(q)).catch(q=>z(Ye(q))).finally(()=>D(!1)))},[e,n]),H=v.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(F=>{I("Agent config reloaded successfully.")}).catch(F=>z(Ye(F))).finally(()=>c(!1))},[e,t]),Q=v.useCallback(F=>{f(!0);const K=e.fhirUrl("Agent",t,"$upgrade");K.searchParams.set("force",String(F)),e.get(K,{cache:"reload"}).then(L=>{I("Agent upgraded successfully.")}).catch(L=>z(Ye(L))).finally(()=>f(!1))},[e,t]),O=v.useCallback(F=>{m(!0);const K=F.logLimit||20;e.get(e.fhirUrl("Agent",t,`$fetch-logs${K!==void 0?`?limit=${K}`:""}`),{cache:"reload"}).then(L=>{const q=L?.parameter?.find(ie=>ie.name==="logs");q&&M(q?.valueString)}).catch(L=>z(Ye(L))).finally(()=>m(!1))},[e,t]);function I(F){Ne({color:"green",title:"Success",icon:a.jsx(Po,{size:"1rem"}),message:F})}function z(F){Ne({color:"red",title:"Error",message:F,autoClose:!1})}return a.jsxs(lt,{children:[a.jsx(Un,{opened:$,onClose:J,title:"Upgrade Agent",centered:!0,children:a.jsx(gre,{opened:$,close:J,version:b,loadingStatus:r,handleStatus:Z,handleUpgrade:Q})}),a.jsx(Ie,{order:1,children:"Agent Tools"}),a.jsxs("div",{style:{marginBottom:10},children:["Agent: ",a.jsx(jl,{value:n,link:!0})]}),a.jsx(pn,{my:"lg"}),a.jsx(Ie,{order:2,children:"Agent Status"}),a.jsx("p",{children:"Retrieve the status of the agent. This tests whether the agent is connected to the Medplum server, and the last time it was able to communicate."}),a.jsx(ke,{onClick:Z,loading:r,disabled:P&&!r,children:"Get Status"}),!r&&g&&a.jsx(fe,{children:a.jsxs(fe.Tbody,{children:[a.jsxs(fe.Tr,{children:[a.jsx(fe.Td,{children:"Status"}),a.jsx(fe.Td,{children:a.jsx(Rm,{status:g})})]}),a.jsxs(fe.Tr,{children:[a.jsx(fe.Td,{children:"Version"}),a.jsx(fe.Td,{children:b})]}),a.jsxs(fe.Tr,{children:[a.jsx(fe.Td,{children:"Last Updated"}),a.jsx(fe.Td,{children:mr(j,void 0,{timeZoneName:"longOffset"})})]})]})}),a.jsx(pn,{my:"lg"}),a.jsx(Ie,{order:2,children:"Reload Config"}),a.jsx("p",{children:"Reload the configuration of this agent, syncing it with the current version of the Agent resource on the Medplum server."}),a.jsx(ke,{onClick:H,loading:l,disabled:P&&!l,"aria-label":"Reload config",children:"Reload Config"}),a.jsx(pn,{my:"lg"}),a.jsx(Ie,{order:2,children:"Upgrade Agent"}),a.jsx("p",{children:"Upgrade the version of this agent, to either the latest (default) or a specified version."}),a.jsx(ke,{onClick:U,loading:d,disabled:P&&!d,"aria-label":"Upgrade agent",children:"Upgrade"}),a.jsx(pn,{my:"lg"}),a.jsxs(ut,{onSubmit:O,children:[a.jsx(Ie,{order:2,children:"Fetch Logs"}),a.jsx("p",{children:"Fetch logs from the agent."}),k?.length?a.jsx(Pd,{block:!0,mb:15,children:k}):null,a.jsxs(ye,{children:[a.jsx(Oc,{w:100,id:"logLimit",name:"logLimit",placeholder:"20",label:"Log Limit"}),a.jsx(ke,{mt:22,loading:p,disabled:P&&!p,"aria-label":"Fetch logs",type:"submit",children:"Fetch Logs"})]})]}),a.jsx(pn,{my:"lg"}),a.jsx(Ie,{order:2,children:"Ping from Agent"}),a.jsx("p",{children:"Send a ping command from the agent to a valid IP address or hostname. Use this tool to troubleshoot local network connectivity."}),a.jsx(ut,{onSubmit:Y,children:a.jsxs(ye,{children:[a.jsx(Ve,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:a.jsx(bn,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:R,disabled:P&&!R,children:a.jsx(Uq,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),a.jsx(Oc,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!R&&T&&a.jsxs(a.Fragment,{children:[a.jsx(Ie,{order:5,mt:"sm",mb:0,children:"Last Ping"}),a.jsx("pre",{children:T})]})]})}function yre(){const e=wn(),t=Re(),[n,r]=v.useState();v.useEffect(()=>{t.get("auth/me",{cache:"no-cache"}).then(r).catch(l=>Ne({color:"red",message:Ye(l),autoClose:!1}))},[t]);function o(l){t.post("auth/revoke",{loginId:l}).then(()=>t.get("auth/me",{cache:"no-cache"})).then(r).then(()=>Ne({color:"green",message:"Login revoked"})).catch(c=>Ne({color:"red",message:Ye(c),autoClose:!1}))}return n?a.jsxs(a.Fragment,{children:[a.jsxs(lt,{children:[a.jsx(Ie,{children:"Security"}),a.jsxs(Cm,{children:[a.jsx(Ti,{term:"ID",children:a.jsx(Dt,{href:`/${_t(n.profile)}`,children:n.profile.id})}),a.jsx(Ti,{term:"Resource Type",children:n.profile.resourceType}),a.jsx(Ti,{term:"Name",children:Jc(n.profile.name?.[0])})]})]}),a.jsxs(lt,{children:[a.jsx(Ie,{children:"Sessions"}),a.jsxs(fe,{children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{children:"OS"}),a.jsx("th",{children:"Browser"}),a.jsx("th",{children:"IP Address"}),a.jsx("th",{children:"Auth Method"}),a.jsx("th",{children:"Last Updated"}),a.jsx("th",{})]})}),a.jsx("tbody",{children:n.security.sessions.map(l=>a.jsxs("tr",{children:[a.jsx("td",{children:l.os}),a.jsx("td",{children:l.browser}),a.jsx("td",{children:l.remoteAddress}),a.jsx("td",{children:l.authMethod}),a.jsx("td",{children:mr(l.lastUpdated)}),a.jsx("td",{children:a.jsx(Dt,{href:"#",onClick:()=>o(l.id),children:"Revoke"})})]},l.id))})]})]}),a.jsxs(lt,{children:[a.jsx(Ie,{children:"Password"}),a.jsx(ke,{onClick:()=>e("/changepassword")?.catch(console.error),children:"Change password"})]}),a.jsxs(lt,{children:[a.jsx(Ie,{children:"Multi Factor Auth"}),a.jsxs("p",{children:["Enrolled: ",n.security.mfaEnrolled.toString()]}),!n.security.mfaEnrolled&&a.jsx(ke,{onClick:()=>e("/mfa")?.catch(console.error),children:"Enroll"})]})]}):null}function xre(){const{id:e,secret:t}=Ut(),n=Re(),[r,o]=v.useState(),[l,c]=v.useState(!1),d=tu(r,void 0);return a.jsxs(lt,{width:450,children:[a.jsx(yr,{issues:d}),a.jsxs(ut,{onSubmit:f=>{if(f.password!==f.confirmPassword){o(xo("Passwords do not match","confirmPassword"));return}o(void 0);const p={id:e,secret:t,password:f.password};n.post("auth/setpassword",p).then(()=>c(!0)).catch(m=>o(qt(m)))},children:[a.jsxs(ar,{style:{flexDirection:"column"},children:[a.jsx(Mi,{size:32}),a.jsx(Ie,{children:"Set password"})]}),!l&&a.jsxs(Be,{children:[a.jsx(Qi,{name:"password",label:"New password",required:!0,error:At(r,"password")}),a.jsx(Qi,{name:"confirmPassword",label:"Confirm new password",required:!0,error:At(r,"confirmPassword")}),a.jsx(ye,{justify:"flex-end",mt:"xl",children:a.jsx(ke,{type:"submit",children:"Set password"})})]}),l&&a.jsxs("div",{"data-testid":"success",children:["Password set. You can now ",a.jsx(mt,{to:"/signin",children:"sign in"}),"."]})]})]})}function bre(){const e=Sm(),t=wn(),[n]=xS(),r=ef(),o=v.useCallback(()=>{const l=n.get("next");t(l?.startsWith("/")?l:"/")?.catch(console.error)},[n,t]);return v.useEffect(()=>{e&&n.has("next")&&o()},[e,n,o]),a.jsxs(rP,{onSuccess:()=>o(),onForgotPassword:()=>t("/resetpassword")?.catch(console.error),onRegister:Dk()?()=>t("/register")?.catch(console.error):void 0,googleClientId:r.googleClientId,login:n.get("login")||void 0,projectId:n.get("project")||void 0,children:[a.jsx(Mi,{size:32}),a.jsxs(Ie,{children:["Sign in to ",GA()]}),n.get("project")==="new"&&a.jsx("div",{children:"Sign in again to create a new project"})]})}function Sre(){const e=wn(),t=Gr(),[n,r]=v.useState(),[o,l]=v.useState(),[c,d]=v.useState();return v.useEffect(()=>{const f=Object.fromEntries(new URLSearchParams(t.search).entries());r(f.resourceType),l(f.query),d(JSON.parse(f.fields))},[t]),!n||!o||!c?null:a.jsx(hK,{resourceType:n,checkboxesEnabled:!0,query:o,fields:c,onClick:f=>e(`/${n}/${f.resource.id}`)?.catch(console.error),onAuxClick:f=>window.open(`/${n}/${f.resource.id}`,"_blank"),onBulk:f=>{e(`/bulk/${n}?ids=${f.join(",")}`)?.catch(console.error)}})}function wre(){const{id:e,secret:t}=Ut(),n=Re(),[r,o]=v.useState(),[l,c]=v.useState(!1),d=tu(r,void 0);return a.jsxs(lt,{width:450,children:[a.jsx(yr,{issues:d}),a.jsxs(ut,{onSubmit:()=>{o(void 0);const f={id:e,secret:t};n.post("auth/verifyemail",f).then(()=>c(!0)).catch(p=>o(qt(p)))},children:[a.jsxs(ar,{style:{flexDirection:"column"},children:[a.jsx(Mi,{size:32}),a.jsx(Ie,{children:"Email address verification required"})]}),!l&&a.jsxs(Be,{children:[a.jsx("p",{children:"In order to sign in, click the button below to verify your ability to receive email at the address this link was sent to."}),a.jsx(ye,{justify:"flex-end",mt:"xl",children:a.jsx(ke,{type:"submit",children:"Verify email"})})]}),l&&a.jsxs("div",{"data-testid":"success",children:["Email verified. You can now ",a.jsx(mt,{to:"/signin",children:"sign in"}),"."]})]})]})}function jre(){return a.jsx(HJ,{children:a.jsxs(Ue,{errorElement:a.jsx(nne,{}),children:[a.jsx(Ue,{path:"/signin",element:a.jsx(bre,{})}),a.jsx(Ue,{path:"/oauth",element:a.jsx(yne,{})}),a.jsx(Ue,{path:"/resetpassword",element:a.jsx(bne,{})}),a.jsx(Ue,{path:"/setpassword/:id/:secret",element:a.jsx(xre,{})}),a.jsx(Ue,{path:"/verifyemail/:id/:secret",element:a.jsx(wre,{})}),a.jsx(Ue,{path:"/register",element:a.jsx(xne,{})}),a.jsx(Ue,{path:"/changepassword",element:a.jsx(Jte,{})}),a.jsx(Ue,{path:"/security",element:a.jsx(yre,{})}),a.jsx(Ue,{path:"/mfa",element:a.jsx(mne,{})}),a.jsx(Ue,{path:"/batch",element:a.jsx(Xte,{})}),a.jsx(Ue,{path:"/bulk/:resourceType",element:a.jsx(Zte,{})}),a.jsx(Ue,{path:"/smart",element:a.jsx(Sre,{})}),a.jsx(Ue,{path:"/forms/:id",element:a.jsx(rne,{})}),a.jsx(Ue,{path:"/admin/super",element:a.jsx(Jee,{})}),a.jsx(Ue,{path:"/admin/super/asyncjob",element:a.jsx(Qee,{})}),a.jsx(Ue,{path:"/admin/super/db",element:a.jsx(zee,{})}),a.jsx(Ue,{path:"/admin/config",element:a.jsx(Fee,{})}),a.jsxs(Ue,{path:"/admin",element:a.jsx(Hee,{}),children:[a.jsx(Ue,{path:"patients",element:a.jsx(Vee,{})}),a.jsx(Ue,{path:"bots/new",element:a.jsx(Dee,{})}),a.jsx(Ue,{path:"bots",element:a.jsx(Ree,{})}),a.jsx(Ue,{path:"clients/new",element:a.jsx(Aee,{})}),a.jsx(Ue,{path:"clients",element:a.jsx(_ee,{})}),a.jsx(Ue,{path:"details",element:a.jsx(cR,{})}),a.jsx(Ue,{path:"invite",element:a.jsx(Bee,{})}),a.jsx(Ue,{path:"users",element:a.jsx(nte,{})}),a.jsx(Ue,{path:"project",element:a.jsx(cR,{})}),a.jsx(Ue,{path:"secrets",element:a.jsx(qee,{})}),a.jsx(Ue,{path:"sites",element:a.jsx(Gee,{})}),a.jsx(Ue,{path:"members/:membershipId",element:a.jsx(Uee,{})})]}),a.jsx(Ue,{path:"/lab/assays",element:a.jsx(hne,{})}),a.jsx(Ue,{path:"/lab/panels",element:a.jsx(pne,{})}),a.jsxs(Ue,{path:"/:resourceType/new",element:a.jsx(tne,{}),children:[a.jsx(Ue,{index:!0,element:a.jsx(Uy,{})}),a.jsx(Ue,{path:"form",element:a.jsx(Uy,{})}),a.jsx(Ue,{path:"json",element:a.jsx(Fne,{})}),a.jsx(Ue,{path:"profiles",element:a.jsx(Uy,{})})]}),a.jsxs(Ue,{path:"/:resourceType/:id",element:a.jsx(hre,{}),children:[a.jsx(Ue,{index:!0,element:a.jsx(RR,{})}),a.jsx(Ue,{path:"apply",element:a.jsx(wne,{})}),a.jsx(Ue,{path:"apps",element:a.jsx(jne,{})}),a.jsx(Ue,{path:"event",element:a.jsx(Ene,{})}),a.jsx(Ue,{path:"blame",element:a.jsx(Tne,{})}),a.jsx(Ue,{path:"bots",element:a.jsx(Yne,{})}),a.jsx(Ue,{path:"builder",element:a.jsx(Mne,{})}),a.jsx(Ue,{path:"checklist",element:a.jsx(Lne,{})}),a.jsx(Ue,{path:"delete",element:a.jsx(Ine,{})}),a.jsx(Ue,{path:"details",element:a.jsx(Une,{})}),a.jsx(Ue,{path:"edit",element:a.jsx(Bne,{})}),a.jsx(Ue,{path:"editor",element:a.jsx(Nne,{})}),a.jsxs(Ue,{path:"history",children:[a.jsx(Ue,{index:!0,element:a.jsx(TR,{})}),a.jsx(Ue,{path:":versionId/:tab",element:a.jsx(Ah,{})}),a.jsx(Ue,{path:":versionId",element:a.jsx(Ah,{})})]}),a.jsxs(Ue,{path:"_history",children:[a.jsx(Ue,{index:!0,element:a.jsx(TR,{})}),a.jsx(Ue,{path:":versionId/:tab",element:a.jsx(Ah,{})}),a.jsx(Ue,{path:":versionId",element:a.jsx(Ah,{})})]}),a.jsx(Ue,{path:"json",element:a.jsx(Hne,{})}),a.jsx(Ue,{path:"preview",element:a.jsx(qne,{})}),a.jsx(Ue,{path:"responses",element:a.jsx(Xne,{})}),a.jsx(Ue,{path:"report",element:a.jsx(Jne,{})}),a.jsx(Ue,{path:"ranges",element:a.jsx(Zne,{})}),a.jsx(Ue,{path:"subscriptions",element:a.jsx(pre,{})}),a.jsx(Ue,{path:"timeline",element:a.jsx(RR,{})}),a.jsx(Ue,{path:"tools",element:a.jsx(vre,{})}),a.jsx(Ue,{path:"profiles",element:a.jsx(Gne,{})}),a.jsx(Ue,{path:"export",element:a.jsx(Vne,{})})]}),a.jsx(Ue,{path:"/:resourceType",element:a.jsx(jR,{})}),a.jsx(Ue,{path:"/",element:a.jsx(jR,{})})]})})}function Cre(){const e=Re(),t=e.getUserConfiguration(),n=Gr(),[r]=xS();return e.isLoading()?a.jsx(Di,{}):a.jsx(eQ,{logo:a.jsx(Mi,{size:24}),pathname:n.pathname,searchParams:r,version:xA,menus:Ere(t),displayAddBookmark:!!t?.id,children:a.jsx(v.Suspense,{fallback:a.jsx(Di,{}),children:a.jsx(jre,{})})})}function Ere(e){const t=e?.menu?.map(n=>({title:n.title,links:n.link?.map(r=>({label:r.name,href:r.target,icon:Tre(r.target)}))||[]}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:a.jsx(fq,{})}]}),t}const _R={Patient:Yq,Practitioner:sq,Organization:CH,ServiceRequest:Nq,DiagnosticReport:zq,Questionnaire:oq,admin:yH,AccessPolicy:uq,Subscription:oG,batch:Cq,Observation:bq};function Tre(e){if(e.includes("admin/super/db"))return a.jsx(BH,{});try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in _R){const n=_R[t];return a.jsx(n,{})}}catch{}return a.jsx(cm,{w:30})}async function Rre(){const e=ef(),t=new bA({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=pee([{path:"*",element:a.jsx(Cre,{})}]),o=c=>r.navigate(c);hZ.createRoot(document.getElementById("root")).render(a.jsx(v.StrictMode,{children:a.jsx(wF,{medplum:t,navigate:o,children:a.jsxs(JR,{theme:n,children:[a.jsx(Sa,{position:"bottom-right"}),a.jsx(UJ,{router:r})]})})}))}Rre().catch(console.error);
607
- //# sourceMappingURL=index-B5mDagDt.js.map
607
+ //# sourceMappingURL=index-DAMfHhqQ.js.map