@medplum/app 3.2.21 → 3.2.22

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.
@@ -98,7 +98,7 @@ Error generating stack: `+i.message+`
98
98
  *
99
99
  * Copy of "partysocket" from Partykit team, a fork of the original "Reconnecting WebSocket"
100
100
  * https://github.com/partykit/partykit/blob/main/packages/partysocket
101
- */const Wa={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let Ew=!1;function N8(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Wa.Event=globalThis.Event,Wa.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Wa.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function M8(e,t){if(!e)throw new Error(t)}function ld(e){return new e.constructor(e.type,e)}const Ji={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1};let Tw=!1;class fi extends Hh{constructor(t,n,r={}){Ew||(N8(),Ew=!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:i=Ji.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),i),M8(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(a=>{var l;return(l=this._ws)==null?void 0:l.send(a)}),this._messageQueue=[],this.onopen&&this.onopen(o),this.dispatchEvent(ld(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(ld(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(ld(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(ld(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 fi.CONNECTING}get OPEN(){return fi.OPEN}get CLOSING(){return fi.CLOSING}get CLOSED(){return fi.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){var n;return this._messageQueue.reduce((r,o)=>(typeof o=="string"?r+=o.length:o instanceof Blob?r+=o.size:r+=o.byteLength,r),0)+(((n=this._ws)==null?void 0:n.bufferedAmount)??0)}get extensions(){var t;return((t=this._ws)==null?void 0:t.extensions)??""}get protocol(){var t;return((t=this._ws)==null?void 0:t.protocol)??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?fi.CLOSED:fi.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=Ji.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=Ji.reconnectionDelayGrowFactor,minReconnectionDelay:n=Ji.minReconnectionDelay,maxReconnectionDelay:r=Ji.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=Ji.maxRetries,connectionTimeout:n=Ji.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"&&!Tw&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),Tw=!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 Wa.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Wa.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Wa.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 O8=5e3;class Og extends Hh{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 L8{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new Og(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class $8{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof Jk))throw new Fe(Dt("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new Fe(Dt("Not a valid URL"))}const i=r!=null&&r.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger}):new fi(o,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=i,this.masterSubEmitter=new Og,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??O8,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,o,i,a,l,c;try{const u=JSON.parse(n.data);if(u.type==="pong"){this.waitingForPong=!1;return}const d=u,f=(o=(r=d==null?void 0:d.entry)==null?void 0:r[0])==null?void 0:o.resource;if(f.type==="heartbeat"){(i=this.masterSubEmitter)==null||i.dispatchEvent({type:"heartbeat",payload:d});return}if(f.type==="handshake"){const m=sl(f.subscription),g={type:"connect",payload:{subscriptionId:m}};(a=this.masterSubEmitter)==null||a.dispatchEvent(g);const v=this.criteriaEntriesBySubscriptionId.get(m);if(!v){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}v.connecting=!1,v.emitter.dispatchEvent({...g});return}(l=this.masterSubEmitter)==null||l.dispatchEvent({type:"message",payload:d});const h=this.criteriaEntriesBySubscriptionId.get(sl(f.subscription));if(!h){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}h.emitter.dispatchEvent({type:"message",payload:d})}catch(u){console.error(u);const d={type:"error",payload:u};(c=this.masterSubEmitter)==null||c.dispatchEvent(d);for(const f of this.getAllCriteriaEmitters())f.dispatchEvent({...d})}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new Fe(d7(new Error("WebSocket error")))};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const o of this.getAllCriteriaEmitters())o.dispatchEvent({...n})}),t.addEventListener("close",()=>{var r,o;const n={type:"close"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),(o=this.masterSubEmitter)==null||o.removeAllListeners())}),t.addEventListener("open",()=>{var r;const n={type:"open"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const o of this.getAllCriteriaEmitters())o.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{var r;const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&((r=this.currentProfile)==null?void 0:r.id)!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){var o;const r={type:"error",payload:n};(o=this.masterSubEmitter)==null||o.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){var r;const{subscriptionId:n}=t;if(n){const o={type:"disconnect",payload:{subscriptionId:n}};(r=this.masterSubEmitter)==null||r.dispatchEvent(o),t.emitter.dispatchEvent({...o})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){var a,l;let n=t==null?void 0:t.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${ct(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=(a=r==null?void 0:r.find(c=>c.name==="token"))==null?void 0:a.valueString,i=(l=r==null?void 0:r.find(c=>c.name==="websocket-url"))==null?void 0:l.valueUrl;if(!o)throw new Fe(Dt("Failed to get token"));if(!i)throw new Fe(Dt("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(Ai(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){var l;const{criteria:n,subscriptionProps:r,subscriptionId:o,token:i}=t;if(!this.criteriaEntries.has(n))return;const a=this.criteriaEntries.get(n);r?a.criteriaWithProps=a.criteriaWithProps.filter(c=>{const u=c.subscriptionProps;return!Ai(r,u)}):a.bareCriteria=void 0,!a.bareCriteria&&a.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),(l=this.masterSubEmitter)==null||l._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),i&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:i}}))}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(Ie(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 L8(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 Og(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const F8="3.2.21-c76aa3890",z8=sn.FHIR_JSON+", */*; q=0.1",U8="https://api.medplum.com/",B8=1e3,V8=6e4,W8=0,H8=3e5,q8="Binary/",Pw={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]};class Jk extends Hh{constructor(t){if(super(),this.initComplete=!0,t!=null&&t.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=(t==null?void 0:t.fetch)??G8(),this.storage=(t==null?void 0:t.storage)??new I8,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=Ik((t==null?void 0:t.baseUrl)??U8),this.fhirBaseUrl=io(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=io(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=io(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=io(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=io(this.baseUrl,(t==null?void 0:t.fhircastHubUrl)??"fhircast/STU3"),this.clientId=(t==null?void 0:t.clientId)??"",this.clientSecret=(t==null?void 0:t.clientSecret)??"",this.onUnauthenticated=t==null?void 0:t.onUnauthenticated,this.refreshGracePeriod=(t==null?void 0:t.refreshGracePeriod)??H8,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?W8:V8),this.cacheTime>0?this.requestCache=new Kk((t==null?void 0:t.resourceCacheSize)??B8):this.requestCache=void 0,t!=null&&t.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t!=null&&t.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}clear(){this.storage.clear(),typeof window<"u"&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){var t;this.storage.setString("activeLogin",void 0),(t=this.requestCache)==null||t.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){var n;t=t.toString(),(n=this.requestCache)==null||n.delete(t)}invalidateAll(){var t;(t=this.requestCache)==null||t.clear()}invalidateSearches(t){const n=io(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?o=new Promise((a,l)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:a,reject:l}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const i=new Mr(o);return this.setCacheEntry(t,i),i}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,sn.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(window.location.search).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,o,i=!0){let a=o;i&&(a=await this.ensureCodeChallenge(o)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,a,i))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");const r=new URLSearchParams;return r.set("grant_type","urn:ietf:params:oauth:grant-type:token-exchange"),r.set("subject_token_type","urn:ietf:params:oauth:token-type:access_token"),r.set("client_id",n),r.set("subject_token",t),this.fetchTokens(r)}getExternalAuthRedirectUri(t,n,r,o,i=!0){const a=new URL(t);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",n),a.searchParams.set("redirect_uri",r),a.searchParams.set("scope",o.scope??"openid profile email"),a.searchParams.set("state",JSON.stringify(o)),i){const{codeChallenge:l,codeChallengeMethod:c}=o;if(!c)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!l)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");a.searchParams.set("code_challenge_method",c),a.searchParams.set("code_challenge",l)}return a.toString()}fhirUrl(...t){return new URL(io(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=B6(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),i="search-"+o.toString(),a=this.getCacheEntry(i,r);if(a)return a.value;const l=new Mr((async()=>{const c=await this.get(o,r);if(c.entry)for(const u of c.entry)this.cacheResource(u.resource);return c})());return this.setCacheEntry(i,l),l}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const i="searchOne-"+o.toString(),a=this.getCacheEntry(i,r);if(a)return a.value;const l=new Mr(this.search(t,o.searchParams,r).then(c=>{var u,d;return(d=(u=c.entry)==null?void 0:u[0])==null?void 0:d.resource}));return this.setCacheEntry(i,l),l}searchResources(t,n,r){const i="searchResources-"+this.fhirSearchUrl(t,n).toString(),a=this.getCacheEntry(i,r);if(a)return a.value;const l=new Mr(this.search(t,n,r).then(_w));return this.setCacheEntry(i,l),l}async*searchResourcePages(t,n,r){var i,a;let o=this.fhirSearchUrl(t,n);for(;o;){const l=new URL(o).searchParams,c=await this.search(t,l,r),u=(i=c.link)==null?void 0:i.find(d=>d.relation==="next");if(!((a=c.entry)!=null&&a.length)&&!u)break;yield _w(c),o=u!=null&&u.url?new URL(u.url):void 0}}searchValueSet(t,n,r){return this.valueSetExpand({url:t,filter:n},r)}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){var o,i;const r=(i=(o=this.requestCache)==null?void 0:o.get(this.fhirUrl(t,n).toString()))==null?void 0:i.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return Pw;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 Mr(Promise.reject(new Error("Missing reference")));if(r==="system")return new Mr(Promise.resolve(Pw));const[o,i]=r.split("/");return!o||!i?new Mr(Promise.reject(new Error("Invalid reference"))):this.readResource(o,i,n)}requestSchema(t){if(xk(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Mr((async()=>{const i=`{
101
+ */const Wa={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let Ew=!1;function N8(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Wa.Event=globalThis.Event,Wa.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Wa.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function M8(e,t){if(!e)throw new Error(t)}function ld(e){return new e.constructor(e.type,e)}const Ji={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1};let Tw=!1;class fi extends Hh{constructor(t,n,r={}){Ew||(N8(),Ew=!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:i=Ji.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),i),M8(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(a=>{var l;return(l=this._ws)==null?void 0:l.send(a)}),this._messageQueue=[],this.onopen&&this.onopen(o),this.dispatchEvent(ld(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(ld(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(ld(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(ld(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 fi.CONNECTING}get OPEN(){return fi.OPEN}get CLOSING(){return fi.CLOSING}get CLOSED(){return fi.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){var n;return this._messageQueue.reduce((r,o)=>(typeof o=="string"?r+=o.length:o instanceof Blob?r+=o.size:r+=o.byteLength,r),0)+(((n=this._ws)==null?void 0:n.bufferedAmount)??0)}get extensions(){var t;return((t=this._ws)==null?void 0:t.extensions)??""}get protocol(){var t;return((t=this._ws)==null?void 0:t.protocol)??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?fi.CLOSED:fi.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=Ji.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=Ji.reconnectionDelayGrowFactor,minReconnectionDelay:n=Ji.minReconnectionDelay,maxReconnectionDelay:r=Ji.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=Ji.maxRetries,connectionTimeout:n=Ji.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"&&!Tw&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),Tw=!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 Wa.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Wa.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Wa.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 O8=5e3;class Og extends Hh{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 L8{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new Og(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class $8{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof Jk))throw new Fe(Dt("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new Fe(Dt("Not a valid URL"))}const i=r!=null&&r.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger}):new fi(o,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=i,this.masterSubEmitter=new Og,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??O8,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,o,i,a,l,c;try{const u=JSON.parse(n.data);if(u.type==="pong"){this.waitingForPong=!1;return}const d=u,f=(o=(r=d==null?void 0:d.entry)==null?void 0:r[0])==null?void 0:o.resource;if(f.type==="heartbeat"){(i=this.masterSubEmitter)==null||i.dispatchEvent({type:"heartbeat",payload:d});return}if(f.type==="handshake"){const m=sl(f.subscription),g={type:"connect",payload:{subscriptionId:m}};(a=this.masterSubEmitter)==null||a.dispatchEvent(g);const v=this.criteriaEntriesBySubscriptionId.get(m);if(!v){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}v.connecting=!1,v.emitter.dispatchEvent({...g});return}(l=this.masterSubEmitter)==null||l.dispatchEvent({type:"message",payload:d});const h=this.criteriaEntriesBySubscriptionId.get(sl(f.subscription));if(!h){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}h.emitter.dispatchEvent({type:"message",payload:d})}catch(u){console.error(u);const d={type:"error",payload:u};(c=this.masterSubEmitter)==null||c.dispatchEvent(d);for(const f of this.getAllCriteriaEmitters())f.dispatchEvent({...d})}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new Fe(d7(new Error("WebSocket error")))};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const o of this.getAllCriteriaEmitters())o.dispatchEvent({...n})}),t.addEventListener("close",()=>{var r,o;const n={type:"close"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),(o=this.masterSubEmitter)==null||o.removeAllListeners())}),t.addEventListener("open",()=>{var r;const n={type:"open"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const o of this.getAllCriteriaEmitters())o.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{var r;const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&((r=this.currentProfile)==null?void 0:r.id)!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){var o;const r={type:"error",payload:n};(o=this.masterSubEmitter)==null||o.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){var r;const{subscriptionId:n}=t;if(n){const o={type:"disconnect",payload:{subscriptionId:n}};(r=this.masterSubEmitter)==null||r.dispatchEvent(o),t.emitter.dispatchEvent({...o})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){var a,l;let n=t==null?void 0:t.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${ct(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=(a=r==null?void 0:r.find(c=>c.name==="token"))==null?void 0:a.valueString,i=(l=r==null?void 0:r.find(c=>c.name==="websocket-url"))==null?void 0:l.valueUrl;if(!o)throw new Fe(Dt("Failed to get token"));if(!i)throw new Fe(Dt("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(Ai(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){var l;const{criteria:n,subscriptionProps:r,subscriptionId:o,token:i}=t;if(!this.criteriaEntries.has(n))return;const a=this.criteriaEntries.get(n);r?a.criteriaWithProps=a.criteriaWithProps.filter(c=>{const u=c.subscriptionProps;return!Ai(r,u)}):a.bareCriteria=void 0,!a.bareCriteria&&a.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),(l=this.masterSubEmitter)==null||l._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),i&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:i}}))}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(Ie(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 L8(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 Og(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const F8="3.2.22-a936b292a",z8=sn.FHIR_JSON+", */*; q=0.1",U8="https://api.medplum.com/",B8=1e3,V8=6e4,W8=0,H8=3e5,q8="Binary/",Pw={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]};class Jk extends Hh{constructor(t){if(super(),this.initComplete=!0,t!=null&&t.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=(t==null?void 0:t.fetch)??G8(),this.storage=(t==null?void 0:t.storage)??new I8,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=Ik((t==null?void 0:t.baseUrl)??U8),this.fhirBaseUrl=io(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=io(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=io(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=io(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=io(this.baseUrl,(t==null?void 0:t.fhircastHubUrl)??"fhircast/STU3"),this.clientId=(t==null?void 0:t.clientId)??"",this.clientSecret=(t==null?void 0:t.clientSecret)??"",this.onUnauthenticated=t==null?void 0:t.onUnauthenticated,this.refreshGracePeriod=(t==null?void 0:t.refreshGracePeriod)??H8,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?W8:V8),this.cacheTime>0?this.requestCache=new Kk((t==null?void 0:t.resourceCacheSize)??B8):this.requestCache=void 0,t!=null&&t.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t!=null&&t.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}clear(){this.storage.clear(),typeof window<"u"&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){var t;this.storage.setString("activeLogin",void 0),(t=this.requestCache)==null||t.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){var n;t=t.toString(),(n=this.requestCache)==null||n.delete(t)}invalidateAll(){var t;(t=this.requestCache)==null||t.clear()}invalidateSearches(t){const n=io(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?o=new Promise((a,l)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:a,reject:l}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const i=new Mr(o);return this.setCacheEntry(t,i),i}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,sn.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(window.location.search).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,o,i=!0){let a=o;i&&(a=await this.ensureCodeChallenge(o)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,a,i))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");const r=new URLSearchParams;return r.set("grant_type","urn:ietf:params:oauth:grant-type:token-exchange"),r.set("subject_token_type","urn:ietf:params:oauth:token-type:access_token"),r.set("client_id",n),r.set("subject_token",t),this.fetchTokens(r)}getExternalAuthRedirectUri(t,n,r,o,i=!0){const a=new URL(t);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",n),a.searchParams.set("redirect_uri",r),a.searchParams.set("scope",o.scope??"openid profile email"),a.searchParams.set("state",JSON.stringify(o)),i){const{codeChallenge:l,codeChallengeMethod:c}=o;if(!c)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!l)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");a.searchParams.set("code_challenge_method",c),a.searchParams.set("code_challenge",l)}return a.toString()}fhirUrl(...t){return new URL(io(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=B6(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),i="search-"+o.toString(),a=this.getCacheEntry(i,r);if(a)return a.value;const l=new Mr((async()=>{const c=await this.get(o,r);if(c.entry)for(const u of c.entry)this.cacheResource(u.resource);return c})());return this.setCacheEntry(i,l),l}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const i="searchOne-"+o.toString(),a=this.getCacheEntry(i,r);if(a)return a.value;const l=new Mr(this.search(t,o.searchParams,r).then(c=>{var u,d;return(d=(u=c.entry)==null?void 0:u[0])==null?void 0:d.resource}));return this.setCacheEntry(i,l),l}searchResources(t,n,r){const i="searchResources-"+this.fhirSearchUrl(t,n).toString(),a=this.getCacheEntry(i,r);if(a)return a.value;const l=new Mr(this.search(t,n,r).then(_w));return this.setCacheEntry(i,l),l}async*searchResourcePages(t,n,r){var i,a;let o=this.fhirSearchUrl(t,n);for(;o;){const l=new URL(o).searchParams,c=await this.search(t,l,r),u=(i=c.link)==null?void 0:i.find(d=>d.relation==="next");if(!((a=c.entry)!=null&&a.length)&&!u)break;yield _w(c),o=u!=null&&u.url?new URL(u.url):void 0}}searchValueSet(t,n,r){return this.valueSetExpand({url:t,filter:n},r)}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){var o,i;const r=(i=(o=this.requestCache)==null?void 0:o.get(this.fhirUrl(t,n).toString()))==null?void 0:i.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return Pw;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 Mr(Promise.reject(new Error("Missing reference")));if(r==="system")return new Mr(Promise.resolve(Pw));const[o,i]=r.split("/");return!o||!i?new Mr(Promise.reject(new Error("Invalid reference"))):this.readResource(o,i,n)}requestSchema(t){if(xk(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Mr((async()=>{const i=`{
102
102
  StructureDefinitionList(name: "${t}") {
103
103
  resourceType,
104
104
  name,
@@ -138,7 +138,7 @@ Error generating stack: `+i.message+`
138
138
  expression,
139
139
  target
140
140
  }
141
- }`.replace(/\s+/g," "),a=await this.graphql(i);lw(a.data.StructureDefinitionList);for(const l of a.data.SearchParameterList)tF(l)})());return this.setCacheEntry(n,o),o}requestProfileSchema(t,n){if(!(n!=null&&n.expandProfile)&&Lx(t))return Promise.resolve();const r=t+"-requestSchema"+(n!=null&&n.expandProfile?"-nested":""),o=this.getCacheEntry(r,void 0);if(o)return o.value;const i=new Mr((async()=>{if(n!=null&&n.expandProfile){const a=this.fhirUrl("StructureDefinition","$expand-profile");a.search=new URLSearchParams({url:t}).toString();const l=await this.post(a.toString(),{});lw(l)}else{const a=await this.searchOne("StructureDefinition",{url:t,_sort:"-_lastUpdated"});if(!a){console.warn(`No StructureDefinition found for ${t}!`);return}yk(a)}})());return this.setCacheEntry(r,i),i}readHistory(t,n,r){return this.get(this.fhirUrl(t,n,"_history"),r)}readVersion(t,n,r,o){return this.get(this.fhirUrl(t,n,"_history",r),o)}readPatientEverything(t,n){return this.get(this.fhirUrl("Patient",t,"$everything"),n)}createResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(t.resourceType),this.post(this.fhirUrl(t.resourceType),t,void 0,n)}async createResourceIfNoneExist(t,n,r){return await this.searchOne(t.resourceType,n,r)??this.createResource(t,r)}async upsertResource(t,n,r){const o=this.fhirSearchUrl(t.resourceType,n);let i=await this.put(o,t,void 0,r);return i||(i=t),this.cacheResource(i),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),i}async createAttachment(t,n,r,o,i){const a=Dw(t,n,r,o),l=i??(typeof n=="object"?n:{}),c=await this.createBinary(a,l);return{contentType:a.contentType,url:c.url,title:a.filename}}createBinary(t,n,r,o,i){const a=Dw(t,n,r,o),l=i??(typeof n=="object"?n:{}),{data:c,contentType:u,filename:d,securityContext:f,onProgress:h}=a,m=this.fhirUrl("Binary");return d&&m.searchParams.set("_filename",d),f!=null&&f.reference&&this.setRequestHeader(l,"X-Security-Context",f.reference),h?this.uploadwithProgress(m,c,u,h,l):this.post(m,c,u,l)}uploadwithProgress(t,n,r,o,i){return new Promise((a,l)=>{var f;const c=new XMLHttpRequest,u=()=>c.abort();(f=i==null?void 0:i.signal)==null||f.addEventListener("abort",u);const d=h=>{var m;(m=i==null?void 0:i.signal)==null||m.removeEventListener("abort",u),h instanceof Error?l(h):a(h)};if(c.responseType="json",c.onabort=()=>d(new DOMException("Request aborted","AbortError")),c.onerror=()=>d(new Error("Request error")),o&&(c.upload.onprogress=h=>o(h),c.upload.onload=h=>o(h)),c.onload=()=>{c.status>=200&&c.status<300?d(c.response):d(new Fe(mt(c.response||c.statusText)))},c.open("POST",t),c.withCredentials=!0,c.setRequestHeader("Authorization","Bearer "+this.accessToken),c.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),c.setRequestHeader("Content-Type",r),this.options.extendedMode!==!1&&c.setRequestHeader("X-Medplum","extended"),i!=null&&i.headers){const h=i.headers;for(const[m,g]of Object.entries(h))c.setRequestHeader(m,g)}c.send(n)})}async createPdf(t,n,r,o){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");const i=Y8(t,n,r,o),a=typeof n=="object"?n:{},{docDefinition:l,tableLayouts:c,fonts:u,...d}=i,f=await this.createPdfImpl(l,c,u),h={...d,data:f,contentType:"application/pdf"};return this.createBinary(h,a)}createComment(t,n,r){const o=this.getProfile();let i,a;return t.resourceType==="Encounter"&&(i=Tt(t),a=t.subject),t.resourceType==="ServiceRequest"&&(i=t.encounter,a=t.subject),t.resourceType==="Patient"&&(a=Tt(t)),this.createResource({resourceType:"Communication",status:"completed",basedOn:[Tt(t)],encounter:i,subject:a,sender:o?Tt(o):void 0,sent:new Date().toISOString(),payload:[{contentString:n}]},r)}async updateResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");if(!t.id)throw new Error("Missing id");let r=await this.put(this.fhirUrl(t.resourceType,t.id),t,void 0,n);return r||(r=t),this.cacheResource(r),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),r}async patchResource(t,n,r,o){const i=await this.patch(this.fhirUrl(t,n),r,o);return this.cacheResource(i),this.invalidateUrl(this.fhirUrl(t,n,"_history")),this.invalidateSearches(t),i}deleteResource(t,n,r){return this.deleteCacheEntry(this.fhirUrl(t,n).toString()),this.invalidateSearches(t),this.delete(this.fhirUrl(t,n),r)}validateResource(t,n){return this.post(this.fhirUrl(t.resourceType,"$validate"),t,void 0,n)}executeBot(t,n,r,o){let i;if(typeof t=="string"){const a=t;i=this.fhirUrl("Bot",a,"$execute")}else{const a=t;i=this.fhirUrl("Bot","$execute"),i.searchParams.set("identifier",a.system+"|"+a.value)}return this.post(i,n,r,o)}executeBatch(t,n){return this.post(this.fhirBaseUrl,t,void 0,n)}sendEmail(t,n){return this.post("email/v1/send",t,sn.JSON,n)}graphql(t,n,r,o){return this.post(this.fhirUrl("$graphql"),{query:t,operationName:n,variables:r},sn.JSON,o)}readResourceGraph(t,n,r,o){return this.get(`${this.fhirUrl(t,n)}/$graph?graph=${r}`,o)}pushToAgent(t,n,r,o,i,a){return this.post(this.fhirUrl("Agent",sl(t),"$push"),{destination:typeof n=="string"?n:ct(n),body:r,contentType:o,waitForResponse:i},sn.FHIR_JSON,a)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(t){var n,r;(!((n=this.sessionDetails)!=null&&n.profile)||ct(this.sessionDetails.profile)!==((r=t.profile)==null?void 0:r.reference))&&this.clearActiveLogin(),this.setAccessToken(t.accessToken,t.refreshToken),this.storage.setObject("activeLogin",t),this.addLogin(t),this.refreshPromise=void 0,await this.refreshProfile()}getAccessToken(){return this.accessToken}setAccessToken(t,n){this.accessToken=t,this.refreshToken=n,this.accessTokenExpires=_8(t),this.medplumServer=R8(t)}getLogins(){return this.storage.getObject("logins")??[]}addLogin(t){const n=this.getLogins().filter(r=>{var o,i;return((o=r.profile)==null?void 0:o.reference)!==((i=t.profile)==null?void 0:i.reference)});n.push(t),this.storage.setObject("logins",n)}async refreshProfile(){return this.medplumServer?(this.profilePromise=new Promise((t,n)=>{this.get("auth/me",{cache:"no-cache"}).then(r=>{var i,a;this.profilePromise=void 0;const o=((a=(i=this.sessionDetails)==null?void 0:i.profile)==null?void 0:a.id)!==r.profile.id;this.sessionDetails=r,o&&this.dispatchEvent({type:"change"}),t(r.profile),this.dispatchEvent({type:"profileRefreshed"})}).catch(n)}),this.dispatchEvent({type:"profileRefreshing"}),this.profilePromise):Promise.resolve(void 0)}isLoading(){var t;return!this.isInitialized||!!this.profilePromise&&!((t=this.sessionDetails)!=null&&t.profile)}isSuperAdmin(){var t;return!!((t=this.sessionDetails)!=null&&t.project.superAdmin)}isProjectAdmin(){var t;return!!((t=this.sessionDetails)!=null&&t.membership.admin)}getProject(){var t;return(t=this.sessionDetails)==null?void 0:t.project}getProjectMembership(){var t;return(t=this.sessionDetails)==null?void 0:t.membership}getProfile(){var t;return(t=this.sessionDetails)==null?void 0:t.profile}async getProfileAsync(){return this.profilePromise?this.profilePromise:this.sessionDetails?this.sessionDetails.profile:this.refreshProfile()}getUserConfiguration(){var t;return(t=this.sessionDetails)==null?void 0:t.config}getAccessPolicy(){var t;return(t=this.sessionDetails)==null?void 0:t.accessPolicy}async download(t,n={}){this.refreshPromise&&await this.refreshPromise;const r=t.toString();r.startsWith(q8)&&(t=this.fhirUrl(r));let o=n.headers;return o||(o={},n.headers=o),o.Accept||(o.Accept="*/*"),this.addFetchOptionsDefaults(n),(await this.fetchWithRetry(t.toString(),n)).blob()}async createMedia(t,n){const{additionalFields:r,...o}=t,i=await this.createResource({resourceType:"Media",status:"preparation",content:{contentType:t.contentType},...r});o.securityContext||(o.securityContext=Tt(i));const a=await this.createAttachment(o,n);return this.updateResource({...i,status:"completed",content:a})}async uploadMedia(t,n,r,o,i){return this.createMedia({data:t,contentType:n,filename:r,additionalFields:o},i)}async bulkExport(t="",n,r,o){const i=t&&`${t}/`,a=this.fhirUrl(`${i}$export`);return n&&a.searchParams.set("_type",n),r&&a.searchParams.set("_since",r),this.startAsyncRequest(a.toString(),o)}async startAsyncRequest(t,n={}){this.addFetchOptionsDefaults(n);const r=n.headers;return r.Prefer="respond-async",this.request("POST",t,n)}get keyValue(){return this.keyValueClient||(this.keyValueClient=new D8(this)),this.keyValueClient}getCacheEntry(t,n){if(!this.requestCache||(n==null?void 0:n.cache)==="no-cache"||(n==null?void 0:n.cache)==="reload")return;const r=this.requestCache.get(t);if(!(!r||r.requestTime+this.cacheTime<Date.now()))return r}setCacheEntry(t,n){this.requestCache&&this.requestCache.set(t,{requestTime:Date.now(),value:n})}cacheResource(t){var n,r;t!=null&&t.id&&!((r=(n=t.meta)==null?void 0:n.tag)!=null&&r.some(o=>o.code==="SUBSETTED"))&&this.setCacheEntry(this.fhirUrl(t.resourceType,t.id).toString(),new Mr(Promise.resolve(t)))}deleteCacheEntry(t){this.requestCache&&this.requestCache.delete(t)}async request(t,n,r={},o={}){await this.refreshIfExpired(),r.method=t,this.addFetchOptionsDefaults(r);const i=await this.fetchWithRetry(n,r);if(i.status===401)return this.handleUnauthenticated(t,n,r);if(i.status===204||i.status===304)return;const a=i.headers.get("content-type"),l=a==null?void 0:a.includes("json");if(i.status===404&&!l)throw new Fe(c7);const c=await this.parseBody(i,l);if(i.status===200&&r.followRedirectOnOk||i.status===201&&r.followRedirectOnCreated){const u=await Rw(i,c);if(u)return this.request("GET",u,{...r,body:void 0})}if(i.status===202&&r.pollStatusOnAccepted){const d=await Rw(i,c)??o.statusUrl;if(d)return this.pollStatus(d,r,o)}if(i.status>=400)throw new Fe(mt(c));return c}async parseBody(t,n){let r;if(n)try{r=await t.json()}catch(o){throw console.error("Error parsing response",t.status,o),o}else r=await t.text();return r}async fetchWithRetry(t,n){t.startsWith("http")||(t=io(this.baseUrl,t));const r=(n==null?void 0:n.maxRetries)??2,o=200;for(let i=0;i<=r;i++){try{this.options.verbose&&this.logRequest(t,n);const a=await this.fetch(t,n);if(this.options.verbose&&this.logResponse(a),a.status<500||i===r)return a}catch(a){if(a.message==="Failed to fetch"&&i===0&&this.dispatchEvent({type:"offline"}),a.name==="AbortError"||i===r)throw a}await gw(o)}throw new Error("Unreachable")}logRequest(t,n){if(console.log(`> ${n.method} ${t}`),n.headers){const r=n.headers;for(const o of Uc(Object.keys(r)))console.log(`> ${o}: ${r[o]}`)}}logResponse(t){console.log(`< ${t.status} ${t.statusText}`),t.headers&&t.headers.forEach((n,r)=>console.log(`< ${r}: ${n}`))}async pollStatus(t,n,r){const o={...n,method:"GET",body:void 0,redirect:"follow"};if(r.pollCount===void 0)n.headers&&typeof n.headers=="object"&&"Prefer"in n.headers&&(o.headers={...n.headers},delete o.headers.Prefer),r.statusUrl=t,r.pollCount=1;else{const i=n.pollStatusPeriod??1e3;await gw(i),r.pollCount++}return this.request("GET",t,o,r)}async executeAutoBatch(){var o,i;if(this.autoBatchQueue===void 0)return;const t=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,t.length===1){const a=t[0];try{a.resolve(await this.request(a.method,io(this.fhirBaseUrl,a.url),a.options))}catch(l){a.reject(new Fe(mt(l)))}return}const n={resourceType:"Bundle",type:"batch",entry:t.map(a=>({request:{method:a.method,url:a.url},resource:a.options.body?JSON.parse(a.options.body):void 0}))},r=await this.post(this.fhirBaseUrl,n);for(let a=0;a<t.length;a++){const l=t[a],c=(o=r.entry)==null?void 0:o[a];(i=c==null?void 0:c.response)!=null&&i.outcome&&!pk(c.response.outcome)?l.reject(new Fe(c.response.outcome)):l.resolve(c==null?void 0:c.resource)}}addFetchOptionsDefaults(t){this.setRequestHeader(t,"Accept",z8,!0),this.options.extendedMode!==!1&&this.setRequestHeader(t,"X-Medplum","extended"),t.body&&this.setRequestHeader(t,"Content-Type",sn.FHIR_JSON,!0),this.accessToken?this.setRequestHeader(t,"Authorization","Bearer "+this.accessToken):this.basicAuth&&this.setRequestHeader(t,"Authorization","Basic "+this.basicAuth),t.cache||(t.cache="no-cache"),t.credentials||(t.credentials="include")}setRequestContentType(t,n){this.setRequestHeader(t,"Content-Type",n)}setRequestHeader(t,n,r,o=!1){t.headers||(t.headers={});const i=t.headers;o&&i[n]||(i[n]=r)}setRequestBody(t,n){typeof n=="string"||typeof Blob<"u"&&(n instanceof Blob||(n==null?void 0:n.constructor.name)==="Blob")||typeof File<"u"&&(n instanceof File||(n==null?void 0:n.constructor.name)==="File")||typeof Uint8Array<"u"&&(n instanceof Uint8Array||(n==null?void 0:n.constructor.name)==="Uint8Array")?t.body=n:n&&(t.body=JSON.stringify(n))}handleUnauthenticated(t,n,r){return this.refresh()?this.request(t,n,r):(this.clear(),this.onUnauthenticated&&this.onUnauthenticated(),Promise.reject(new Fe(Fc)))}async startPkce(){const t=ww();sessionStorage.setItem("pkceState",t);const n=ww().slice(0,128);sessionStorage.setItem("codeVerifier",n);const r=await h8(n),o=O6(r).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return sessionStorage.setItem("codeChallenge",o),{codeChallengeMethod:"S256",codeChallenge:o}}async requestAuthorization(t){const n=await this.ensureCodeChallenge(t??{}),r=new URL(this.authorizeUrl);r.searchParams.set("response_type","code"),r.searchParams.set("state",sessionStorage.getItem("pkceState")),r.searchParams.set("client_id",n.clientId??this.clientId),r.searchParams.set("redirect_uri",n.redirectUri??kw()),r.searchParams.set("code_challenge_method",n.codeChallengeMethod),r.searchParams.set("code_challenge",n.codeChallenge),r.searchParams.set("scope",n.scope??"openid profile"),window.location.assign(r.toString())}processCode(t,n){const r=new URLSearchParams;if(r.set("grant_type","authorization_code"),r.set("code",t),r.set("client_id",(n==null?void 0:n.clientId)??this.clientId),r.set("redirect_uri",(n==null?void 0:n.redirectUri)??kw()),typeof sessionStorage<"u"){const o=sessionStorage.getItem("codeVerifier");o&&r.set("code_verifier",o)}return this.fetchTokens(r)}refreshIfExpired(t){return t===void 0&&(t=this.refreshGracePeriod),!this.refreshPromise&&this.accessTokenExpires!==void 0&&Date.now()>this.accessTokenExpires-t&&this.refresh(),this.refreshPromise??Promise.resolve()}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken){const t=new URLSearchParams;return t.set("grant_type","refresh_token"),t.set("client_id",this.clientId),t.set("refresh_token",this.refreshToken),this.refreshPromise=this.fetchTokens(t),this.refreshPromise}if(this.clientId&&this.clientSecret)return this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise}async startClientLogin(t,n){this.clientId=t,this.clientSecret=n;const r=new URLSearchParams;return r.set("grant_type","client_credentials"),r.set("client_id",t),r.set("client_secret",n),this.fetchTokens(r)}async startJwtBearerLogin(t,n,r){this.clientId=t;const o=new URLSearchParams;return o.set("grant_type","urn:ietf:params:oauth:grant-type:jwt-bearer"),o.set("client_id",t),o.set("assertion",n),o.set("scope",r),this.fetchTokens(o)}async startJwtAssertionLogin(t){const n=new URLSearchParams;return n.append("grant_type","client_credentials"),n.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),n.append("client_assertion",t),this.fetchTokens(n)}setBasicAuth(t,n){this.clientId=t,this.clientSecret=n,this.basicAuth=f8(t+":"+n)}async fhircastSubscribe(t,n){if(!(typeof t=="string"&&t!==""))throw new Fe(Dt("Invalid topic provided. Topic must be a valid string."));if(!(typeof n=="object"&&Array.isArray(n)&&n.length>0))throw new Fe(Dt("Invalid events provided. Events must be an array of event names containing at least one event."));const r={channelType:"websocket",mode:"subscribe",topic:t,events:n},i=(await this.post(this.fhircastHubUrl,Sw(r),sn.FORM_URL_ENCODED))["hub.channel.endpoint"];if(!i)throw new Error("Invalid response!");return r.endpoint=i,r}async fhircastUnsubscribe(t){if(!Jx(t))throw new Fe(Dt("Invalid topic or subscriptionRequest. SubscriptionRequest must be an object."));if(!(t.endpoint&&typeof t.endpoint=="string"&&t.endpoint.startsWith("ws")))throw new Fe(Dt("Provided subscription request must have an endpoint in order to unsubscribe."));t.mode="unsubscribe",await this.post(this.fhircastHubUrl,Sw(t),sn.FORM_URL_ENCODED)}fhircastConnect(t){return new T8(t)}async fhircastPublish(t,n,r,o){return b8(n)?this.post(this.fhircastHubUrl,Cw(t,n,r,o),sn.JSON):(w8(n),this.post(this.fhircastHubUrl,Cw(t,n,r),sn.JSON))}async fhircastGetContext(t){return this.get(`${this.fhircastHubUrl}/${t}`)}async invite(t,n){return this.post("admin/projects/"+t+"/invite",n)}async fetchTokens(t){const n={method:"POST",headers:{"Content-Type":sn.FORM_URL_ENCODED},body:t.toString(),credentials:"include"},r=n.headers;this.basicAuth&&(r.Authorization=`Basic ${this.basicAuth}`);let o;try{o=await this.fetchWithRetry(this.tokenUrl,n)}catch(a){throw this.refreshPromise=void 0,a}if(!o.ok){this.clearActiveLogin();try{const a=await o.json();throw new Fe(go(a.error_description))}catch(a){throw new Fe(go("Failed to fetch tokens"),a)}}const i=await o.json();return await this.verifyTokens(i),this.getProfile()}async verifyTokens(t){const n=t.access_token;if(k8(n)){const r=Zx(n);if(Date.now()>=r.exp*1e3)throw this.clearActiveLogin(),new Fe(u7);if(r.cid){if(r.cid!==this.clientId)throw this.clearActiveLogin(),new Fe(sw)}else if(this.clientId&&r.client_id!==this.clientId)throw this.clearActiveLogin(),new Fe(sw)}return this.setActiveLogin({accessToken:n,refreshToken:t.refresh_token,project:t.project,profile:t.profile})}checkSessionDetailsMatchLogin(t){var n,r;return this.sessionDetails&&t?((r=(n=t.profile)==null?void 0:n.reference)==null?void 0:r.endsWith(this.sessionDetails.profile.id))??!1:!0}setupStorageListener(){try{window.addEventListener("storage",t=>{if(t.key===null)window.location.reload();else if(t.key==="activeLogin"){const n=t.oldValue?JSON.parse(t.oldValue):void 0,r=t.newValue?JSON.parse(t.newValue):void 0;(n==null?void 0:n.profile.reference)!==(r==null?void 0:r.profile.reference)||!this.checkSessionDetailsMatchLogin(r)?window.location.reload():r?this.setAccessToken(r.accessToken,r.refreshToken):this.clear()}})}catch{}}getSubscriptionManager(){return this.subscriptionManager||(this.subscriptionManager=new $8(this,U6(this.baseUrl,"/ws/subscriptions-r4"))),this.subscriptionManager}subscribeToCriteria(t,n){return this.getSubscriptionManager().addCriteria(t,n)}unsubscribeFromCriteria(t,n){this.subscriptionManager&&(this.subscriptionManager.removeCriteria(t,n),this.subscriptionManager.getCriteriaCount()===0&&this.subscriptionManager.closeWebSocket())}getMasterSubscriptionEmitter(){return this.getSubscriptionManager().getMasterEmitter()}}function G8(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}function kw(){return typeof window>"u"?"":window.location.protocol+"//"+window.location.host+"/"}async function Rw(e,t){var o,i;const n=e.headers.get("content-location");if(n)return n;const r=e.headers.get("location");if(r)return r;if(zh(t)&&((i=(o=t.issue)==null?void 0:o[0])!=null&&i.diagnostics))return t.issue[0].diagnostics}function _w(e){var n;const t=((n=e.entry)==null?void 0:n.map(r=>r.resource))??[];return Object.assign(t,{bundle:e})}function Q8(e){return Tn(e)&&"data"in e&&"contentType"in e}function Dw(e,t,n,r){return Q8(e)?e:{data:e,filename:t,contentType:n,onProgress:r}}function K8(e){return Tn(e)&&"docDefinition"in e}function Y8(e,t,n,r){return K8(e)?e:{docDefinition:e,filename:t,tableLayouts:n,fonts:r}}function al({parentContext:e,path:t,elements:n,profileUrl:r,debugMode:o,accessPolicyResource:i}){if(t===(e==null?void 0:e.path))return;o??(o=(e==null?void 0:e.debugMode)??!1),i??(i=e==null?void 0:e.accessPolicyResource);let a=X8(t,n,e,!!o);const l=Ig(t,".",2)[1];a=J8(a,i,l),a=Z8(a,i,l);const c=Object.create(null);for(const[d,f]of Object.entries(a))c[t+"."+d]=f;let u;if(e&&!e.isDefaultContext)u=e.getExtendedProps;else{const d=Object.create(null);u=f=>{const h=Ig(f,".",2)[1];if(h){if(!d[h]){const m=bf(h,i==null?void 0:i.hiddenFields);d[h]={hidden:m,readonly:m||bf(h,i==null?void 0:i.readonlyFields)}}return d[h]}}}return{path:t,elements:a,elementsByPath:c,profileUrl:r??(e==null?void 0:e.profileUrl),debugMode:o,getExtendedProps:u,accessPolicyResource:i}}function X8(e,t,n,r){const o=Object.create(null);if(n)for(const[a,l]of Object.entries(n.elementsByPath)){const c=zc(e,a);c!==void 0&&(o[c]=l)}let i=!1;if(t)for(const[a,l]of Object.entries(t))a in o||(o[a]=l,i=!0);return r&&console.assert(i,"Unnecessary ElementsContext; not using any newly provided elements"),o}function J8(e,t,n){var o;if(!((o=t==null?void 0:t.hiddenFields)!=null&&o.length))return e;const r=n?n+".":"";return Object.fromEntries(Object.entries(e).filter(([i])=>!bf(r+i,t.hiddenFields)))}function Z8(e,t,n){var i;if(!((i=t==null?void 0:t.readonlyFields)!=null&&i.length))return e;const r=Object.create(null),o=n?n+".":"";for(const[a,l]of Object.entries(e))bf(o+a,t.readonlyFields)?r[a]={...l,readonly:!0}:r[a]=l;return r}function bf(e,t){if(!(t!=null&&t.length))return!1;const n=e.split(".");for(let r=1;r<=n.length;r++){const o=n.slice(0,r).join(".");if(t.includes(o))return!0}return!1}function Zk(e){return e.type!==void 0&&e.type.length>0}function ez(e,t,n,r){var i;const o=f6(e,t.path,{profileUrl:r});if(o){const a=((i=n.typeSchema)==null?void 0:i.elements)??n.elements;return o.some(l=>m6(l,t,n,a))??!1}return console.assert(!1,"getNestedProperty[%s] in isDiscriminatorComponentMatch missed",t.path),!1}function eR(e,t,n,r){var o,i;if(e)for(const a of t){const l={value:e,type:((o=a.typeSchema)==null?void 0:o.type)??((i=a.type)==null?void 0:i[0].code)};if(n.every(c=>{var u;return ez(l,c,a,((u=a.typeSchema)==null?void 0:u.url)??r)}))return a.name}}class tz{constructor(t,n,r){if(t.type===void 0)throw new Error("schema must include a type");this.rootSchema=t;const o=al({parentContext:void 0,path:this.rootSchema.type,elements:r??this.rootSchema.elements,profileUrl:this.rootSchema.name===this.rootSchema.type?void 0:this.rootSchema.url});if(o===void 0)throw new Error("Could not create root elements context");this.elementsContextStack=[o],this.visitor=n}get elementsContext(){return this.elementsContextStack[this.elementsContextStack.length-1]}crawlElement(t,n,r){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema);const o=Object.fromEntries(Object.entries(this.elementsContext.elements).filter(([i])=>i.startsWith(n)));this.crawlElementsImpl(o,r),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlSlice(t,n,r){const o=this.prepareSlices(r.slices,r);if(!Ft(o.slices))throw new Error(`cannot crawl slice ${n.name} since it has no type information`);this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.sliceAllowList=[n],this.crawlSliceImpl(o.slices[0],n.path,o),this.sliceAllowList=void 0,this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlResource(){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.crawlElementsImpl(this.rootSchema.elements,this.rootSchema.type),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlElementsImpl(t,n){const r=nz(t);for(const o of r)this.crawlElementNode(o,n)}crawlElementNode(t,n){var o,i;const r=n+"."+t.key;this.visitor.onEnterElement&&this.visitor.onEnterElement(r,t.element,this.elementsContext);for(const a of t.children)this.crawlElementNode(a,n);Ft((i=(o=t.element)==null?void 0:o.slicing)==null?void 0:i.slices)&&this.crawlSlicingImpl(t.element.slicing,r),this.visitor.onExitElement&&this.visitor.onExitElement(r,t.element,this.elementsContext)}prepareSlices(t,n){var i,a;const r=[];for(const l of t){if(!Zk(l))continue;const c=(a=(i=l.type.find(u=>Ft(u.profile)))==null?void 0:i.profile)==null?void 0:a[0];if(Ft(c)){const u=Sl(c);u&&(l.typeSchema=u)}r.push(l)}return{...n,slices:r}}crawlSlicingImpl(t,n){const r=this.prepareSlices(t.slices,t);for(const o of r.slices)(this.sliceAllowList===void 0||this.sliceAllowList.includes(o))&&this.crawlSliceImpl(o,n,r)}crawlSliceImpl(t,n,r){const o=t.typeSchema;o&&this.visitor.onEnterSchema&&this.visitor.onEnterSchema(o),this.visitor.onEnterSlice&&this.visitor.onEnterSlice(n,t,r);let i;const a=(o==null?void 0:o.elements)??t.elements;Ft(a)&&(i=al({path:n,parentContext:this.elementsContext,elements:a})),i&&this.elementsContextStack.push(i),this.crawlElementsImpl(a,n),i&&this.elementsContextStack.pop(),this.visitor.onExitSlice&&this.visitor.onExitSlice(n,t,r),o&&this.visitor.onExitSchema&&this.visitor.onExitSchema(o)}}function nz(e){const t=[];function n(i,a){return a.startsWith(i+".")}function r(i,a){for(const l of i.children)if(n(l.key,a.key)){r(l,a);return}i.children.push(a)}const o=Object.entries(e);o.sort((i,a)=>i[0].localeCompare(a[0]));for(const[i,a]of o){const l={key:i,element:a,children:[]};let c=!1;for(const u of t)if(n(u.key,i)){r(u,l),c=!0;break}c||t.push(l)}return t}const om="__sliceName";function rz(e,t){const n=new oz(e,e.resourceType,"resource");return new tz(t,n).crawlResource(),n.getDefaultValue()}function Iw(e,t,n){for(const[r,o]of Object.entries(t)){if(n===void 0||n===r){wf(e,r,o,t);continue}const i=zc(n,r);i!==void 0&&wf(e,i,o,t)}return e}class oz{constructor(t,n,r){this.schemaStack=[],this.valueStack=[],this.rootValue=Qr(t),this.valueStack.splice(0,this.valueStack.length,{type:r,path:n,values:[this.rootValue]})}get schema(){return this.schemaStack[this.schemaStack.length-1]}get value(){return this.valueStack[this.valueStack.length-1]}onEnterSchema(t){this.schemaStack.push(t)}onExitSchema(){this.schemaStack.pop()}onEnterElement(t,n,r){const o=this.value.values,i=this.value.path,a=zc(i,t);if(a===void 0)throw new Error(`Expected ${t} to be prefixed by ${i}`);const l=[];for(const c of o){if(c===void 0)continue;const u=Array.isArray(c)?c:[c];for(const d of u){iz(d,a,n,r.elements),wf(d,a,n,r.elements);const f=$g(d,a,n,r.elements);f!==void 0&&l.push(f)}}this.valueStack.push({type:"element",path:t,values:l})}onExitElement(t,n,r){if(!this.valueStack.pop())throw new Error("Expected value context to exist when exiting element");const i=zc(this.value.path,t);if(i===void 0)throw new Error(`Expected ${t} to be prefixed by ${this.value.path}`);for(const a of this.value.values){const l=$g(a,i,n,r.elements);if(Array.isArray(l))for(let c=l.length-1;c>=0;c--){const u=l[c];Ft(u)||l.splice(c,1)}zt(l)&&Lg(a,void 0,i,n)}}onEnterSlice(t,n,r){const o=this.value.values,i=[];for(const a of o){if(a===void 0)continue;if(!Array.isArray(a))throw new Error("Expected array value for sliced element");const l=this.getMatchingSliceValues(a,n,r);i.push(l)}this.valueStack.push({type:"slice",path:t,values:i})}getMatchingSliceValues(t,n,r){const o=[];for(const i of t)(i[om]??eR(i,[n],r.discriminator,this.schema.url))===n.name&&o.push(i);for(let i=o.length;i<n.min;i++)if(Ux(n.type[0].code)){const a=Object.create(null);o.push(a),t.push(a)}return o}onExitSlice(){const t=this.valueStack.pop();if(!t)throw new Error("Expected value context to exist in onExitSlice");for(const n of t.values)for(let r=n.length-1;r>=0;r--){const o=n[r];om in o&&delete o[om]}}getDefaultValue(){return this.rootValue}}function iz(e,t,n,r){const o=$g(e,t,n,r);n.min>0&&o===void 0&&Ux(n.type[0].code)&&(n.isArray?Lg(e,[Object.create(null)],t,n):Lg(e,Object.create(null),t,n))}function Lg(e,t,n,r){if(n.includes("."))throw new Error("key cannot be nested");let o=n;if(n.includes("[x]")){const i=r.type[0].code;o=n.replace("[x]",tn(i))}t===void 0?delete e[o]:e[o]=t}function $g(e,t,n,r){const o=t.split(".");let i=e,a;for(let l=0;l<o.length;l++){let c=o[l];if(c.includes("[x]")){const d=r[o.slice(0,l+1).join(".")].type[0].code;c=c.replace("[x]",tn(d))}if(l===o.length-1){Array.isArray(i)?a=i.map(u=>u[c]):a=i[c];continue}if(Array.isArray(i))i=i.map(u=>u[c]);else if(Tn(i)){if(i[c]===void 0)return;i=i[c]}else return}return a}function wf(e,t,n,r){if(!(n.fixed||n.pattern))return e;if(Array.isArray(e))return e.map(l=>wf(l,t,n,r));e==null&&(e=Object.create(null));const o=e,i=t.split(".");let a=o;for(let l=0;l<i.length;l++){let c=i[l];if(c.includes("[x]")){const d=r[i.slice(0,l+1).join(".")].type[0].code;c=c.replace("[x]",tn(d))}if(l===i.length-1){const u=Array.isArray(a)?a:[a];for(const d of u)n.fixed?d[c]??(d[c]=n.fixed.value):n.pattern&&(d[c]=tR(d[c],n.pattern.value))}else{if(!(c in a)){const u=i.slice(0,l+1).join(".");a[c]=r[u].isArray?[Object.create(null)]:Object.create(null)}a=a[c]}}return o}function tR(e,t){if(Array.isArray(t)&&(Array.isArray(e)||e===void 0))return((e==null?void 0:e.length)??0)>0?e:Qr(t);if(Tn(t)&&(Tn(e)&&!Array.isArray(e)||e===void 0)){const n=Qr(e)??Object.create(null);for(const r of Object.keys(t))n[r]=tR(n[r],t[r]);return n}return e}const sz="https://api.github.com/repos/medplum/medplum/releases",im=new Map;function az(e){const t=e;if(!t.tag_name)throw new Error("Manifest missing tag_name");const n=t.assets;if(!(n!=null&&n.length))throw new Error("Manifest missing assets list");for(const r of n){if(!r.browser_download_url)throw new Error("Asset missing browser download URL");if(!r.name)throw new Error("Asset missing name")}}async function lz(e){let t=im.get("latest");if(!t){const r=await fetch(`${sz}/latest`);if(r.status!==200){let i;try{i=(await r.json()).message}catch(a){console.error(`Failed to parse message from body: ${Ie(a)}`)}throw new Error(`Received status code ${r.status} while fetching manifest for version 'latest'. Message: ${i}`)}const o=await r.json();az(o),t=o,im.set("latest",t),im.set(t.tag_name.slice(1),t)}return t}async function cz(){const e=await lz();if(!e.tag_name.startsWith("v"))throw new Error(`Invalid release name found. Release tag '${e.tag_name}' did not start with 'v'`);return e.tag_name.slice(1)}const nR=p.createContext(void 0);function qh(){return p.useContext(nR)}function ae(){return qh().medplum}function Gh(){return qh().navigate}function Qh(){return qh().profile}const Aw=["change","storageInitialized","storageInitFailed","profileRefreshing","profileRefreshed"];function uz(e){const t=e.medplum,n=e.navigate??dz,[r,o]=p.useState({profile:t.getProfile(),loading:t.isLoading()});p.useEffect(()=>{function a(){o(l=>({...l,profile:t.getProfile(),loading:t.isLoading()}))}for(const l of Aw)t.addEventListener(l,a);return()=>{for(const l of Aw)t.removeEventListener(l,a)}},[t]);const i=p.useMemo(()=>({...r,medplum:t,navigate:n}),[r,t,n]);return s.jsx(nR.Provider,{value:i,children:e.children})}function dz(e){window.location.assign(e)}const Nw=new Map,rR=e=>p.useMemo(()=>{if(!e)return;const t=e.split("?")[0];if(!t)return e;let n;try{n=new URLSearchParams(new URL(e).search)}catch{return e}if(!n.has("Key-Pair-Id")||!n.has("Signature"))return e;const r=n.get("Expires");if(!r||r.length>13)return e;const o=Nw.get(t);if(o){const a=new URLSearchParams(new URL(o).search).get("Expires");if(a&&parseInt(a,10)*1e3-5e3>Date.now())return o}return Nw.set(t,e),e},[e]);function fz(e){const t=p.useRef();return p.useEffect(()=>{t.current=e}),t.current}function St(e,t){const n=ae(),[r,o]=p.useState(()=>Mw(n,e)),i=p.useCallback(a=>{Ai(a,r)||o(a)},[r]);return p.useEffect(()=>{let a=!0;const l=Mw(n,e);return!l&&Qs(e)?n.readReference(e).then(c=>{a&&i(c)}).catch(c=>{a&&(i(void 0),t&&t(mt(c)))}):i(l),()=>a=!1},[n,e,i,t]),r}function Mw(e,t){if(t){if(ti(t))return t;if(Qs(t))return e.getCachedReference(t)}}function hz(e,t,n={leading:!1}){const[r,o]=p.useState(e),i=p.useRef(!1),a=p.useRef(),l=p.useRef(!1),c=p.useCallback(()=>window.clearTimeout(a.current),[]);return p.useEffect(()=>{i.current&&(!l.current&&n.leading?(l.current=!0,o(e)):(c(),a.current=setTimeout(()=>{l.current=!1,o(e)},t)))},[e,n.leading,t,c]),p.useEffect(()=>(i.current=!0,c),[c]),[r,c]}const pz=250;function mz(e,t,n){return oR("searchOne",e,t)}function ll(e,t,n){return oR("searchResources",e,t)}function oR(e,t,n,r){const o=ae(),[i,a]=p.useState(),[l,c]=p.useState(!0),[u,d]=p.useState(),[f,h]=p.useState(),m=o.fhirSearchUrl(t,n).toString(),[g]=hz(m,pz,{leading:!0});return p.useEffect(()=>{g!==i&&(a(g),o[e](t,n).then(v=>{c(!1),d(v),h(l7)}).catch(v=>{c(!1),d(void 0),h(mt(v))}))},[o,e,t,n,i,g]),[u,l,f]}function gz(e){const t=e.value;return t?s.jsx(s.Fragment,{children:W6(t)}):null}const iR=["meta","implicitRules","contained","extension","modifierExtension"],sR=["language","text"],wt=p.createContext({path:"",profileUrl:void 0,elements:Object.create(null),elementsByPath:Object.create(null),getExtendedProps:()=>({readonly:!1,hidden:!1}),accessPolicyResource:void 0,debugMode:!1,isDefaultContext:!0});wt.displayName="ElementsContext";const e0=["extension","modifierExtension"],vz=["id",...iR].filter(e=>!e0.includes(e));function yz(e){return Object.entries(e).filter(([n,r])=>{var o;return!Ft(r.type)||r.max===0||r.path.toLowerCase().endsWith("extension.url")&&r.fixed||e0.includes(n)&&!Ft((o=r.slicing)==null?void 0:o.slices)||vz.includes(n)?!1:!(sR.includes(n)&&r.path.split(".").length===2||n.includes("."))})}function Ow(e,t){return e.line&&e.line.length>t?e.line[t]:""}function Lw(e,t,n){const r=e.line||[];for(;r.length<=t;)r.push("");return r[t]=n,{...e,line:r}}function xz(e){const[t,n]=p.useState(e.defaultValue||{}),r=p.useRef();r.current=t;const{getExtendedProps:o}=p.useContext(wt),[i,a,l,c,u,d,f]=p.useMemo(()=>["use","type","line1","line2","city","state","postalCode"].map(w=>o(e.path+"."+w)),[o,e.path]);function h(w){n(w),e.onChange&&e.onChange(w)}function m(w){h({...r.current,use:w})}function g(w){h({...r.current,type:w})}function v(w){h(Lw(r.current||{},0,w))}function S(w){h(Lw(r.current||{},1,w))}function b(w){h({...r.current,city:w})}function x(w){h({...r.current,state:w})}function y(w){h({...r.current,postalCode:w})}return s.jsxs(ee,{gap:"xs",wrap:"nowrap",grow:!0,children:[s.jsx(Pt,{disabled:e.disabled||(i==null?void 0:i.readonly),"data-testid":"address-use",defaultValue:t.use,onChange:w=>m(w.currentTarget.value),data:["","home","work","temp","old","billing"]}),s.jsx(Pt,{disabled:e.disabled||(a==null?void 0:a.readonly),"data-testid":"address-type",defaultValue:t.type,onChange:w=>g(w.currentTarget.value),data:["","postal","physical","both"]}),s.jsx(ye,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"Line 1",defaultValue:Ow(t,0),onChange:w=>v(w.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Line 2",defaultValue:Ow(t,1),onChange:w=>S(w.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(u==null?void 0:u.readonly),placeholder:"City",defaultValue:t.city,onChange:w=>b(w.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(d==null?void 0:d.readonly),placeholder:"State",defaultValue:t.state,onChange:w=>x(w.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(f==null?void 0:f.readonly),placeholder:"Postal Code",defaultValue:t.postalCode,onChange:w=>y(w.currentTarget.value)})]})}function bz(e){const t=Qh(),[n,r]=p.useState(e.defaultValue||{});function o(i){const a=i?{text:i,authorReference:t&&Tt(t),time:new Date().toISOString()}:{};r(a),e.onChange&&e.onChange(a)}return s.jsx(ye,{disabled:e.disabled,name:e.name,placeholder:"Annotation text",defaultValue:n.text,onChange:i=>o(i.currentTarget.value)})}/**
141
+ }`.replace(/\s+/g," "),a=await this.graphql(i);lw(a.data.StructureDefinitionList);for(const l of a.data.SearchParameterList)tF(l)})());return this.setCacheEntry(n,o),o}requestProfileSchema(t,n){if(!(n!=null&&n.expandProfile)&&Lx(t))return Promise.resolve();const r=t+"-requestSchema"+(n!=null&&n.expandProfile?"-nested":""),o=this.getCacheEntry(r,void 0);if(o)return o.value;const i=new Mr((async()=>{if(n!=null&&n.expandProfile){const a=this.fhirUrl("StructureDefinition","$expand-profile");a.search=new URLSearchParams({url:t}).toString();const l=await this.post(a.toString(),{});lw(l)}else{const a=await this.searchOne("StructureDefinition",{url:t,_sort:"-_lastUpdated"});if(!a){console.warn(`No StructureDefinition found for ${t}!`);return}yk(a)}})());return this.setCacheEntry(r,i),i}readHistory(t,n,r){return this.get(this.fhirUrl(t,n,"_history"),r)}readVersion(t,n,r,o){return this.get(this.fhirUrl(t,n,"_history",r),o)}readPatientEverything(t,n){return this.get(this.fhirUrl("Patient",t,"$everything"),n)}createResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(t.resourceType),this.post(this.fhirUrl(t.resourceType),t,void 0,n)}async createResourceIfNoneExist(t,n,r){const o=this.fhirUrl(t.resourceType);r?r.headers?Array.isArray(r.headers)?r.headers.push(["If-None-Exist",n]):r.headers instanceof Headers?r.headers.set("If-None-Exist",n):r.headers["If-None-Exist"]=n:r.headers={"If-None-Exist":n}:r={headers:{"If-None-Exist":n}};const i=await this.post(o,t,void 0,r);return this.cacheResource(i),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),i}async upsertResource(t,n,r){const o=this.fhirSearchUrl(t.resourceType,n);let i=await this.put(o,t,void 0,r);return i||(i=t),this.cacheResource(i),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),i}async createAttachment(t,n,r,o,i){const a=Dw(t,n,r,o),l=i??(typeof n=="object"?n:{}),c=await this.createBinary(a,l);return{contentType:a.contentType,url:c.url,title:a.filename}}createBinary(t,n,r,o,i){const a=Dw(t,n,r,o),l=i??(typeof n=="object"?n:{}),{data:c,contentType:u,filename:d,securityContext:f,onProgress:h}=a,m=this.fhirUrl("Binary");return d&&m.searchParams.set("_filename",d),f!=null&&f.reference&&this.setRequestHeader(l,"X-Security-Context",f.reference),h?this.uploadwithProgress(m,c,u,h,l):this.post(m,c,u,l)}uploadwithProgress(t,n,r,o,i){return new Promise((a,l)=>{var f;const c=new XMLHttpRequest,u=()=>c.abort();(f=i==null?void 0:i.signal)==null||f.addEventListener("abort",u);const d=h=>{var m;(m=i==null?void 0:i.signal)==null||m.removeEventListener("abort",u),h instanceof Error?l(h):a(h)};if(c.responseType="json",c.onabort=()=>d(new DOMException("Request aborted","AbortError")),c.onerror=()=>d(new Error("Request error")),o&&(c.upload.onprogress=h=>o(h),c.upload.onload=h=>o(h)),c.onload=()=>{c.status>=200&&c.status<300?d(c.response):d(new Fe(mt(c.response||c.statusText)))},c.open("POST",t),c.withCredentials=!0,c.setRequestHeader("Authorization","Bearer "+this.accessToken),c.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),c.setRequestHeader("Content-Type",r),this.options.extendedMode!==!1&&c.setRequestHeader("X-Medplum","extended"),i!=null&&i.headers){const h=i.headers;for(const[m,g]of Object.entries(h))c.setRequestHeader(m,g)}c.send(n)})}async createPdf(t,n,r,o){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");const i=Y8(t,n,r,o),a=typeof n=="object"?n:{},{docDefinition:l,tableLayouts:c,fonts:u,...d}=i,f=await this.createPdfImpl(l,c,u),h={...d,data:f,contentType:"application/pdf"};return this.createBinary(h,a)}createComment(t,n,r){const o=this.getProfile();let i,a;return t.resourceType==="Encounter"&&(i=Tt(t),a=t.subject),t.resourceType==="ServiceRequest"&&(i=t.encounter,a=t.subject),t.resourceType==="Patient"&&(a=Tt(t)),this.createResource({resourceType:"Communication",status:"completed",basedOn:[Tt(t)],encounter:i,subject:a,sender:o?Tt(o):void 0,sent:new Date().toISOString(),payload:[{contentString:n}]},r)}async updateResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");if(!t.id)throw new Error("Missing id");let r=await this.put(this.fhirUrl(t.resourceType,t.id),t,void 0,n);return r||(r=t),this.cacheResource(r),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),r}async patchResource(t,n,r,o){const i=await this.patch(this.fhirUrl(t,n),r,o);return this.cacheResource(i),this.invalidateUrl(this.fhirUrl(t,n,"_history")),this.invalidateSearches(t),i}deleteResource(t,n,r){return this.deleteCacheEntry(this.fhirUrl(t,n).toString()),this.invalidateSearches(t),this.delete(this.fhirUrl(t,n),r)}validateResource(t,n){return this.post(this.fhirUrl(t.resourceType,"$validate"),t,void 0,n)}executeBot(t,n,r,o){let i;if(typeof t=="string"){const a=t;i=this.fhirUrl("Bot",a,"$execute")}else{const a=t;i=this.fhirUrl("Bot","$execute"),i.searchParams.set("identifier",a.system+"|"+a.value)}return this.post(i,n,r,o)}executeBatch(t,n){return this.post(this.fhirBaseUrl,t,void 0,n)}sendEmail(t,n){return this.post("email/v1/send",t,sn.JSON,n)}graphql(t,n,r,o){return this.post(this.fhirUrl("$graphql"),{query:t,operationName:n,variables:r},sn.JSON,o)}readResourceGraph(t,n,r,o){return this.get(`${this.fhirUrl(t,n)}/$graph?graph=${r}`,o)}pushToAgent(t,n,r,o,i,a){return this.post(this.fhirUrl("Agent",sl(t),"$push"),{destination:typeof n=="string"?n:ct(n),body:r,contentType:o,waitForResponse:i},sn.FHIR_JSON,a)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(t){var n,r;(!((n=this.sessionDetails)!=null&&n.profile)||ct(this.sessionDetails.profile)!==((r=t.profile)==null?void 0:r.reference))&&this.clearActiveLogin(),this.setAccessToken(t.accessToken,t.refreshToken),this.storage.setObject("activeLogin",t),this.addLogin(t),this.refreshPromise=void 0,await this.refreshProfile()}getAccessToken(){return this.accessToken}setAccessToken(t,n){this.accessToken=t,this.refreshToken=n,this.accessTokenExpires=_8(t),this.medplumServer=R8(t)}getLogins(){return this.storage.getObject("logins")??[]}addLogin(t){const n=this.getLogins().filter(r=>{var o,i;return((o=r.profile)==null?void 0:o.reference)!==((i=t.profile)==null?void 0:i.reference)});n.push(t),this.storage.setObject("logins",n)}async refreshProfile(){return this.medplumServer?(this.profilePromise=new Promise((t,n)=>{this.get("auth/me",{cache:"no-cache"}).then(r=>{var i,a;this.profilePromise=void 0;const o=((a=(i=this.sessionDetails)==null?void 0:i.profile)==null?void 0:a.id)!==r.profile.id;this.sessionDetails=r,o&&this.dispatchEvent({type:"change"}),t(r.profile),this.dispatchEvent({type:"profileRefreshed"})}).catch(n)}),this.dispatchEvent({type:"profileRefreshing"}),this.profilePromise):Promise.resolve(void 0)}isLoading(){var t;return!this.isInitialized||!!this.profilePromise&&!((t=this.sessionDetails)!=null&&t.profile)}isSuperAdmin(){var t;return!!((t=this.sessionDetails)!=null&&t.project.superAdmin)}isProjectAdmin(){var t;return!!((t=this.sessionDetails)!=null&&t.membership.admin)}getProject(){var t;return(t=this.sessionDetails)==null?void 0:t.project}getProjectMembership(){var t;return(t=this.sessionDetails)==null?void 0:t.membership}getProfile(){var t;return(t=this.sessionDetails)==null?void 0:t.profile}async getProfileAsync(){return this.profilePromise?this.profilePromise:this.sessionDetails?this.sessionDetails.profile:this.refreshProfile()}getUserConfiguration(){var t;return(t=this.sessionDetails)==null?void 0:t.config}getAccessPolicy(){var t;return(t=this.sessionDetails)==null?void 0:t.accessPolicy}async download(t,n={}){this.refreshPromise&&await this.refreshPromise;const r=t.toString();r.startsWith(q8)&&(t=this.fhirUrl(r));let o=n.headers;return o||(o={},n.headers=o),o.Accept||(o.Accept="*/*"),this.addFetchOptionsDefaults(n),(await this.fetchWithRetry(t.toString(),n)).blob()}async createMedia(t,n){const{additionalFields:r,...o}=t,i=await this.createResource({resourceType:"Media",status:"preparation",content:{contentType:t.contentType},...r});o.securityContext||(o.securityContext=Tt(i));const a=await this.createAttachment(o,n);return this.updateResource({...i,status:"completed",content:a})}async uploadMedia(t,n,r,o,i){return this.createMedia({data:t,contentType:n,filename:r,additionalFields:o},i)}async bulkExport(t="",n,r,o){const i=t&&`${t}/`,a=this.fhirUrl(`${i}$export`);return n&&a.searchParams.set("_type",n),r&&a.searchParams.set("_since",r),this.startAsyncRequest(a.toString(),o)}async startAsyncRequest(t,n={}){this.addFetchOptionsDefaults(n);const r=n.headers;return r.Prefer="respond-async",this.request("POST",t,n)}get keyValue(){return this.keyValueClient||(this.keyValueClient=new D8(this)),this.keyValueClient}getCacheEntry(t,n){if(!this.requestCache||(n==null?void 0:n.cache)==="no-cache"||(n==null?void 0:n.cache)==="reload")return;const r=this.requestCache.get(t);if(!(!r||r.requestTime+this.cacheTime<Date.now()))return r}setCacheEntry(t,n){this.requestCache&&this.requestCache.set(t,{requestTime:Date.now(),value:n})}cacheResource(t){var n,r;t!=null&&t.id&&!((r=(n=t.meta)==null?void 0:n.tag)!=null&&r.some(o=>o.code==="SUBSETTED"))&&this.setCacheEntry(this.fhirUrl(t.resourceType,t.id).toString(),new Mr(Promise.resolve(t)))}deleteCacheEntry(t){this.requestCache&&this.requestCache.delete(t)}async request(t,n,r={},o={}){await this.refreshIfExpired(),r.method=t,this.addFetchOptionsDefaults(r);const i=await this.fetchWithRetry(n,r);if(i.status===401)return this.handleUnauthenticated(t,n,r);if(i.status===204||i.status===304)return;const a=i.headers.get("content-type"),l=a==null?void 0:a.includes("json");if(i.status===404&&!l)throw new Fe(c7);const c=await this.parseBody(i,l);if(i.status===200&&r.followRedirectOnOk||i.status===201&&r.followRedirectOnCreated){const u=await Rw(i,c);if(u)return this.request("GET",u,{...r,body:void 0})}if(i.status===202&&r.pollStatusOnAccepted){const d=await Rw(i,c)??o.statusUrl;if(d)return this.pollStatus(d,r,o)}if(i.status>=400)throw new Fe(mt(c));return c}async parseBody(t,n){let r;if(n)try{r=await t.json()}catch(o){throw console.error("Error parsing response",t.status,o),o}else r=await t.text();return r}async fetchWithRetry(t,n){t.startsWith("http")||(t=io(this.baseUrl,t));const r=(n==null?void 0:n.maxRetries)??2,o=200;for(let i=0;i<=r;i++){try{this.options.verbose&&this.logRequest(t,n);const a=await this.fetch(t,n);if(this.options.verbose&&this.logResponse(a),a.status<500||i===r)return a}catch(a){if(a.message==="Failed to fetch"&&i===0&&this.dispatchEvent({type:"offline"}),a.name==="AbortError"||i===r)throw a}await gw(o)}throw new Error("Unreachable")}logRequest(t,n){if(console.log(`> ${n.method} ${t}`),n.headers){const r=n.headers;for(const o of Uc(Object.keys(r)))console.log(`> ${o}: ${r[o]}`)}}logResponse(t){console.log(`< ${t.status} ${t.statusText}`),t.headers&&t.headers.forEach((n,r)=>console.log(`< ${r}: ${n}`))}async pollStatus(t,n,r){const o={...n,method:"GET",body:void 0,redirect:"follow"};if(r.pollCount===void 0)n.headers&&typeof n.headers=="object"&&"Prefer"in n.headers&&(o.headers={...n.headers},delete o.headers.Prefer),r.statusUrl=t,r.pollCount=1;else{const i=n.pollStatusPeriod??1e3;await gw(i),r.pollCount++}return this.request("GET",t,o,r)}async executeAutoBatch(){var o,i;if(this.autoBatchQueue===void 0)return;const t=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,t.length===1){const a=t[0];try{a.resolve(await this.request(a.method,io(this.fhirBaseUrl,a.url),a.options))}catch(l){a.reject(new Fe(mt(l)))}return}const n={resourceType:"Bundle",type:"batch",entry:t.map(a=>({request:{method:a.method,url:a.url},resource:a.options.body?JSON.parse(a.options.body):void 0}))},r=await this.post(this.fhirBaseUrl,n);for(let a=0;a<t.length;a++){const l=t[a],c=(o=r.entry)==null?void 0:o[a];(i=c==null?void 0:c.response)!=null&&i.outcome&&!pk(c.response.outcome)?l.reject(new Fe(c.response.outcome)):l.resolve(c==null?void 0:c.resource)}}addFetchOptionsDefaults(t){this.setRequestHeader(t,"Accept",z8,!0),this.options.extendedMode!==!1&&this.setRequestHeader(t,"X-Medplum","extended"),t.body&&this.setRequestHeader(t,"Content-Type",sn.FHIR_JSON,!0),this.accessToken?this.setRequestHeader(t,"Authorization","Bearer "+this.accessToken):this.basicAuth&&this.setRequestHeader(t,"Authorization","Basic "+this.basicAuth),t.cache||(t.cache="no-cache"),t.credentials||(t.credentials="include")}setRequestContentType(t,n){this.setRequestHeader(t,"Content-Type",n)}setRequestHeader(t,n,r,o=!1){t.headers||(t.headers={});const i=t.headers;o&&i[n]||(i[n]=r)}setRequestBody(t,n){typeof n=="string"||typeof Blob<"u"&&(n instanceof Blob||(n==null?void 0:n.constructor.name)==="Blob")||typeof File<"u"&&(n instanceof File||(n==null?void 0:n.constructor.name)==="File")||typeof Uint8Array<"u"&&(n instanceof Uint8Array||(n==null?void 0:n.constructor.name)==="Uint8Array")?t.body=n:n&&(t.body=JSON.stringify(n))}handleUnauthenticated(t,n,r){return this.refresh()?this.request(t,n,r):(this.clear(),this.onUnauthenticated&&this.onUnauthenticated(),Promise.reject(new Fe(Fc)))}async startPkce(){const t=ww();sessionStorage.setItem("pkceState",t);const n=ww().slice(0,128);sessionStorage.setItem("codeVerifier",n);const r=await h8(n),o=O6(r).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return sessionStorage.setItem("codeChallenge",o),{codeChallengeMethod:"S256",codeChallenge:o}}async requestAuthorization(t){const n=await this.ensureCodeChallenge(t??{}),r=new URL(this.authorizeUrl);r.searchParams.set("response_type","code"),r.searchParams.set("state",sessionStorage.getItem("pkceState")),r.searchParams.set("client_id",n.clientId??this.clientId),r.searchParams.set("redirect_uri",n.redirectUri??kw()),r.searchParams.set("code_challenge_method",n.codeChallengeMethod),r.searchParams.set("code_challenge",n.codeChallenge),r.searchParams.set("scope",n.scope??"openid profile"),window.location.assign(r.toString())}processCode(t,n){const r=new URLSearchParams;if(r.set("grant_type","authorization_code"),r.set("code",t),r.set("client_id",(n==null?void 0:n.clientId)??this.clientId),r.set("redirect_uri",(n==null?void 0:n.redirectUri)??kw()),typeof sessionStorage<"u"){const o=sessionStorage.getItem("codeVerifier");o&&r.set("code_verifier",o)}return this.fetchTokens(r)}refreshIfExpired(t){return t===void 0&&(t=this.refreshGracePeriod),!this.refreshPromise&&this.accessTokenExpires!==void 0&&Date.now()>this.accessTokenExpires-t&&this.refresh(),this.refreshPromise??Promise.resolve()}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken){const t=new URLSearchParams;return t.set("grant_type","refresh_token"),t.set("client_id",this.clientId),t.set("refresh_token",this.refreshToken),this.refreshPromise=this.fetchTokens(t),this.refreshPromise}if(this.clientId&&this.clientSecret)return this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise}async startClientLogin(t,n){this.clientId=t,this.clientSecret=n;const r=new URLSearchParams;return r.set("grant_type","client_credentials"),r.set("client_id",t),r.set("client_secret",n),this.fetchTokens(r)}async startJwtBearerLogin(t,n,r){this.clientId=t;const o=new URLSearchParams;return o.set("grant_type","urn:ietf:params:oauth:grant-type:jwt-bearer"),o.set("client_id",t),o.set("assertion",n),o.set("scope",r),this.fetchTokens(o)}async startJwtAssertionLogin(t){const n=new URLSearchParams;return n.append("grant_type","client_credentials"),n.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),n.append("client_assertion",t),this.fetchTokens(n)}setBasicAuth(t,n){this.clientId=t,this.clientSecret=n,this.basicAuth=f8(t+":"+n)}async fhircastSubscribe(t,n){if(!(typeof t=="string"&&t!==""))throw new Fe(Dt("Invalid topic provided. Topic must be a valid string."));if(!(typeof n=="object"&&Array.isArray(n)&&n.length>0))throw new Fe(Dt("Invalid events provided. Events must be an array of event names containing at least one event."));const r={channelType:"websocket",mode:"subscribe",topic:t,events:n},i=(await this.post(this.fhircastHubUrl,Sw(r),sn.FORM_URL_ENCODED))["hub.channel.endpoint"];if(!i)throw new Error("Invalid response!");return r.endpoint=i,r}async fhircastUnsubscribe(t){if(!Jx(t))throw new Fe(Dt("Invalid topic or subscriptionRequest. SubscriptionRequest must be an object."));if(!(t.endpoint&&typeof t.endpoint=="string"&&t.endpoint.startsWith("ws")))throw new Fe(Dt("Provided subscription request must have an endpoint in order to unsubscribe."));t.mode="unsubscribe",await this.post(this.fhircastHubUrl,Sw(t),sn.FORM_URL_ENCODED)}fhircastConnect(t){return new T8(t)}async fhircastPublish(t,n,r,o){return b8(n)?this.post(this.fhircastHubUrl,Cw(t,n,r,o),sn.JSON):(w8(n),this.post(this.fhircastHubUrl,Cw(t,n,r),sn.JSON))}async fhircastGetContext(t){return this.get(`${this.fhircastHubUrl}/${t}`)}async invite(t,n){return this.post("admin/projects/"+t+"/invite",n)}async fetchTokens(t){const n={method:"POST",headers:{"Content-Type":sn.FORM_URL_ENCODED},body:t.toString(),credentials:"include"},r=n.headers;this.basicAuth&&(r.Authorization=`Basic ${this.basicAuth}`);let o;try{o=await this.fetchWithRetry(this.tokenUrl,n)}catch(a){throw this.refreshPromise=void 0,a}if(!o.ok){this.clearActiveLogin();try{const a=await o.json();throw new Fe(go(a.error_description))}catch(a){throw new Fe(go("Failed to fetch tokens"),a)}}const i=await o.json();return await this.verifyTokens(i),this.getProfile()}async verifyTokens(t){const n=t.access_token;if(k8(n)){const r=Zx(n);if(Date.now()>=r.exp*1e3)throw this.clearActiveLogin(),new Fe(u7);if(r.cid){if(r.cid!==this.clientId)throw this.clearActiveLogin(),new Fe(sw)}else if(this.clientId&&r.client_id!==this.clientId)throw this.clearActiveLogin(),new Fe(sw)}return this.setActiveLogin({accessToken:n,refreshToken:t.refresh_token,project:t.project,profile:t.profile})}checkSessionDetailsMatchLogin(t){var n,r;return this.sessionDetails&&t?((r=(n=t.profile)==null?void 0:n.reference)==null?void 0:r.endsWith(this.sessionDetails.profile.id))??!1:!0}setupStorageListener(){try{window.addEventListener("storage",t=>{if(t.key===null)window.location.reload();else if(t.key==="activeLogin"){const n=t.oldValue?JSON.parse(t.oldValue):void 0,r=t.newValue?JSON.parse(t.newValue):void 0;(n==null?void 0:n.profile.reference)!==(r==null?void 0:r.profile.reference)||!this.checkSessionDetailsMatchLogin(r)?window.location.reload():r?this.setAccessToken(r.accessToken,r.refreshToken):this.clear()}})}catch{}}getSubscriptionManager(){return this.subscriptionManager||(this.subscriptionManager=new $8(this,U6(this.baseUrl,"/ws/subscriptions-r4"))),this.subscriptionManager}subscribeToCriteria(t,n){return this.getSubscriptionManager().addCriteria(t,n)}unsubscribeFromCriteria(t,n){this.subscriptionManager&&(this.subscriptionManager.removeCriteria(t,n),this.subscriptionManager.getCriteriaCount()===0&&this.subscriptionManager.closeWebSocket())}getMasterSubscriptionEmitter(){return this.getSubscriptionManager().getMasterEmitter()}}function G8(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}function kw(){return typeof window>"u"?"":window.location.protocol+"//"+window.location.host+"/"}async function Rw(e,t){var o,i;const n=e.headers.get("content-location");if(n)return n;const r=e.headers.get("location");if(r)return r;if(zh(t)&&((i=(o=t.issue)==null?void 0:o[0])!=null&&i.diagnostics))return t.issue[0].diagnostics}function _w(e){var n;const t=((n=e.entry)==null?void 0:n.map(r=>r.resource))??[];return Object.assign(t,{bundle:e})}function Q8(e){return Tn(e)&&"data"in e&&"contentType"in e}function Dw(e,t,n,r){return Q8(e)?e:{data:e,filename:t,contentType:n,onProgress:r}}function K8(e){return Tn(e)&&"docDefinition"in e}function Y8(e,t,n,r){return K8(e)?e:{docDefinition:e,filename:t,tableLayouts:n,fonts:r}}function al({parentContext:e,path:t,elements:n,profileUrl:r,debugMode:o,accessPolicyResource:i}){if(t===(e==null?void 0:e.path))return;o??(o=(e==null?void 0:e.debugMode)??!1),i??(i=e==null?void 0:e.accessPolicyResource);let a=X8(t,n,e,!!o);const l=Ig(t,".",2)[1];a=J8(a,i,l),a=Z8(a,i,l);const c=Object.create(null);for(const[d,f]of Object.entries(a))c[t+"."+d]=f;let u;if(e&&!e.isDefaultContext)u=e.getExtendedProps;else{const d=Object.create(null);u=f=>{const h=Ig(f,".",2)[1];if(h){if(!d[h]){const m=bf(h,i==null?void 0:i.hiddenFields);d[h]={hidden:m,readonly:m||bf(h,i==null?void 0:i.readonlyFields)}}return d[h]}}}return{path:t,elements:a,elementsByPath:c,profileUrl:r??(e==null?void 0:e.profileUrl),debugMode:o,getExtendedProps:u,accessPolicyResource:i}}function X8(e,t,n,r){const o=Object.create(null);if(n)for(const[a,l]of Object.entries(n.elementsByPath)){const c=zc(e,a);c!==void 0&&(o[c]=l)}let i=!1;if(t)for(const[a,l]of Object.entries(t))a in o||(o[a]=l,i=!0);return r&&console.assert(i,"Unnecessary ElementsContext; not using any newly provided elements"),o}function J8(e,t,n){var o;if(!((o=t==null?void 0:t.hiddenFields)!=null&&o.length))return e;const r=n?n+".":"";return Object.fromEntries(Object.entries(e).filter(([i])=>!bf(r+i,t.hiddenFields)))}function Z8(e,t,n){var i;if(!((i=t==null?void 0:t.readonlyFields)!=null&&i.length))return e;const r=Object.create(null),o=n?n+".":"";for(const[a,l]of Object.entries(e))bf(o+a,t.readonlyFields)?r[a]={...l,readonly:!0}:r[a]=l;return r}function bf(e,t){if(!(t!=null&&t.length))return!1;const n=e.split(".");for(let r=1;r<=n.length;r++){const o=n.slice(0,r).join(".");if(t.includes(o))return!0}return!1}function Zk(e){return e.type!==void 0&&e.type.length>0}function ez(e,t,n,r){var i;const o=f6(e,t.path,{profileUrl:r});if(o){const a=((i=n.typeSchema)==null?void 0:i.elements)??n.elements;return o.some(l=>m6(l,t,n,a))??!1}return console.assert(!1,"getNestedProperty[%s] in isDiscriminatorComponentMatch missed",t.path),!1}function eR(e,t,n,r){var o,i;if(e)for(const a of t){const l={value:e,type:((o=a.typeSchema)==null?void 0:o.type)??((i=a.type)==null?void 0:i[0].code)};if(n.every(c=>{var u;return ez(l,c,a,((u=a.typeSchema)==null?void 0:u.url)??r)}))return a.name}}class tz{constructor(t,n,r){if(t.type===void 0)throw new Error("schema must include a type");this.rootSchema=t;const o=al({parentContext:void 0,path:this.rootSchema.type,elements:r??this.rootSchema.elements,profileUrl:this.rootSchema.name===this.rootSchema.type?void 0:this.rootSchema.url});if(o===void 0)throw new Error("Could not create root elements context");this.elementsContextStack=[o],this.visitor=n}get elementsContext(){return this.elementsContextStack[this.elementsContextStack.length-1]}crawlElement(t,n,r){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema);const o=Object.fromEntries(Object.entries(this.elementsContext.elements).filter(([i])=>i.startsWith(n)));this.crawlElementsImpl(o,r),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlSlice(t,n,r){const o=this.prepareSlices(r.slices,r);if(!Ft(o.slices))throw new Error(`cannot crawl slice ${n.name} since it has no type information`);this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.sliceAllowList=[n],this.crawlSliceImpl(o.slices[0],n.path,o),this.sliceAllowList=void 0,this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlResource(){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.crawlElementsImpl(this.rootSchema.elements,this.rootSchema.type),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlElementsImpl(t,n){const r=nz(t);for(const o of r)this.crawlElementNode(o,n)}crawlElementNode(t,n){var o,i;const r=n+"."+t.key;this.visitor.onEnterElement&&this.visitor.onEnterElement(r,t.element,this.elementsContext);for(const a of t.children)this.crawlElementNode(a,n);Ft((i=(o=t.element)==null?void 0:o.slicing)==null?void 0:i.slices)&&this.crawlSlicingImpl(t.element.slicing,r),this.visitor.onExitElement&&this.visitor.onExitElement(r,t.element,this.elementsContext)}prepareSlices(t,n){var i,a;const r=[];for(const l of t){if(!Zk(l))continue;const c=(a=(i=l.type.find(u=>Ft(u.profile)))==null?void 0:i.profile)==null?void 0:a[0];if(Ft(c)){const u=Sl(c);u&&(l.typeSchema=u)}r.push(l)}return{...n,slices:r}}crawlSlicingImpl(t,n){const r=this.prepareSlices(t.slices,t);for(const o of r.slices)(this.sliceAllowList===void 0||this.sliceAllowList.includes(o))&&this.crawlSliceImpl(o,n,r)}crawlSliceImpl(t,n,r){const o=t.typeSchema;o&&this.visitor.onEnterSchema&&this.visitor.onEnterSchema(o),this.visitor.onEnterSlice&&this.visitor.onEnterSlice(n,t,r);let i;const a=(o==null?void 0:o.elements)??t.elements;Ft(a)&&(i=al({path:n,parentContext:this.elementsContext,elements:a})),i&&this.elementsContextStack.push(i),this.crawlElementsImpl(a,n),i&&this.elementsContextStack.pop(),this.visitor.onExitSlice&&this.visitor.onExitSlice(n,t,r),o&&this.visitor.onExitSchema&&this.visitor.onExitSchema(o)}}function nz(e){const t=[];function n(i,a){return a.startsWith(i+".")}function r(i,a){for(const l of i.children)if(n(l.key,a.key)){r(l,a);return}i.children.push(a)}const o=Object.entries(e);o.sort((i,a)=>i[0].localeCompare(a[0]));for(const[i,a]of o){const l={key:i,element:a,children:[]};let c=!1;for(const u of t)if(n(u.key,i)){r(u,l),c=!0;break}c||t.push(l)}return t}const om="__sliceName";function rz(e,t){const n=new oz(e,e.resourceType,"resource");return new tz(t,n).crawlResource(),n.getDefaultValue()}function Iw(e,t,n){for(const[r,o]of Object.entries(t)){if(n===void 0||n===r){wf(e,r,o,t);continue}const i=zc(n,r);i!==void 0&&wf(e,i,o,t)}return e}class oz{constructor(t,n,r){this.schemaStack=[],this.valueStack=[],this.rootValue=Qr(t),this.valueStack.splice(0,this.valueStack.length,{type:r,path:n,values:[this.rootValue]})}get schema(){return this.schemaStack[this.schemaStack.length-1]}get value(){return this.valueStack[this.valueStack.length-1]}onEnterSchema(t){this.schemaStack.push(t)}onExitSchema(){this.schemaStack.pop()}onEnterElement(t,n,r){const o=this.value.values,i=this.value.path,a=zc(i,t);if(a===void 0)throw new Error(`Expected ${t} to be prefixed by ${i}`);const l=[];for(const c of o){if(c===void 0)continue;const u=Array.isArray(c)?c:[c];for(const d of u){iz(d,a,n,r.elements),wf(d,a,n,r.elements);const f=$g(d,a,n,r.elements);f!==void 0&&l.push(f)}}this.valueStack.push({type:"element",path:t,values:l})}onExitElement(t,n,r){if(!this.valueStack.pop())throw new Error("Expected value context to exist when exiting element");const i=zc(this.value.path,t);if(i===void 0)throw new Error(`Expected ${t} to be prefixed by ${this.value.path}`);for(const a of this.value.values){const l=$g(a,i,n,r.elements);if(Array.isArray(l))for(let c=l.length-1;c>=0;c--){const u=l[c];Ft(u)||l.splice(c,1)}zt(l)&&Lg(a,void 0,i,n)}}onEnterSlice(t,n,r){const o=this.value.values,i=[];for(const a of o){if(a===void 0)continue;if(!Array.isArray(a))throw new Error("Expected array value for sliced element");const l=this.getMatchingSliceValues(a,n,r);i.push(l)}this.valueStack.push({type:"slice",path:t,values:i})}getMatchingSliceValues(t,n,r){const o=[];for(const i of t)(i[om]??eR(i,[n],r.discriminator,this.schema.url))===n.name&&o.push(i);for(let i=o.length;i<n.min;i++)if(Ux(n.type[0].code)){const a=Object.create(null);o.push(a),t.push(a)}return o}onExitSlice(){const t=this.valueStack.pop();if(!t)throw new Error("Expected value context to exist in onExitSlice");for(const n of t.values)for(let r=n.length-1;r>=0;r--){const o=n[r];om in o&&delete o[om]}}getDefaultValue(){return this.rootValue}}function iz(e,t,n,r){const o=$g(e,t,n,r);n.min>0&&o===void 0&&Ux(n.type[0].code)&&(n.isArray?Lg(e,[Object.create(null)],t,n):Lg(e,Object.create(null),t,n))}function Lg(e,t,n,r){if(n.includes("."))throw new Error("key cannot be nested");let o=n;if(n.includes("[x]")){const i=r.type[0].code;o=n.replace("[x]",tn(i))}t===void 0?delete e[o]:e[o]=t}function $g(e,t,n,r){const o=t.split(".");let i=e,a;for(let l=0;l<o.length;l++){let c=o[l];if(c.includes("[x]")){const d=r[o.slice(0,l+1).join(".")].type[0].code;c=c.replace("[x]",tn(d))}if(l===o.length-1){Array.isArray(i)?a=i.map(u=>u[c]):a=i[c];continue}if(Array.isArray(i))i=i.map(u=>u[c]);else if(Tn(i)){if(i[c]===void 0)return;i=i[c]}else return}return a}function wf(e,t,n,r){if(!(n.fixed||n.pattern))return e;if(Array.isArray(e))return e.map(l=>wf(l,t,n,r));e==null&&(e=Object.create(null));const o=e,i=t.split(".");let a=o;for(let l=0;l<i.length;l++){let c=i[l];if(c.includes("[x]")){const d=r[i.slice(0,l+1).join(".")].type[0].code;c=c.replace("[x]",tn(d))}if(l===i.length-1){const u=Array.isArray(a)?a:[a];for(const d of u)n.fixed?d[c]??(d[c]=n.fixed.value):n.pattern&&(d[c]=tR(d[c],n.pattern.value))}else{if(!(c in a)){const u=i.slice(0,l+1).join(".");a[c]=r[u].isArray?[Object.create(null)]:Object.create(null)}a=a[c]}}return o}function tR(e,t){if(Array.isArray(t)&&(Array.isArray(e)||e===void 0))return((e==null?void 0:e.length)??0)>0?e:Qr(t);if(Tn(t)&&(Tn(e)&&!Array.isArray(e)||e===void 0)){const n=Qr(e)??Object.create(null);for(const r of Object.keys(t))n[r]=tR(n[r],t[r]);return n}return e}const sz="https://api.github.com/repos/medplum/medplum/releases",im=new Map;function az(e){const t=e;if(!t.tag_name)throw new Error("Manifest missing tag_name");const n=t.assets;if(!(n!=null&&n.length))throw new Error("Manifest missing assets list");for(const r of n){if(!r.browser_download_url)throw new Error("Asset missing browser download URL");if(!r.name)throw new Error("Asset missing name")}}async function lz(e){let t=im.get("latest");if(!t){const r=await fetch(`${sz}/latest`);if(r.status!==200){let i;try{i=(await r.json()).message}catch(a){console.error(`Failed to parse message from body: ${Ie(a)}`)}throw new Error(`Received status code ${r.status} while fetching manifest for version 'latest'. Message: ${i}`)}const o=await r.json();az(o),t=o,im.set("latest",t),im.set(t.tag_name.slice(1),t)}return t}async function cz(){const e=await lz();if(!e.tag_name.startsWith("v"))throw new Error(`Invalid release name found. Release tag '${e.tag_name}' did not start with 'v'`);return e.tag_name.slice(1)}const nR=p.createContext(void 0);function qh(){return p.useContext(nR)}function ae(){return qh().medplum}function Gh(){return qh().navigate}function Qh(){return qh().profile}const Aw=["change","storageInitialized","storageInitFailed","profileRefreshing","profileRefreshed"];function uz(e){const t=e.medplum,n=e.navigate??dz,[r,o]=p.useState({profile:t.getProfile(),loading:t.isLoading()});p.useEffect(()=>{function a(){o(l=>({...l,profile:t.getProfile(),loading:t.isLoading()}))}for(const l of Aw)t.addEventListener(l,a);return()=>{for(const l of Aw)t.removeEventListener(l,a)}},[t]);const i=p.useMemo(()=>({...r,medplum:t,navigate:n}),[r,t,n]);return s.jsx(nR.Provider,{value:i,children:e.children})}function dz(e){window.location.assign(e)}const Nw=new Map,rR=e=>p.useMemo(()=>{if(!e)return;const t=e.split("?")[0];if(!t)return e;let n;try{n=new URLSearchParams(new URL(e).search)}catch{return e}if(!n.has("Key-Pair-Id")||!n.has("Signature"))return e;const r=n.get("Expires");if(!r||r.length>13)return e;const o=Nw.get(t);if(o){const a=new URLSearchParams(new URL(o).search).get("Expires");if(a&&parseInt(a,10)*1e3-5e3>Date.now())return o}return Nw.set(t,e),e},[e]);function fz(e){const t=p.useRef();return p.useEffect(()=>{t.current=e}),t.current}function St(e,t){const n=ae(),[r,o]=p.useState(()=>Mw(n,e)),i=p.useCallback(a=>{Ai(a,r)||o(a)},[r]);return p.useEffect(()=>{let a=!0;const l=Mw(n,e);return!l&&Qs(e)?n.readReference(e).then(c=>{a&&i(c)}).catch(c=>{a&&(i(void 0),t&&t(mt(c)))}):i(l),()=>a=!1},[n,e,i,t]),r}function Mw(e,t){if(t){if(ti(t))return t;if(Qs(t))return e.getCachedReference(t)}}function hz(e,t,n={leading:!1}){const[r,o]=p.useState(e),i=p.useRef(!1),a=p.useRef(),l=p.useRef(!1),c=p.useCallback(()=>window.clearTimeout(a.current),[]);return p.useEffect(()=>{i.current&&(!l.current&&n.leading?(l.current=!0,o(e)):(c(),a.current=setTimeout(()=>{l.current=!1,o(e)},t)))},[e,n.leading,t,c]),p.useEffect(()=>(i.current=!0,c),[c]),[r,c]}const pz=250;function mz(e,t,n){return oR("searchOne",e,t)}function ll(e,t,n){return oR("searchResources",e,t)}function oR(e,t,n,r){const o=ae(),[i,a]=p.useState(),[l,c]=p.useState(!0),[u,d]=p.useState(),[f,h]=p.useState(),m=o.fhirSearchUrl(t,n).toString(),[g]=hz(m,pz,{leading:!0});return p.useEffect(()=>{g!==i&&(a(g),o[e](t,n).then(v=>{c(!1),d(v),h(l7)}).catch(v=>{c(!1),d(void 0),h(mt(v))}))},[o,e,t,n,i,g]),[u,l,f]}function gz(e){const t=e.value;return t?s.jsx(s.Fragment,{children:W6(t)}):null}const iR=["meta","implicitRules","contained","extension","modifierExtension"],sR=["language","text"],wt=p.createContext({path:"",profileUrl:void 0,elements:Object.create(null),elementsByPath:Object.create(null),getExtendedProps:()=>({readonly:!1,hidden:!1}),accessPolicyResource:void 0,debugMode:!1,isDefaultContext:!0});wt.displayName="ElementsContext";const e0=["extension","modifierExtension"],vz=["id",...iR].filter(e=>!e0.includes(e));function yz(e){return Object.entries(e).filter(([n,r])=>{var o;return!Ft(r.type)||r.max===0||r.path.toLowerCase().endsWith("extension.url")&&r.fixed||e0.includes(n)&&!Ft((o=r.slicing)==null?void 0:o.slices)||vz.includes(n)?!1:!(sR.includes(n)&&r.path.split(".").length===2||n.includes("."))})}function Ow(e,t){return e.line&&e.line.length>t?e.line[t]:""}function Lw(e,t,n){const r=e.line||[];for(;r.length<=t;)r.push("");return r[t]=n,{...e,line:r}}function xz(e){const[t,n]=p.useState(e.defaultValue||{}),r=p.useRef();r.current=t;const{getExtendedProps:o}=p.useContext(wt),[i,a,l,c,u,d,f]=p.useMemo(()=>["use","type","line1","line2","city","state","postalCode"].map(w=>o(e.path+"."+w)),[o,e.path]);function h(w){n(w),e.onChange&&e.onChange(w)}function m(w){h({...r.current,use:w})}function g(w){h({...r.current,type:w})}function v(w){h(Lw(r.current||{},0,w))}function S(w){h(Lw(r.current||{},1,w))}function b(w){h({...r.current,city:w})}function x(w){h({...r.current,state:w})}function y(w){h({...r.current,postalCode:w})}return s.jsxs(ee,{gap:"xs",wrap:"nowrap",grow:!0,children:[s.jsx(Pt,{disabled:e.disabled||(i==null?void 0:i.readonly),"data-testid":"address-use",defaultValue:t.use,onChange:w=>m(w.currentTarget.value),data:["","home","work","temp","old","billing"]}),s.jsx(Pt,{disabled:e.disabled||(a==null?void 0:a.readonly),"data-testid":"address-type",defaultValue:t.type,onChange:w=>g(w.currentTarget.value),data:["","postal","physical","both"]}),s.jsx(ye,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"Line 1",defaultValue:Ow(t,0),onChange:w=>v(w.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Line 2",defaultValue:Ow(t,1),onChange:w=>S(w.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(u==null?void 0:u.readonly),placeholder:"City",defaultValue:t.city,onChange:w=>b(w.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(d==null?void 0:d.readonly),placeholder:"State",defaultValue:t.state,onChange:w=>x(w.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(f==null?void 0:f.readonly),placeholder:"Postal Code",defaultValue:t.postalCode,onChange:w=>y(w.currentTarget.value)})]})}function bz(e){const t=Qh(),[n,r]=p.useState(e.defaultValue||{});function o(i){const a=i?{text:i,authorReference:t&&Tt(t),time:new Date().toISOString()}:{};r(a),e.onChange&&e.onChange(a)}return s.jsx(ye,{disabled:e.disabled,name:e.name,placeholder:"Annotation text",defaultValue:n.text,onChange:i=>o(i.currentTarget.value)})}/**
142
142
  * @license @tabler/icons-react v3.17.0 - MIT
143
143
  *
144
144
  * This source code is licensed under the MIT license.
@@ -568,7 +568,7 @@ Error generating stack: `+i.message+`
568
568
  * LICENSE.md file in the root directory of this source tree.
569
569
  *
570
570
  * @license MIT
571
- */function If(){return If=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},If.apply(this,arguments)}function Xg(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(o=>[n,o]):[[n,r]])},[]))}function gQ(e,t){let n=Xg(e);return t&&t.forEach((r,o)=>{n.has(o)||t.getAll(o).forEach(i=>{n.append(o,i)})}),n}const vQ="6";try{window.__reactRouterVersion=vQ}catch{}function yQ(e,t){return _G({basename:void 0,future:If({},void 0,{v7_prependBasename:!0}),history:eG({window:void 0}),hydrationData:xQ(),routes:e,mapRouteProperties:mQ,dataStrategy:void 0,patchRoutesOnNavigation:void 0,window:void 0}).initialize()}function xQ(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=If({},t,{errors:bQ(t.errors)})),t}function bQ(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,o]of t)if(o&&o.__type==="RouteErrorResponse")n[r]=new _f(o.status,o.statusText,o.data,o.internal===!0);else if(o&&o.__type==="Error"){if(o.__subType){let i=window[o.__subType];if(typeof i=="function")try{let a=new i(o.message);a.stack="",n[r]=a}catch{}}if(n[r]==null){let i=new Error(o.message);i.stack="",n[r]=i}}else n[r]=o;return n}const wQ=p.createContext({isTransitioning:!1}),SQ=p.createContext(new Map),jQ="startTransition",kS=ij[jQ],CQ="flushSync",RS=s4[CQ];function EQ(e){kS?kS(e):e()}function Yl(e){RS?RS(e):e()}class TQ{constructor(){this.status="pending",this.promise=new Promise((t,n)=>{this.resolve=r=>{this.status==="pending"&&(this.status="resolved",t(r))},this.reject=r=>{this.status==="pending"&&(this.status="rejected",n(r))}})}}function PQ(e){let{fallbackElement:t,router:n,future:r}=e,[o,i]=p.useState(n.state),[a,l]=p.useState(),[c,u]=p.useState({isTransitioning:!1}),[d,f]=p.useState(),[h,m]=p.useState(),[g,v]=p.useState(),S=p.useRef(new Map),{v7_startTransition:b}=r||{},x=p.useCallback(E=>{b?EQ(E):E()},[b]),y=p.useCallback((E,R)=>{let{deletedFetchers:_,flushSync:N,viewTransitionOpts:O}=R;_.forEach(z=>S.current.delete(z)),E.fetchers.forEach((z,H)=>{z.data!==void 0&&S.current.set(H,z.data)});let F=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!O||F){N?Yl(()=>i(E)):x(()=>i(E));return}if(N){Yl(()=>{h&&(d&&d.resolve(),h.skipTransition()),u({isTransitioning:!0,flushSync:!0,currentLocation:O.currentLocation,nextLocation:O.nextLocation})});let z=n.window.document.startViewTransition(()=>{Yl(()=>i(E))});z.finished.finally(()=>{Yl(()=>{f(void 0),m(void 0),l(void 0),u({isTransitioning:!1})})}),Yl(()=>m(z));return}h?(d&&d.resolve(),h.skipTransition(),v({state:E,currentLocation:O.currentLocation,nextLocation:O.nextLocation})):(l(E),u({isTransitioning:!0,flushSync:!1,currentLocation:O.currentLocation,nextLocation:O.nextLocation}))},[n.window,h,d,S,x]);p.useLayoutEffect(()=>n.subscribe(y),[n,y]),p.useEffect(()=>{c.isTransitioning&&!c.flushSync&&f(new TQ)},[c]),p.useEffect(()=>{if(d&&a&&n.window){let E=a,R=d.promise,_=n.window.document.startViewTransition(async()=>{x(()=>i(E)),await R});_.finished.finally(()=>{f(void 0),m(void 0),l(void 0),u({isTransitioning:!1})}),m(_)}},[x,a,d,n.window]),p.useEffect(()=>{d&&a&&o.location.key===a.location.key&&d.resolve()},[d,h,o.location,a]),p.useEffect(()=>{!c.isTransitioning&&g&&(l(g.state),u({isTransitioning:!0,flushSync:!1,currentLocation:g.currentLocation,nextLocation:g.nextLocation}),v(void 0))},[c.isTransitioning,g]),p.useEffect(()=>{},[]);let w=p.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:E=>n.navigate(E),push:(E,R,_)=>n.navigate(E,{state:R,preventScrollReset:_==null?void 0:_.preventScrollReset}),replace:(E,R,_)=>n.navigate(E,{replace:!0,state:R,preventScrollReset:_==null?void 0:_.preventScrollReset})}),[n]),C=n.basename||"/",j=p.useMemo(()=>({router:n,navigator:w,static:!1,basename:C}),[n,w,C]),T=p.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return p.useEffect(()=>fQ(r,n.future),[r,n.future]),p.createElement(p.Fragment,null,p.createElement(tp.Provider,{value:j},p.createElement(z2.Provider,{value:o},p.createElement(SQ.Provider,{value:S.current},p.createElement(wQ.Provider,{value:c},p.createElement(hQ,{basename:C,location:o.location,navigationType:o.historyAction,navigator:w,future:T},o.initialized||n.future.v7_partialHydration?p.createElement(kQ,{routes:n.routes,future:n.future,state:o}):t))))),null)}const kQ=p.memo(RQ);function RQ(e){let{routes:t,future:n,state:r}=e;return V2(t,void 0,r,n)}var _S;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(_S||(_S={}));var DS;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(DS||(DS={}));function O0(e){let t=p.useRef(Xg(e)),n=p.useRef(!1),r=ri(),o=p.useMemo(()=>gQ(r.search,n.current?null:t.current),[r.search]),i=Gt(),a=p.useCallback((l,c)=>{const u=Xg(typeof l=="function"?l(o):l);n.current=!0,i("?"+u,c)},[i,o]);return[o,a]}const _Q=new Map([["aac","audio/aac"],["abw","application/x-abiword"],["arc","application/x-freearc"],["avif","image/avif"],["avi","video/x-msvideo"],["azw","application/vnd.amazon.ebook"],["bin","application/octet-stream"],["bmp","image/bmp"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["cda","application/x-cdf"],["csh","application/x-csh"],["css","text/css"],["csv","text/csv"],["doc","application/msword"],["docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],["eot","application/vnd.ms-fontobject"],["epub","application/epub+zip"],["gz","application/gzip"],["gif","image/gif"],["heic","image/heic"],["heif","image/heif"],["htm","text/html"],["html","text/html"],["ico","image/vnd.microsoft.icon"],["ics","text/calendar"],["jar","application/java-archive"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["js","text/javascript"],["json","application/json"],["jsonld","application/ld+json"],["mid","audio/midi"],["midi","audio/midi"],["mjs","text/javascript"],["mp3","audio/mpeg"],["mp4","video/mp4"],["mpeg","video/mpeg"],["mpkg","application/vnd.apple.installer+xml"],["odp","application/vnd.oasis.opendocument.presentation"],["ods","application/vnd.oasis.opendocument.spreadsheet"],["odt","application/vnd.oasis.opendocument.text"],["oga","audio/ogg"],["ogv","video/ogg"],["ogx","application/ogg"],["opus","audio/opus"],["otf","font/otf"],["png","image/png"],["pdf","application/pdf"],["php","application/x-httpd-php"],["ppt","application/vnd.ms-powerpoint"],["pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],["rar","application/vnd.rar"],["rtf","application/rtf"],["sh","application/x-sh"],["svg","image/svg+xml"],["swf","application/x-shockwave-flash"],["tar","application/x-tar"],["tif","image/tiff"],["tiff","image/tiff"],["ts","video/mp2t"],["ttf","font/ttf"],["txt","text/plain"],["vsd","application/vnd.visio"],["wav","audio/wav"],["weba","audio/webm"],["webm","video/webm"],["webp","image/webp"],["woff","font/woff"],["woff2","font/woff2"],["xhtml","application/xhtml+xml"],["xls","application/vnd.ms-excel"],["xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],["xml","application/xml"],["xul","application/vnd.mozilla.xul+xml"],["zip","application/zip"],["7z","application/x-7z-compressed"],["mkv","video/x-matroska"],["mov","video/quicktime"],["msg","application/vnd.ms-outlook"]]);function Du(e,t){const n=DQ(e);if(typeof n.path!="string"){const{webkitRelativePath:r}=e;Object.defineProperty(n,"path",{value:typeof t=="string"?t:typeof r=="string"&&r.length>0?r:e.name,writable:!1,configurable:!1,enumerable:!0})}return n}function DQ(e){const{name:t}=e;if(t&&t.lastIndexOf(".")!==-1&&!e.type){const r=t.split(".").pop().toLowerCase(),o=_Q.get(r);o&&Object.defineProperty(e,"type",{value:o,writable:!1,configurable:!1,enumerable:!0})}return e}var Rl=(e,t,n)=>new Promise((r,o)=>{var i=c=>{try{l(n.next(c))}catch(u){o(u)}},a=c=>{try{l(n.throw(c))}catch(u){o(u)}},l=c=>c.done?r(c.value):Promise.resolve(c.value).then(i,a);l((n=n.apply(e,t)).next())});const IQ=[".DS_Store","Thumbs.db"];function AQ(e){return Rl(this,null,function*(){return Af(e)&&NQ(e.dataTransfer)?$Q(e.dataTransfer,e.type):MQ(e)?OQ(e):Array.isArray(e)&&e.every(t=>"getFile"in t&&typeof t.getFile=="function")?LQ(e):[]})}function NQ(e){return Af(e)}function MQ(e){return Af(e)&&Af(e.target)}function Af(e){return typeof e=="object"&&e!==null}function OQ(e){return Jg(e.target.files).map(t=>Du(t))}function LQ(e){return Rl(this,null,function*(){return(yield Promise.all(e.map(n=>n.getFile()))).map(n=>Du(n))})}function $Q(e,t){return Rl(this,null,function*(){if(e.items){const n=Jg(e.items).filter(o=>o.kind==="file");if(t!=="drop")return n;const r=yield Promise.all(n.map(FQ));return IS(q2(r))}return IS(Jg(e.files).map(n=>Du(n)))})}function IS(e){return e.filter(t=>IQ.indexOf(t.name)===-1)}function Jg(e){if(e===null)return[];const t=[];for(let n=0;n<e.length;n++){const r=e[n];t.push(r)}return t}function FQ(e){if(typeof e.webkitGetAsEntry!="function")return AS(e);const t=e.webkitGetAsEntry();return t&&t.isDirectory?G2(t):AS(e)}function q2(e){return e.reduce((t,n)=>[...t,...Array.isArray(n)?q2(n):[n]],[])}function AS(e){const t=e.getAsFile();if(!t)return Promise.reject(`${e} is not a File`);const n=Du(t);return Promise.resolve(n)}function zQ(e){return Rl(this,null,function*(){return e.isDirectory?G2(e):UQ(e)})}function G2(e){const t=e.createReader();return new Promise((n,r)=>{const o=[];function i(){t.readEntries(a=>Rl(this,null,function*(){if(a.length){const l=Promise.all(a.map(zQ));o.push(l),i()}else try{const l=yield Promise.all(o);n(l)}catch(l){r(l)}}),a=>{r(a)})}i()})}function UQ(e){return Rl(this,null,function*(){return new Promise((t,n)=>{e.file(r=>{const o=Du(r,e.fullPath);t(o)},r=>{n(r)})})})}function BQ(e,t){if(e&&t){const n=Array.isArray(t)?t:t.split(","),r=e.name||"",o=(e.type||"").toLowerCase(),i=o.replace(/\/.*$/,"");return n.some(a=>{const l=a.trim().toLowerCase();return l.charAt(0)==="."?r.toLowerCase().endsWith(l):l.endsWith("/*")?i===l.replace(/\/.*$/,""):o===l})}return!0}var VQ=Object.defineProperty,WQ=Object.defineProperties,HQ=Object.getOwnPropertyDescriptors,NS=Object.getOwnPropertySymbols,qQ=Object.prototype.hasOwnProperty,GQ=Object.prototype.propertyIsEnumerable,MS=(e,t,n)=>t in e?VQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,QQ=(e,t)=>{for(var n in t||(t={}))qQ.call(t,n)&&MS(e,n,t[n]);if(NS)for(var n of NS(t))GQ.call(t,n)&&MS(e,n,t[n]);return e},KQ=(e,t)=>WQ(e,HQ(t));const YQ="file-invalid-type",XQ="file-too-large",JQ="file-too-small",ZQ="too-many-files",eK=e=>{e=Array.isArray(e)&&e.length===1?e[0]:e;const t=Array.isArray(e)?`one of ${e.join(", ")}`:e;return{code:YQ,message:`File type must be ${t}`}},OS=e=>({code:XQ,message:`File is larger than ${e} ${e===1?"byte":"bytes"}`}),LS=e=>({code:JQ,message:`File is smaller than ${e} ${e===1?"byte":"bytes"}`}),tK={code:ZQ,message:"Too many files"};function Q2(e,t){const n=e.type==="application/x-moz-file"||BQ(e,t);return[n,n?null:eK(t)]}function K2(e,t,n){if(ls(e.size))if(ls(t)&&ls(n)){if(e.size>n)return[!1,OS(n)];if(e.size<t)return[!1,LS(t)]}else{if(ls(t)&&e.size<t)return[!1,LS(t)];if(ls(n)&&e.size>n)return[!1,OS(n)]}return[!0,null]}function ls(e){return e!=null}function nK({files:e,accept:t,minSize:n,maxSize:r,multiple:o,maxFiles:i,validator:a}){return!o&&e.length>1||o&&i>=1&&e.length>i?!1:e.every(l=>{const[c]=Q2(l,t),[u]=K2(l,n,r),d=a?a(l):null;return c&&u&&!d})}function Nf(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function hd(e){return e.dataTransfer?Array.prototype.some.call(e.dataTransfer.types,t=>t==="Files"||t==="application/x-moz-file"):!!e.target&&!!e.target.files}function $S(e){e.preventDefault()}function rK(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function oK(e){return e.indexOf("Edge/")!==-1}function iK(e=window.navigator.userAgent){return rK(e)||oK(e)}function oo(...e){return(t,...n)=>e.some(r=>(!Nf(t)&&r&&r(t,...n),Nf(t)))}function sK(){return"showOpenFilePicker"in window}function aK(e){return ls(e)?[{description:"Files",accept:Object.entries(e).filter(([n,r])=>{let o=!0;return Y2(n)||(console.warn(`Skipped "${n}" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.`),o=!1),(!Array.isArray(r)||!r.every(X2))&&(console.warn(`Skipped "${n}" because an invalid file extension was provided.`),o=!1),o}).reduce((n,[r,o])=>KQ(QQ({},n),{[r]:o}),{})}]:e}function lK(e){if(ls(e))return Object.entries(e).reduce((t,[n,r])=>[...t,n,...r],[]).filter(t=>Y2(t)||X2(t)).join(",")}function cK(e){return e instanceof DOMException&&(e.name==="AbortError"||e.code===e.ABORT_ERR)}function uK(e){return e instanceof DOMException&&(e.name==="SecurityError"||e.code===e.SECURITY_ERR)}function Y2(e){return e==="audio/*"||e==="video/*"||e==="image/*"||e==="text/*"||/\w+\/[-+.\w]+/g.test(e)}function X2(e){return/^.*\.[\w]+$/.test(e)}var dK=Object.defineProperty,fK=Object.defineProperties,hK=Object.getOwnPropertyDescriptors,Mf=Object.getOwnPropertySymbols,J2=Object.prototype.hasOwnProperty,Z2=Object.prototype.propertyIsEnumerable,FS=(e,t,n)=>t in e?dK(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,An=(e,t)=>{for(var n in t||(t={}))J2.call(t,n)&&FS(e,n,t[n]);if(Mf)for(var n of Mf(t))Z2.call(t,n)&&FS(e,n,t[n]);return e},hi=(e,t)=>fK(e,hK(t)),Of=(e,t)=>{var n={};for(var r in e)J2.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Mf)for(var r of Mf(e))t.indexOf(r)<0&&Z2.call(e,r)&&(n[r]=e[r]);return n};const L0=p.forwardRef((e,t)=>{var n=e,{children:r}=n,o=Of(n,["children"]);const i=t_(o),{open:a}=i,l=Of(i,["open"]);return p.useImperativeHandle(t,()=>({open:a}),[a]),Jt.createElement(p.Fragment,null,r(hi(An({},l),{open:a})))});L0.displayName="Dropzone";const e_={disabled:!1,getFilesFromEvent:AQ,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!0,autoFocus:!1};L0.defaultProps=e_;L0.propTypes={children:vt.func,accept:vt.objectOf(vt.arrayOf(vt.string)),multiple:vt.bool,preventDropOnDocument:vt.bool,noClick:vt.bool,noKeyboard:vt.bool,noDrag:vt.bool,noDragEventsBubbling:vt.bool,minSize:vt.number,maxSize:vt.number,maxFiles:vt.number,disabled:vt.bool,getFilesFromEvent:vt.func,onFileDialogCancel:vt.func,onFileDialogOpen:vt.func,useFsAccessApi:vt.bool,autoFocus:vt.bool,onDragEnter:vt.func,onDragLeave:vt.func,onDragOver:vt.func,onDrop:vt.func,onDropAccepted:vt.func,onDropRejected:vt.func,onError:vt.func,validator:vt.func};const Zg={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function t_(e={}){const{accept:t,disabled:n,getFilesFromEvent:r,maxSize:o,minSize:i,multiple:a,maxFiles:l,onDragEnter:c,onDragLeave:u,onDragOver:d,onDrop:f,onDropAccepted:h,onDropRejected:m,onFileDialogCancel:g,onFileDialogOpen:v,useFsAccessApi:S,autoFocus:b,preventDropOnDocument:x,noClick:y,noKeyboard:w,noDrag:C,noDragEventsBubbling:j,onError:T,validator:E}=An(An({},e_),e),R=p.useMemo(()=>lK(t),[t]),_=p.useMemo(()=>aK(t),[t]),N=p.useMemo(()=>typeof v=="function"?v:zS,[v]),O=p.useMemo(()=>typeof g=="function"?g:zS,[g]),F=p.useRef(null),z=p.useRef(null),[H,D]=p.useReducer(pK,Zg),{isFocused:k,isFileDialogActive:P}=H,I=p.useRef(typeof window<"u"&&window.isSecureContext&&S&&sK()),L=()=>{!I.current&&P&&setTimeout(()=>{if(z.current){const{files:J}=z.current;J.length||(D({type:"closeDialog"}),O())}},300)};p.useEffect(()=>(window.addEventListener("focus",L,!1),()=>{window.removeEventListener("focus",L,!1)}),[z,P,O,I]);const $=p.useRef([]),Q=J=>{F.current&&F.current.contains(J.target)||(J.preventDefault(),$.current=[])};p.useEffect(()=>(x&&(document.addEventListener("dragover",$S,!1),document.addEventListener("drop",Q,!1)),()=>{x&&(document.removeEventListener("dragover",$S),document.removeEventListener("drop",Q))}),[F,x]),p.useEffect(()=>(!n&&b&&F.current&&F.current.focus(),()=>{}),[F,b,n]);const ue=p.useCallback(J=>{T?T(J):console.error(J)},[T]),Re=p.useCallback(J=>{J.preventDefault(),J.persist(),ne(J),$.current=[...$.current,J.target],hd(J)&&Promise.resolve(r(J)).then(se=>{if(Nf(J)&&!j)return;const G=se.length,Se=G>0&&nK({files:se,accept:R,minSize:i,maxSize:o,multiple:a,maxFiles:l,validator:E}),He=G>0&&!Se;D({isDragAccept:Se,isDragReject:He,isDragActive:!0,type:"setDraggedFiles"}),c&&c(J)}).catch(se=>ue(se))},[r,c,ue,j,R,i,o,a,l,E]),me=p.useCallback(J=>{J.preventDefault(),J.persist(),ne(J);const se=hd(J);if(se&&J.dataTransfer)try{J.dataTransfer.dropEffect="copy"}catch{}return se&&d&&d(J),!1},[d,j]),ge=p.useCallback(J=>{J.preventDefault(),J.persist(),ne(J);const se=$.current.filter(Se=>F.current&&F.current.contains(Se)),G=se.indexOf(J.target);G!==-1&&se.splice(G,1),$.current=se,!(se.length>0)&&(D({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),hd(J)&&u&&u(J))},[F,u,j]),De=p.useCallback((J,se)=>{const G=[],Se=[];J.forEach(He=>{const[kt,lt]=Q2(He,R),[Nt,rn]=K2(He,i,o),un=E?E(He):null;if(kt&&Nt&&!un)G.push(He);else{let eo=[lt,rn];un&&(eo=eo.concat(un)),Se.push({file:He,errors:eo.filter(Bn=>Bn)})}}),(!a&&G.length>1||a&&l>=1&&G.length>l)&&(G.forEach(He=>{Se.push({file:He,errors:[tK]})}),G.splice(0)),D({acceptedFiles:G,fileRejections:Se,type:"setFiles"}),f&&f(G,Se,se),Se.length>0&&m&&m(Se,se),G.length>0&&h&&h(G,se)},[D,a,R,i,o,l,f,h,m,E]),le=p.useCallback(J=>{J.preventDefault(),J.persist(),ne(J),$.current=[],hd(J)&&Promise.resolve(r(J)).then(se=>{Nf(J)&&!j||De(se,J)}).catch(se=>ue(se)),D({type:"reset"})},[r,De,ue,j]),Ne=p.useCallback(()=>{if(I.current){D({type:"openDialog"}),N();const J={multiple:a,types:_};window.showOpenFilePicker(J).then(se=>r(se)).then(se=>{De(se,null),D({type:"closeDialog"})}).catch(se=>{cK(se)?(O(se),D({type:"closeDialog"})):uK(se)?(I.current=!1,z.current?(z.current.value=null,z.current.click()):ue(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no <input> was provided."))):ue(se)});return}z.current&&(D({type:"openDialog"}),N(),z.current.value=null,z.current.click())},[D,N,O,S,De,ue,_,a]),it=p.useCallback(J=>{!F.current||!F.current.isEqualNode(J.target)||(J.key===" "||J.key==="Enter"||J.keyCode===32||J.keyCode===13)&&(J.preventDefault(),Ne())},[F,Ne]),Ue=p.useCallback(()=>{D({type:"focus"})},[]),Je=p.useCallback(()=>{D({type:"blur"})},[]),st=p.useCallback(()=>{y||(iK()?setTimeout(Ne,0):Ne())},[y,Ne]),Be=J=>n?null:J,Ze=J=>w?null:Be(J),at=J=>C?null:Be(J),ne=J=>{j&&J.stopPropagation()},X=p.useMemo(()=>(J={})=>{var se=J,{refKey:G="ref",role:Se,onKeyDown:He,onFocus:kt,onBlur:lt,onClick:Nt,onDragEnter:rn,onDragOver:un,onDragLeave:eo,onDrop:Bn}=se,Js=Of(se,["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"]);return An(An({onKeyDown:Ze(oo(He,it)),onFocus:Ze(oo(kt,Ue)),onBlur:Ze(oo(lt,Je)),onClick:Be(oo(Nt,st)),onDragEnter:at(oo(rn,Re)),onDragOver:at(oo(un,me)),onDragLeave:at(oo(eo,ge)),onDrop:at(oo(Bn,le)),role:typeof Se=="string"&&Se!==""?Se:"presentation",[G]:F},!n&&!w?{tabIndex:0}:{}),Js)},[F,it,Ue,Je,st,Re,me,ge,le,w,C,n]),ce=p.useCallback(J=>{J.stopPropagation()},[]),ke=p.useMemo(()=>(J={})=>{var se=J,{refKey:G="ref",onChange:Se,onClick:He}=se,kt=Of(se,["refKey","onChange","onClick"]);const lt={accept:R,multiple:a,type:"file",style:{display:"none"},onChange:Be(oo(Se,le)),onClick:Be(oo(He,ce)),tabIndex:-1,[G]:z};return An(An({},lt),kt)},[z,t,a,le,n]);return hi(An({},H),{isFocused:k&&!n,getRootProps:X,getInputProps:ke,rootRef:F,inputRef:z,open:Be(Ne)})}function pK(e,t){switch(t.type){case"focus":return hi(An({},e),{isFocused:!0});case"blur":return hi(An({},e),{isFocused:!1});case"openDialog":return hi(An({},Zg),{isFileDialogActive:!0});case"closeDialog":return hi(An({},e),{isFileDialogActive:!1});case"setDraggedFiles":return hi(An({},e),{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return hi(An({},e),{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return An({},Zg);default:return e}}function zS(){}const[mK,gK]=Fn("Dropzone component was not found in tree");function $0(e){const t=n=>{const{children:r,...o}=W(`Dropzone${Z0(e)}`,{},n),i=gK(),a=qo(r)?r:s.jsx("span",{children:r});return i[e]?p.cloneElement(a,o):null};return t.displayName=`@mantine/dropzone/${Z0(e)}`,t}const vK=$0("accept"),yK=$0("reject"),xK=$0("idle");var Kc={root:"m_d46a4834",inner:"m_b85f7144",fullScreen:"m_96f6e9ad",dropzone:"m_7946116d"};const bK={loading:!1,multiple:!0,maxSize:1/0,autoFocus:!1,activateOnClick:!0,activateOnDrag:!0,dragEventsBubbling:!0,activateOnKeyboard:!0,useFsAccessApi:!0,variant:"light",rejectColor:"red"},wK=(e,{radius:t,variant:n,acceptColor:r,rejectColor:o})=>{const i=e.variantColorResolver({color:r||e.primaryColor,theme:e,variant:n}),a=e.variantColorResolver({color:o||"red",theme:e,variant:n});return{root:{"--dropzone-radius":dt(t),"--dropzone-accept-color":i.color,"--dropzone-accept-bg":i.background,"--dropzone-reject-color":a.color,"--dropzone-reject-bg":a.background}}},Hi=Y((e,t)=>{const n=W("Dropzone",bK,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,radius:u,disabled:d,loading:f,multiple:h,maxSize:m,accept:g,children:v,onDropAny:S,onDrop:b,onReject:x,openRef:y,name:w,maxFiles:C,autoFocus:j,activateOnClick:T,activateOnDrag:E,dragEventsBubbling:R,activateOnKeyboard:_,onDragEnter:N,onDragLeave:O,onDragOver:F,onFileDialogCancel:z,onFileDialogOpen:H,preventDropOnDocument:D,useFsAccessApi:k,getFilesFromEvent:P,validator:I,rejectColor:L,acceptColor:$,enablePointerEvents:Q,loaderProps:ue,inputProps:Re,mod:me,...ge}=n,De=de({name:"Dropzone",classes:Kc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:wK}),{getRootProps:le,getInputProps:Ne,isDragAccept:it,isDragReject:Ue,open:Je}=t_({onDrop:S,onDropAccepted:b,onDropRejected:x,disabled:d||f,accept:Array.isArray(g)?g.reduce((Be,Ze)=>({...Be,[Ze]:[]}),{}):g,multiple:h,maxSize:m,maxFiles:C,autoFocus:j,noClick:!T,noDrag:!E,noDragEventsBubbling:!R,noKeyboard:!_,onDragEnter:N,onDragLeave:O,onDragOver:F,onFileDialogCancel:z,onFileDialogOpen:H,preventDropOnDocument:D,useFsAccessApi:k,validator:I,...P?{getFilesFromEvent:P}:null});Uf(y,Je);const st=!it&&!Ue;return s.jsx(mK,{value:{accept:it,reject:Ue,idle:st},children:s.jsxs(q,{...le(),...De("root",{focusable:!0}),...ge,mod:[{accept:it,reject:Ue,idle:st,disabled:d,loading:f,"activate-on-click":T},me],children:[s.jsx(ix,{visible:f,overlayProps:{radius:u},unstyled:l,loaderProps:ue}),s.jsx("input",{...Ne(Re),name:w}),s.jsx("div",{...De("inner"),ref:t,"data-enable-pointer-events":Q||void 0,children:v})]})})});Hi.classes=Kc;Hi.displayName="@mantine/dropzone/Dropzone";Hi.Accept=vK;Hi.Idle=xK;Hi.Reject=yK;const SK={loading:!1,maxSize:1/0,activateOnClick:!1,activateOnDrag:!0,dragEventsBubbling:!0,activateOnKeyboard:!0,active:!0,zIndex:Yr("max"),withinPortal:!0},F0=Y((e,t)=>{const n=W("DropzoneFullScreen",SK,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,active:u,onDrop:d,onReject:f,zIndex:h,withinPortal:m,portalProps:g,...v}=n,S=de({name:"DropzoneFullScreen",classes:Kc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,rootSelector:"fullScreen"}),{resolvedClassNames:b,resolvedStyles:x}=Xc({classNames:r,styles:a,props:n}),[y,w]=p.useState(0),[C,{open:j,close:T}]=Bf(!1),E=_=>{var N;(N=_.dataTransfer)!=null&&N.types.includes("Files")&&(w(O=>O+1),j())},R=()=>{w(_=>_-1)};return p.useEffect(()=>{y===0&&T()},[y]),p.useEffect(()=>{if(u)return document.addEventListener("dragenter",E,!1),document.addEventListener("dragleave",R,!1),()=>{document.removeEventListener("dragenter",E,!1),document.removeEventListener("dragleave",R,!1)}},[u]),s.jsx(zs,{...g,withinPortal:m,children:s.jsx(q,{...S("fullScreen",{style:{opacity:C?1:0,pointerEvents:C?"all":"none",zIndex:h}}),ref:t,children:s.jsx(Hi,{...v,classNames:b,styles:x,unstyled:l,className:Kc.dropzone,onDrop:_=>{d==null||d(_),T(),w(0)},onReject:_=>{f==null||f(_),T(),w(0)}})})})});F0.classes=Kc;F0.displayName="@mantine/dropzone/DropzoneFullScreen";Hi.FullScreen=F0;const pd=Hi,jK='{"resourceType": "Bundle"}';function pm({id:e,title:t,message:n,color:r,icon:o,withCloseButton:i=!1,method:a="show",loading:l}){mo[a]({id:e,loading:l,title:t,message:n,color:r,icon:o,withCloseButton:i,autoClose:!1})}function CK(){const e=At(),t=ae(),[n,r]=p.useState({}),o=p.useCallback(async(l,c)=>{const u="batch-upload";pm({id:u,title:"Batch Upload in Progress",message:"Your batch data is being uploaded. This may take a moment...",method:"show",loading:!0});try{r({});let d=JSON.parse(l);d.type!=="batch"&&d.type!=="transaction"&&(d=Gk(d));const f=await t.executeBatch(d);r(h=>({...h,[c]:f})),pm({id:u,title:"Batch Upload Successful",message:"Your batch data was successfully uploaded.",color:"green",method:"update",icon:s.jsx(Ks,{size:"1rem"}),withCloseButton:!0})}catch(d){pm({id:u,title:"Batch Upload Failed",color:"red",message:Ie(d),method:"update",icon:s.jsx(Cf,{size:"1rem"}),withCloseButton:!0})}},[t]),i=p.useCallback(async l=>{for(const c of l){const u=new FileReader;u.onload=d=>{var f;return o((f=d.target)==null?void 0:f.result,c.name)},u.readAsText(c)}},[o]),a=p.useCallback(async l=>{await o(l.input,"JSON Data")},[o]);return s.jsxs(Oe,{children:[s.jsx(be,{children:"Batch Create"}),s.jsxs("p",{children:["Use this page to create, read, or update multiple resources. For more details, see ",s.jsx("a",{href:"https://www.hl7.org/fhir/http.html#transaction",children:"FHIR Batch and Transaction"}),"."]}),Object.keys(n).length===0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{children:"Input"}),s.jsxs(et,{defaultValue:"upload",children:[s.jsxs(et.List,{children:[s.jsx(et.Tab,{value:"upload",children:"File Upload"}),s.jsx(et.Tab,{value:"json",children:"JSON"})]}),s.jsx(et.Panel,{value:"upload",pt:"xs",children:s.jsx(pd,{onDrop:i,accept:["application/json"],children:s.jsxs(ee,{justify:"center",gap:"xl",style:{minHeight:220,pointerEvents:"none"},children:[s.jsx(pd.Accept,{children:s.jsx(zw,{size:50,stroke:1.5,color:e.colors[e.primaryColor][5]})}),s.jsx(pd.Reject,{children:s.jsx(Cf,{size:50,stroke:1.5,color:e.colors.red[5]})}),s.jsx(pd.Idle,{children:s.jsx(zw,{size:50,stroke:1.5})}),s.jsxs("div",{children:[s.jsx(he,{size:"xl",inline:!0,children:"Drag files here or click to select files"}),s.jsx(he,{size:"sm",color:"dimmed",inline:!0,mt:7,children:"Attach as many files as you like"})]})]})})}),s.jsx(et.Panel,{value:"json",pt:"xs",children:s.jsxs(Qe,{onSubmit:a,children:[s.jsx(yl,{"data-testid":"batch-input",name:"input",autosize:!0,minRows:20,defaultValue:jK,deserialize:JSON.parse}),s.jsx(ee,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ie,{type:"submit",children:"Submit"})})]})})]})]}),Object.keys(n).length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{children:"Output"}),s.jsxs(et,{defaultValue:Object.keys(n)[0],children:[s.jsx(et.List,{children:Object.keys(n).map(l=>s.jsx(et.Tab,{value:l,children:l},l))}),Object.keys(n).map(l=>s.jsx(et.Panel,{value:l,children:s.jsx("pre",{style:{border:"1px solid #888"},children:JSON.stringify(n[l],void 0,2)})},l))]}),s.jsx(ee,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ie,{onClick:()=>r({}),children:"Start over"})})]})]})}function EK(){const{resourceType:e}=ft(),n=(Object.fromEntries(new URLSearchParams(location.search).entries()).ids||"").split(",").filter(o=>!!o),[r]=ll("Questionnaire",`subject-type=${e}`);return r?r.length===0?s.jsxs(Oe,{children:[s.jsxs(be,{children:["No apps for ",e]}),s.jsx(qe,{to:`/${e}`,children:"Return to search page"})]}):s.jsx(Oe,{children:s.jsx("div",{children:r.map(o=>s.jsxs("div",{children:[s.jsx("h3",{children:s.jsx(qe,{to:`/forms/${o.id}?subject=`+n.map(i=>`${e}/${i}`).join(","),children:o.name})}),s.jsx("p",{children:o.description})]},o.id))})}):s.jsx(Tr,{})}function TK(){const e=ae(),[t,n]=p.useState(),[r,o]=p.useState(!1);return s.jsx(Oe,{width:450,children:s.jsxs(Qe,{onSubmit:i=>{n(void 0),e.post("auth/changepassword",i).then(()=>o(!0)).catch(a=>n(mt(a)))},children:[s.jsxs(vn,{style:{flexDirection:"column"},children:[s.jsx(Zr,{size:32}),s.jsx(be,{children:"Change password"})]}),!r&&s.jsxs(Ae,{gap:"xl",mt:"xl",children:[s.jsx(Wr,{name:"oldPassword",label:"Old password",required:!0,autoFocus:!0,error:Ye(t,"oldPassword")}),s.jsx(Wr,{name:"newPassword",label:"New password",required:!0,error:Ye(t,"newPassword")}),s.jsx(Wr,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Ye(t,"confirmPassword")}),s.jsx(ee,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ie,{type:"submit",children:"Change password"})})]}),r&&s.jsx("div",{"data-testid":"success",children:"Password changed successfully"})]})})}const ev=["Form","JSON","Profiles"],PK=["Profiles"],mm=ev[0].toLowerCase();function kK(){const e=Gt(),t=At(),{resourceType:n}=ft(),[r,o]=p.useState(()=>{const a=window.location.pathname.split("/").pop();return a&&ev.map(l=>l.toLowerCase()).includes(a)?a:mm});function i(a){a||(a=mm),o(a),e(`/${n}/new/${a}`)}return s.jsxs(s.Fragment,{children:[s.jsxs(Xn,{children:[s.jsxs(he,{p:"md",fw:500,children:["New ",n]}),s.jsx(kr,{children:s.jsx(et,{defaultValue:mm,value:r,onChange:i,children:s.jsx(et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:ev.map(a=>s.jsx(et.Tab,{value:a.toLowerCase(),px:"md",children:PK.includes(a)?s.jsxs(ee,{gap:"xs",wrap:"nowrap",children:[a,s.jsx(uu,{color:t.primaryColor,size:"sm",children:"Beta"})]}):a},a))})})})]}),s.jsx(M0,{})]})}function RK(){return s.jsx(Oe,{children:s.jsxs(Ae,{children:[s.jsx(be,{order:1,children:"Unexpected Error"}),s.jsx(he,{children:"We're sorry, something went wrong."}),s.jsxs(he,{children:["Please contact ",s.jsx(Xe,{href:"mailto:support@medplum.com",children:"support"})," for assistance."]})]})})}const _K="_root_1fbwr_1",DK="_entry_1fbwr_8",IK="_key_1fbwr_13",AK="_value_1fbwr_20",ip={root:_K,entry:DK,key:IK,value:AK};function ze(e){return s.jsx(kr,{children:s.jsx("div",{className:ip.root,children:e.children})})}ze.Entry=function(t){return s.jsx("div",{className:ip.entry,children:t.children})};ze.Key=function(t){return s.jsx("div",{className:ip.key,children:t.children})};ze.Value=function(t){return s.jsx("div",{className:ip.value,children:t.children})};function NK(e){if(e.gender==="male")return"blue";if(e.gender==="female")return"pink"}function n_(e){var n,r;const t=St(e.patient);return t?s.jsxs(ze,{children:[s.jsx(Vi,{value:t,size:"lg",color:NK(t)}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Name"}),s.jsx(ze.Value,{children:s.jsx(qe,{to:t,fw:500,children:t.name?s.jsx(s0,{value:t.name[0],options:{use:!1}}):"[blank]"})})]}),t.birthDate&&s.jsxs(s.Fragment,{children:[s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"DoB"}),s.jsx(ze.Value,{children:t.birthDate})]}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Age"}),s.jsx(ze.Value,{children:P6(t.birthDate)})]})]}),t.gender&&s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Gender"}),s.jsx(ze.Value,{children:t.gender})]}),t.address&&s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"State"}),s.jsx(ze.Value,{children:(n=t.address[0])==null?void 0:n.state})]}),(r=t.identifier)==null?void 0:r.map(o=>s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:o==null?void 0:o.system}),s.jsx(ze.Value,{children:o==null?void 0:o.value})]},`${o==null?void 0:o.system}-${o==null?void 0:o.value}`))]}):null}function r_(e){const t=St(e.resource);if(!t)return null;const n=[{key:"Type",value:s.jsx(qe,{to:`/${t.resourceType}`,children:t.resourceType})}];function r(a,l){a&&l&&n.push({key:a,value:l})}function o(a){a&&r(a.system,a.value)}function i(a,l){Array.isArray(l)?l.forEach(c=>i(a,c)):typeof l=="string"?r(a,l):l&&(Array.isArray(l.coding)?r(a,l.coding.map(c=>c.display||c.code).join(", ")):r(a,l.text))}if("name"in t){const a=Wo(t);a!==ct(t)&&r("Name",a)}return"category"in t&&i("Category",t.category),t.resourceType!=="Bot"&&"code"in t&&i("Code",t.code),"identifier"in t&&(Array.isArray(t.identifier)?t.identifier.forEach(o):o(t.identifier)),n.length===1&&n.push({key:"ID",value:t.id}),s.jsx(ze,{children:n.map(a=>s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:a.key}),s.jsx(ze.Value,{children:a.value})]},`${a.key}-${a.value}`))})}function z0(e){if(e.resourceType==="Patient")return e;if(e.resourceType==="DiagnosticReport"||e.resourceType==="Encounter"||e.resourceType==="Observation"||e.resourceType==="ServiceRequest")return e.subject}function MK(e){var t;if(e.resourceType==="Specimen")return e;if(e.resourceType==="Observation")return e.specimen;if(e.resourceType==="DiagnosticReport"||e.resourceType==="ServiceRequest")return(t=e.specimen)==null?void 0:t[0]}function Md(e,t){return new Promise((n,r)=>{var i;const o=new MessageChannel;o.port1.onmessage=({data:a})=>{o.port1.close(),a.error?r(a.error):n(a.result)},(i=e.contentWindow)==null||i.postMessage(t,"https://codeeditor.medplum.com",[o.port2])})}function qi(e){var t;return sl((t=e.getActiveLogin())==null?void 0:t.project)}function OK(e,t){const n=new Blob([e],{type:sn.JSON}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r;const i=new Date().toISOString().replace(/\D/g,"");o.download=`${i}.json`,document.body.appendChild(o),o.click(),URL.revokeObjectURL(r)}function LK(){const{id:e}=ft(),t=ri(),r=Object.fromEntries(new URLSearchParams(t.search).entries()).subject,o=ae(),[i,a]=p.useState(!0),[l,c]=p.useState(),[u,d]=p.useState(),[f,h]=p.useState(),[m,g]=p.useState(),[v,S]=p.useState();if(p.useEffect(()=>{const y={resourceType:"Bundle",type:"batch",entry:[{request:{method:"GET",url:`Questionnaire/${e}`}}]};if(r){const w=r.split(",").filter(C=>!!C);w.length===1&&y.entry.push({request:{method:"GET",url:w[0]}}),d(w)}o.executeBatch(y).then(w=>{var C,j,T,E,R,_,N,O;((T=(j=(C=w.entry)==null?void 0:C[0])==null?void 0:j.response)==null?void 0:T.status)!=="200"?g((_=(R=(E=w.entry)==null?void 0:E[0])==null?void 0:R.response)==null?void 0:_.outcome):(c((N=w.entry[0])==null?void 0:N.resource),h((O=w.entry[1])==null?void 0:O.resource)),a(!1)}).catch(w=>{g(w),a(!1)})},[o,e,r]),m)return s.jsx(Oe,{children:s.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)})});if(v)return s.jsxs(Oe,{children:[s.jsx(be,{children:l==null?void 0:l.title}),s.jsx("p",{children:"Your response has been recorded."}),s.jsxs("ul",{children:[v.length===1&&s.jsx("li",{children:s.jsx(qe,{to:v[0],children:"Review your answers"})}),v.length>1&&s.jsxs("li",{children:["Review your answers:",s.jsx("ul",{children:v.map(y=>s.jsx("li",{children:s.jsx(qe,{to:y,children:ct(y)})},y.id))})]}),f&&s.jsx("li",{children:s.jsxs(qe,{to:f,children:["Back to ",Wo(f)]})}),s.jsx("li",{children:s.jsx(qe,{to:"/",children:"Go back home"})})]})]});if(i||!l)return s.jsx(Tr,{});const b=f&&z0(f);return s.jsxs(s.Fragment,{children:[s.jsxs(Xn,{shadow:"xs",radius:0,children:[b&&s.jsx(n_,{patient:b}),f&&f.resourceType!=="Patient"&&s.jsx(r_,{resource:f}),s.jsx(q,{px:"xl",py:"md",children:s.jsxs(he,{children:[Wo(l),u&&u.length>1&&s.jsxs(s.Fragment,{children:[" (for ",u.length," resources)"]})]})})]}),s.jsx(Oe,{children:s.jsx(y2,{questionnaire:l,subject:f&&Tt(f),onSubmit:x})})]});async function x(y){const w=[];if(!u||u.length===0)w.push(await o.createResource(y));else for(const C of u)w.push(await o.createResource({...y,subject:{reference:C}}));S(w)}}const $K="_paper_unw9o_1",FK={paper:$K},zK={Bot:"/admin/bots/new",ClientApplication:"/admin/clients/new"};function o_(e,t){const n=e.resourceType||UK(t),r=e.fields??BK(n),o=e.filters??(e.resourceType?void 0:VK(n)),i=e.sortRules??WK(n),a=e.offset??0,l=e.count??Vh;return{...e,resourceType:n,fields:r,filters:o,sortRules:i,offset:a,count:l}}function UK(e){var t,n;return localStorage.getItem("defaultResourceType")??((n=(t=e==null?void 0:e.option)==null?void 0:t.find(r=>r.id==="defaultResourceType"))==null?void 0:n.valueString)??"Patient"}function BK(e){const t=U0(e);if(t!=null&&t.fields)return t.fields;const n=["id","_lastUpdated"];switch(e){case"Patient":n.push("name","birthDate","gender");break;case"AccessPolicy":case"Bot":case"ClientApplication":case"Practitioner":case"Project":case"Organization":case"Questionnaire":case"UserConfiguration":n.push("name");break;case"CodeSystem":case"ValueSet":n.push("name","title","status");break;case"Condition":n.push("subject","code","clinicalStatus");break;case"Device":n.push("manufacturer","deviceName","patient");break;case"DeviceDefinition":n.push("manufacturer[x]","deviceName");break;case"DeviceRequest":n.push("code[x]","subject");break;case"DiagnosticReport":case"Observation":n.push("subject","code","status");break;case"Encounter":n.push("subject");break;case"ServiceRequest":n.push("subject","code","status","orderDetail");break;case"Subscription":n.push("criteria");break;case"User":n.push("email");break}return n}function VK(e){var t;return(t=U0(e))==null?void 0:t.filters}function WK(e){const t=U0(e);return t!=null&&t.sortRules?t.sortRules:[{code:"_lastUpdated",descending:!0}]}function U0(e){const t=localStorage.getItem(e+"-defaultSearch");return t?JSON.parse(t):void 0}function HK(e){localStorage.setItem("defaultResourceType",e.resourceType),localStorage.setItem(e.resourceType+"-defaultSearch",JSON.stringify(e))}async function qK(e,t){const n={resourceType:e.resourceType,count:1e3,offset:0,filters:e.filters},r=o_(n,t.getUserConfiguration()),o=await t.search(r.resourceType,Aa({...r,total:"accurate",fields:void 0}));return Gk(o)}function US(){const e=ae(),t=Gt(),n=ri(),[r,o]=p.useState();return p.useEffect(()=>{const i=Bk(n.pathname+n.search),a=o_(i,e.getUserConfiguration());n.pathname===`/${a.resourceType}`&&n.search===Aa(a)?(HK(a),o(a)):t(`/${a.resourceType}${Aa(a)}`)},[e,t,n]),!(r!=null&&r.resourceType)||!r.fields||r.fields.length===0?s.jsx(Tr,{}):s.jsx(Xn,{shadow:"xs",m:"md",p:"xs",className:FK.paper,children:s.jsx(ku,{checkboxesEnabled:!0,search:r,onClick:i=>t(`/${i.resource.resourceType}/${i.resource.id}`),onAuxClick:i=>window.open(`/${i.resource.resourceType}/${i.resource.id}`,"_blank"),onChange:i=>{t(`/${r.resourceType}${Aa(i.definition)}`)},onNew:()=>{t(zK[r.resourceType]??`/${r.resourceType}/new`)},onExportCsv:()=>{const i=e.fhirUrl(r.resourceType,"$csv")+Aa(r);e.download(i).then(a=>{window.open(window.URL.createObjectURL(a),"_blank")}).catch(a=>pe({color:"red",message:Ie(a),autoClose:!1}))},onExportTransactionBundle:async()=>{qK(r,e).then(i=>OK(JSON.stringify(i,void 0,2))).catch(i=>pe({color:"red",message:Ie(i),autoClose:!1}))},onDelete:i=>{window.confirm("Are you sure you want to delete these resources?")&&(e.invalidateSearches(r.resourceType),e.executeBatch({resourceType:"Bundle",type:"batch",entry:i.map(a=>({request:{method:"DELETE",url:`${r.resourceType}/${a}`}}))}).then(()=>o({...r})).catch(a=>pe({color:"red",message:Ie(a),autoClose:!1})))},onBulk:i=>{t(`/bulk/${r.resourceType}?ids=${i.join(",")}`)}})})}function GK(){const e=ae(),[t,n]=p.useState(),[r,o]=p.useState(void 0);p.useEffect(()=>{e.get("auth/mfa/status").then(l=>{n(l.enrollQrCode),o(l.enrolled)}).catch(l=>pe({color:"red",message:Ie(l),autoClose:!1}))},[e]);const i=p.useCallback(l=>{e.post("auth/mfa/enroll",l).then(()=>{o(!0),pe({color:"green",message:"Success"})}).catch(c=>pe({color:"red",message:Ie(c),autoClose:!1}))},[e]),a=p.useCallback(()=>{e.post("auth/mfa/disable",{}).catch(console.log)},[e]);return r===void 0?null:r?s.jsx(Oe,{children:s.jsxs(ee,{children:[s.jsx(be,{children:"MFA is enabled"}),s.jsx(ie,{onClick:a,children:"Disable MFA"})]})}):s.jsx(Oe,{width:400,children:s.jsxs(Qe,{onSubmit:i,children:[s.jsx(be,{children:"Multi Factor Auth Setup"}),s.jsx(vn,{children:s.jsx("img",{src:t})}),s.jsx(ye,{name:"token",label:"Code"}),s.jsx(ee,{justify:"flex-end",mt:"xl",children:s.jsx(ie,{type:"submit",children:"Enroll"})})]})})}const gm={BASE_URL:"/",DEV:!1,GOOGLE_CLIENT_ID:"__GOOGLE_CLIENT_ID__",MEDPLUM_BASE_URL:"__MEDPLUM_BASE_URL__",MEDPLUM_CLIENT_ID:"__MEDPLUM_CLIENT_ID__",MEDPLUM_REGISTER_ENABLED:"__MEDPLUM_REGISTER_ENABLED__",MEDPLUM_VERSION:"3.2.21-c76aa3890",MODE:"production",PROD:!0,RECAPTCHA_SITE_KEY:"__RECAPTCHA_SITE_KEY__",SSR:!1},tv={baseUrl:"__MEDPLUM_BASE_URL__",clientId:"__MEDPLUM_CLIENT_ID__",googleClientId:"__GOOGLE_CLIENT_ID__",recaptchaSiteKey:"__RECAPTCHA_SITE_KEY__",registerEnabled:"__MEDPLUM_REGISTER_ENABLED__",awsTextractEnabled:gm==null?void 0:gm.MEDPLUM_AWS_TEXTRACT_ENABLED};function Iu(){return tv}function i_(){return s_("registerEnabled")}function QK(){return s_("awsTextractEnabled")}function s_(e){try{return tv[e]!==!1&&tv[e]!=="false"}catch{return!0}}function KK(){const e=Gt(),[t]=O0(),n=t.get("client_id");if(!n)return null;const r=t.get("scope")||"openid";function o(i){const a=new URL(t.get("redirect_uri"));for(const l of["scope","state","nonce"])t.has(l)&&a.searchParams.set(l,t.get(l));a.searchParams.set("code",i),window.location.assign(a.toString())}return s.jsxs(P2,{onCode:o,onForgotPassword:()=>e("/resetpassword"),onRegister:()=>e("/register"),googleClientId:Iu().googleClientId,clientId:n||void 0,redirectUri:t.get("redirect_uri")||void 0,scope:r,nonce:t.get("nonce")||void 0,launch:t.get("launch")||void 0,codeChallenge:t.get("code_challenge")||void 0,codeChallengeMethod:t.get("code_challenge_method")||void 0,chooseScopes:r!=="openid",children:[s.jsx(Zr,{size:32}),s.jsx(be,{children:"Sign in to Medplum"})]})}function YK(){const e=ae(),t=Gt(),n=Iu();return p.useEffect(()=>{e.getProfile()&&t("/signin?project=new")},[e,t]),i_()?s.jsxs(qq,{type:"project",projectId:"new",onSuccess:()=>t("/"),googleClientId:n.googleClientId,recaptchaSiteKey:n.recaptchaSiteKey,children:[s.jsx(Zr,{size:32}),s.jsx(be,{children:"Create a new account"})]}):s.jsx(Oe,{width:450,children:s.jsx(Ui,{icon:s.jsx(Tl,{size:16}),title:"New projects disabled",color:"red",children:"New projects are disabled on this server."})})}function XK(){const e=Gt(),t=ae(),[n,r]=p.useState(),[o,i]=p.useState(!1),a=Iu().recaptchaSiteKey;return p.useEffect(()=>{a&&E2(a)},[a]),s.jsx(Oe,{width:450,children:s.jsxs(Qe,{onSubmit:async l=>{let c="";a&&(c=await T2(a)),t.post("auth/resetpassword",{...l,recaptchaToken:c}).then(()=>i(!0)).catch(u=>r(mt(u)))},children:[s.jsxs(Ae,{gap:"lg",mb:"xl",align:"center",children:[s.jsx(Zr,{size:32}),s.jsx(be,{children:"Medplum Password Reset"})]}),s.jsxs(Ae,{gap:"xl",children:[s.jsx(Dr,{issues:Eu(n,void 0)}),!o&&s.jsxs(s.Fragment,{children:[s.jsx(ye,{name:"email",type:"email",label:"Email",required:!0,autoFocus:!0,error:Ye(n,"email")}),s.jsxs(ee,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[s.jsx(Xe,{component:"button",type:"button",color:"dimmed",onClick:()=>e("/register"),size:"xs",children:"Register"}),s.jsx(ie,{type:"submit",children:"Reset password"})]})]}),o&&s.jsx("div",{children:"If the account exists on our system, a password reset email will be sent."})]})]})})}function JK(){var i;const e=Gt(),t=ae(),[n,r]=p.useState();p.useEffect(()=>{t.get("auth/me",{cache:"no-cache"}).then(r).catch(a=>pe({color:"red",message:Ie(a),autoClose:!1}))},[t]);function o(a){t.post("auth/revoke",{loginId:a}).then(()=>t.get("auth/me",{cache:"no-cache"})).then(r).then(()=>pe({color:"green",message:"Login revoked"})).catch(l=>pe({color:"red",message:Ie(l),autoClose:!1}))}return n?s.jsxs(s.Fragment,{children:[s.jsxs(Oe,{children:[s.jsx(be,{children:"Security"}),s.jsxs(u0,{children:[s.jsx(Ao,{term:"ID",children:s.jsx(Xe,{href:`/${ct(n.profile)}`,children:n.profile.id})}),s.jsx(Ao,{term:"Resource Type",children:n.profile.resourceType}),s.jsx(Ao,{term:"Name",children:bu((i=n.profile.name)==null?void 0:i[0])})]})]}),s.jsxs(Oe,{children:[s.jsx(be,{children:"Sessions"}),s.jsxs(fe,{children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"OS"}),s.jsx("th",{children:"Browser"}),s.jsx("th",{children:"IP Address"}),s.jsx("th",{children:"Auth Method"}),s.jsx("th",{children:"Last Updated"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:n.security.sessions.map(a=>s.jsxs("tr",{children:[s.jsx("td",{children:a.os}),s.jsx("td",{children:a.browser}),s.jsx("td",{children:a.remoteAddress}),s.jsx("td",{children:a.authMethod}),s.jsx("td",{children:Ln(a.lastUpdated)}),s.jsx("td",{children:s.jsx(Xe,{href:"#",onClick:()=>o(a.id),children:"Revoke"})})]},a.id))})]})]}),s.jsxs(Oe,{children:[s.jsx(be,{children:"Password"}),s.jsx(ie,{onClick:()=>e("/changepassword"),children:"Change password"})]}),s.jsxs(Oe,{children:[s.jsx(be,{children:"Multi Factor Auth"}),s.jsxs("p",{children:["Enrolled: ",n.security.mfaEnrolled.toString()]}),!n.security.mfaEnrolled&&s.jsx(ie,{onClick:()=>e("/mfa"),children:"Enroll"})]})]}):null}function ZK(){const{id:e,secret:t}=ft(),n=ae(),[r,o]=p.useState(),[i,a]=p.useState(!1),l=Eu(r,void 0);return s.jsxs(Oe,{width:450,children:[s.jsx(Dr,{issues:l}),s.jsxs(Qe,{onSubmit:c=>{if(c.password!==c.confirmPassword){o(go("Passwords do not match","confirmPassword"));return}o(void 0);const u={id:e,secret:t,password:c.password};n.post("auth/setpassword",u).then(()=>a(!0)).catch(d=>o(mt(d)))},children:[s.jsxs(vn,{style:{flexDirection:"column"},children:[s.jsx(Zr,{size:32}),s.jsx(be,{children:"Set password"})]}),!i&&s.jsxs(Ae,{children:[s.jsx(Wr,{name:"password",label:"New password",required:!0,error:Ye(r,"password")}),s.jsx(Wr,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Ye(r,"confirmPassword")}),s.jsx(ee,{justify:"flex-end",mt:"xl",children:s.jsx(ie,{type:"submit",children:"Set password"})})]}),i&&s.jsxs("div",{"data-testid":"success",children:["Password set. You can now ",s.jsx(qe,{to:"/signin",children:"sign in"}),"."]})]})]})}function eY(){const e=Qh(),t=Gt(),[n]=O0(),r=Iu(),o=p.useCallback(()=>{const i=n.get("next");t(i!=null&&i.startsWith("/")?i:"/")},[n,t]);return p.useEffect(()=>{e&&n.has("next")&&o()},[e,n,o]),s.jsxs(P2,{onSuccess:()=>o(),onForgotPassword:()=>t("/resetpassword"),onRegister:i_()?()=>t("/register"):void 0,googleClientId:r.googleClientId,login:n.get("login")||void 0,projectId:n.get("project")||void 0,children:[s.jsx(Zr,{size:32}),s.jsx(be,{children:"Sign in to Medplum"}),n.get("project")==="new"&&s.jsx("div",{children:"Sign in again to create a new project"})]})}function tY(){const e=Gt(),t=ri(),[n,r]=p.useState(),[o,i]=p.useState(),[a,l]=p.useState();return p.useEffect(()=>{const c=Object.fromEntries(new URLSearchParams(t.search).entries());r(c.resourceType),i(c.query),l(JSON.parse(c.fields))},[t]),!n||!o||!a?null:s.jsx(QW,{resourceType:n,checkboxesEnabled:!0,query:o,fields:a,onClick:c=>e(`/${n}/${c.resource.id}`),onAuxClick:c=>window.open(`/${n}/${c.resource.id}`,"_blank"),onBulk:c=>{e(`/bulk/${n}?ids=${c.join(",")}`)}})}function sp(e){const t=ae(),n=qi(t),r=Gt(),[o,i]=p.useState({resourceType:"ProjectMembership",filters:[{code:"project",operator:oe.EQUALS,value:"Project/"+n},{code:"profile-type",operator:oe.EQUALS,value:e.resourceType}],fields:e.fields,count:100});return s.jsx(ku,{search:o,onClick:a=>r(`/admin/members/${a.resource.id}`),onChange:a=>i(a.definition),hideFilters:!0,hideToolbar:!0})}function nY(){return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Bots"}),s.jsx(sp,{resourceType:"Bot",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(ee,{justify:"flex-end",children:s.jsx(qe,{to:"/admin/bots/new",children:"Create new bot"})})]})}function rY(){return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Clients"}),s.jsx(sp,{resourceType:"ClientApplication",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(ee,{justify:"flex-end",children:s.jsx(qe,{to:"/admin/clients/new",children:"Create new client"})})]})}function ap(e){return s.jsx(Ys,{resourceType:"AccessPolicy",name:"accessPolicy",defaultValue:e.defaultValue,placeholder:"Access Policy",onChange:t=>{ti(t)?e.onChange(Tt(t)):e.onChange(void 0)}})}function oY(){const e=ae(),t=qi(e),[n,r]=p.useState(""),[o,i]=p.useState(""),[a,l]=p.useState(),[c,u]=p.useState(),[d,f]=p.useState(void 0);return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Create new Bot"}),s.jsxs(Qe,{onSubmit:()=>{const h={name:n,description:o,accessPolicy:a};e.post("admin/projects/"+t+"/bot",h).then(m=>{e.invalidateSearches("Bot"),e.invalidateSearches("ProjectMembership"),f(m),pe({color:"green",message:"Bot created"})}).catch(m=>{pe({color:"red",message:Ie(m),autoClose:!1}),u(mt(m))})},children:[!d&&s.jsxs(Ae,{children:[s.jsx(yt,{title:"Name",htmlFor:"name",outcome:c,children:s.jsx(ye,{id:"name",name:"name",required:!0,autoFocus:!0,onChange:h=>r(h.currentTarget.value),error:Ye(c,"name")})}),s.jsx(yt,{title:"Description",htmlFor:"description",outcome:c,children:s.jsx(ye,{id:"description",name:"description",onChange:h=>i(h.currentTarget.value),error:Ye(c,"description")})}),s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:c,children:s.jsx(ap,{name:"accessPolicy",onChange:l})}),s.jsx(ee,{justify:"flex-end",children:s.jsx(ie,{type:"submit",children:"Create Bot"})})]}),d&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(he,{children:"Bot created"}),s.jsxs(Mn,{children:[s.jsx(Mn.Item,{children:s.jsx(qe,{to:d,children:"Go to new bot"})}),s.jsx(Mn.Item,{children:s.jsx(qe,{to:"/admin/bots",children:"Back to bots list"})})]})]})]})]})}function iY(){const e=ae(),t=qi(e),[n,r]=p.useState(""),[o,i]=p.useState(""),[a,l]=p.useState(""),[c,u]=p.useState(),[d,f]=p.useState(),[h,m]=p.useState(void 0);return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Create new Client"}),s.jsxs(Qe,{onSubmit:()=>{const g={name:n,description:o,redirectUri:a,accessPolicy:c};e.post("admin/projects/"+t+"/client",g).then(v=>{e.invalidateSearches("ClientApplication"),e.invalidateSearches("ProjectMembership"),m(v),pe({color:"green",message:"Client created"})}).catch(v=>{pe({color:"red",message:Ie(v),autoClose:!1}),f(mt(v))})},children:[!h&&s.jsxs(Ae,{children:[s.jsx(yt,{title:"Name",htmlFor:"name",outcome:d,children:s.jsx(ye,{id:"name",name:"name",required:!0,autoFocus:!0,onChange:g=>r(g.currentTarget.value),error:Ye(d,"name")})}),s.jsx(yt,{title:"Description",htmlFor:"description",outcome:d,children:s.jsx(ye,{id:"description",name:"description",onChange:g=>i(g.currentTarget.value),error:Ye(d,"description")})}),s.jsx(yt,{title:"Redirect URI",htmlFor:"redirectUri",outcome:d,children:s.jsx(ye,{id:"redirectUri",name:"redirectUri",onChange:g=>l(g.currentTarget.value),error:Ye(d,"redirectUri")})}),s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:d,children:s.jsx(ap,{name:"accessPolicy",onChange:u})}),s.jsx(ee,{justify:"flex-end",children:s.jsx(ie,{type:"submit",children:"Create Client"})})]}),h&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(he,{children:"Client created"}),s.jsxs(Mn,{children:[s.jsx(Mn.Item,{children:s.jsx(qe,{to:h,children:"Go to new client"})}),s.jsx(Mn.Item,{children:s.jsx(qe,{to:"/admin/clients",children:"Back to clients list"})})]})]})]})]})}function sY(e){return s.jsx(Ys,{resourceType:"UserConfiguration",name:"userConfiguration",defaultValue:e.defaultValue,placeholder:"User Configuration",onChange:t=>{ti(t)?e.onChange(Tt(t)):e.onChange(void 0)}})}function aY(){const{membershipId:e}=ft(),t=ae(),n=qi(t),r=Gt(),o=t.get(`admin/projects/${n}/members/${e}`).read(),[i,a]=p.useState(o.accessPolicy),[l,c]=p.useState(o.userConfiguration),[u,d]=p.useState(o.admin),[f,h]=p.useState(),[m,g]=p.useState(!1);function v(){window.confirm("Are you sure?")&&t.delete(`admin/projects/${n}/members/${e}`).then(()=>t.get(`admin/projects/${n}`,{cache:"no-cache"})).then(()=>r("/admin/project")).catch(S=>h(mt(S)))}return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Edit membership"}),s.jsx("h3",{children:s.jsx(Ha,{value:o.profile,link:!0})}),s.jsxs(Qe,{onSubmit:()=>{const S={...o,accessPolicy:i,userConfiguration:l,admin:u};t.post(`admin/projects/${n}/members/${e}`,S).then(()=>g(!0)).catch(b=>h(mt(b)))},children:[!m&&s.jsxs(Ae,{children:[s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:f,children:s.jsx(ap,{name:"accessPolicy",defaultValue:i,onChange:a})}),s.jsx(yt,{title:"User Configuration",htmlFor:"userConfiguration",outcome:f,children:s.jsx(sY,{name:"userConfiguration",defaultValue:l,onChange:c})}),s.jsx(yt,{title:"Admin",htmlFor:"admin",outcome:f,children:s.jsx(kn,{id:"admin",name:"admin",defaultChecked:u,onChange:S=>d(S.currentTarget.checked)})}),s.jsxs(ee,{justify:"flex-end",mt:"xl",children:[s.jsx(ie,{type:"submit",children:"Save"}),s.jsx(ie,{type:"button",color:"red",variant:"outline",onClick:v,children:"Remove user"})]})]}),m&&s.jsxs("div",{"data-testid":"success",children:[s.jsx("p",{children:"User updated"}),s.jsx("pre",{children:JSON.stringify(f,void 0,2)}),s.jsxs("p",{children:["Click ",s.jsx(qe,{to:"/admin/project",children:"here"})," to return to the project admin page."]})]})]})]})}function lY(){const e=ae(),[t,n]=p.useState(e.getProject()),[r,o]=p.useState(),[i,a]=p.useState(),[l,c]=p.useState(!1),[u,d]=p.useState(void 0),f=p.useCallback(h=>{const m={resourceType:h.resourceType,firstName:h.firstName,lastName:h.lastName,email:h.email,sendEmail:h.sendEmail==="on",accessPolicy:r,admin:h.isAdmin==="on"};e.invite(t==null?void 0:t.id,m).then(g=>{e.invalidateSearches("Patient"),e.invalidateSearches("Practitioner"),e.invalidateSearches("ProjectMembership"),zh(g)?a(g):d(g),c(m.sendEmail??!1),pe({color:"green",message:"Invite success"})}).catch(g=>{pe({color:"red",message:Ie(g),autoClose:!1}),a(mt(g))})},[e,t,r]);return s.jsxs(Qe,{onSubmit:f,children:[!u&&!i&&s.jsxs(Ae,{children:[s.jsx(be,{children:"Invite new member"}),e.isSuperAdmin()&&s.jsx(yt,{title:"Project",htmlFor:"project",outcome:i,children:s.jsx(Ys,{resourceType:"Project",name:"project",defaultValue:t,onChange:n})}),s.jsx(Pt,{name:"resourceType",label:"Role",defaultValue:"Practitioner",data:["Practitioner","Patient","RelatedPerson"],error:Ye(i,"resourceType")}),s.jsx(ye,{name:"firstName",label:"First Name",required:!0,autoFocus:!0,error:Ye(i,"firstName")}),s.jsx(ye,{name:"lastName",label:"Last Name",required:!0,error:Ye(i,"lastName")}),s.jsx(ye,{name:"email",type:"email",label:"Email",required:!0,error:Ye(i,"email")}),s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:i,children:s.jsx(ap,{name:"accessPolicy",onChange:o})}),s.jsx(kn,{name:"sendEmail",label:"Send email",defaultChecked:!0}),s.jsx(kn,{name:"isAdmin",label:"Admin"}),s.jsx(ee,{justify:"flex-end",children:s.jsx(ie,{type:"submit",children:"Invite"})})]}),i&&s.jsxs("div",{"data-testid":"success",children:[s.jsx("p",{children:"User created, email couldn't be sent"}),s.jsx("p",{children:"Could not send email. Make sure you have AWS SES set up."}),s.jsxs("p",{children:["Click ",s.jsx(qe,{to:"/admin/project",children:"here"})," to return to the project admin page."]})]}),u&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(he,{children:"User created"}),l&&s.jsx(he,{children:"Email sent"}),s.jsxs(Mn,{children:[s.jsx(Mn.Item,{children:s.jsx(qe,{to:u,children:"Go to new membership"})}),s.jsx(Mn.Item,{children:s.jsx(qe,{to:u.profile,children:"Go to new profile"})}),s.jsx(Mn.Item,{children:s.jsx(qe,{to:"/admin/users",children:"Back to users list"})})]})]})]})}function cY(){return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Patients"}),s.jsx(sp,{resourceType:"Patient",fields:["user","profile","_lastUpdated"]}),s.jsx(ee,{justify:"flex-end",children:s.jsx(qe,{to:"/admin/invite",children:"Invite new patient"})})]})}function uY(){const e=ae();if(!e.isLoading()&&!e.isProjectAdmin())return s.jsx(Dr,{outcome:hk});function t(n){e.post("admin/projects/setpassword",n).then(()=>pe({color:"green",message:"Done"})).catch(r=>pe({color:"red",message:Ie(r),autoClose:!1}))}return s.jsxs(Oe,{width:600,children:[s.jsx(be,{order:1,children:"Project Admin"}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Force Set Password"}),s.jsx(he,{children:"Sets the password for the specified user in this project."}),s.jsx(he,{children:"This action can only be performed by project administrators. Passwords can only be set for users scoped in this project."}),s.jsx(Qe,{onSubmit:t,children:s.jsxs(Ae,{children:[s.jsx(ye,{name:"email",label:"Email",required:!0}),s.jsx(Wr,{name:"password",label:"Password",required:!0}),s.jsx(ie,{type:"submit",children:"Force Set Password"})]})})]})}function BS(){const e=ae(),t=qi(e),n=e.get(`admin/projects/${t}`).read();return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Details"}),s.jsxs(u0,{children:[s.jsx(Ao,{term:"ID",children:n.project.id}),s.jsx(Ao,{term:"Name",children:n.project.name})]})]})}const VS=["Details","Users","Patients","Clients","Bots","Secrets","Sites"];function dY(){const e=Gt(),n=ri().pathname.replace("/admin/","")||VS[0],r=ae(),o=qi(r),i=p.useMemo(()=>r.get("admin/projects/"+o).read(),[r,o]);function a(l){e(`/admin/${l}`)}return s.jsxs(s.Fragment,{children:[s.jsxs(Xn,{children:[s.jsx(ze,{children:s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Project"}),s.jsx(ze.Value,{children:i.project.name})]})}),s.jsx(kr,{children:s.jsx(et,{value:n.toLowerCase(),onChange:a,children:s.jsx(et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:VS.map(l=>s.jsx(et.Tab,{value:l.toLowerCase(),children:l},l))})})})]}),s.jsx(Oe,{children:s.jsx(M0,{})})]})}function fY(){const e=ae(),t=qi(e),n=e.get(`admin/projects/${t}`).read(),[r,o]=p.useState(!1),[i,a]=p.useState();return p.useEffect(()=>{e.requestSchema("Project").then(()=>o(!0)).catch(console.log)},[e]),p.useEffect(()=>{n&&a(Qr(n.project.secret||[]))},[e,n]),!r||!i?s.jsx("div",{children:"Loading..."}):s.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:l=>{l.preventDefault(),e.post(`admin/projects/${t}/secrets`,i).then(()=>e.get(`admin/projects/${t}`,{cache:"reload"})).then(()=>pe({color:"green",message:"Saved"})).catch(console.log)},children:[s.jsx(be,{children:"Project Secrets"}),s.jsx("p",{children:"Use project secrets to store sensitive information such as API keys or other access credentials."}),s.jsx(Pl,{property:Gs("Project","secret"),name:"secret",path:"Project.secret",defaultValue:i,onChange:a,outcome:void 0}),s.jsx(ie,{type:"submit",children:"Save"})]})}function hY(){const e=ae(),t=qi(e),n=e.get(`admin/projects/${t}`).read(),[r,o]=p.useState(!1),[i,a]=p.useState();return p.useEffect(()=>{e.requestSchema("Project").then(()=>o(!0)).catch(console.log)},[e]),p.useEffect(()=>{n&&a(Qr(n.project.site||[]))},[e,n]),!r||!i?s.jsx("div",{children:"Loading..."}):s.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:l=>{l.preventDefault(),e.post(`admin/projects/${t}/sites`,i).then(()=>e.get(`admin/projects/${t}`,{cache:"reload"})).then(()=>pe({color:"green",message:"Saved"})).catch(c=>{var d,f,h,m;const u=mt(c);pe({color:"red",message:`Error ${(f=(d=u.issue)==null?void 0:d[0].details)==null?void 0:f.text} ${(m=(h=u.issue)==null?void 0:h[0].expression)==null?void 0:m[0]}`,autoClose:!1})})},children:[s.jsx(be,{children:"Project Sites"}),s.jsx("p",{children:"Use project sites configure your project on a separate domain."}),s.jsx(Pl,{property:Gs("Project","site"),name:"site",path:"Project.site",defaultValue:i,onChange:a,outcome:void 0}),s.jsx(ie,{type:"submit",children:"Save"})]})}function pY(){const e=ae(),[t,{open:n,close:r}]=Bf(!1),[o,i]=p.useState(""),[a,l]=p.useState();if(!e.isLoading()&&!e.isSuperAdmin())return s.jsx(Dr,{outcome:hk});function c(){md(e,"Rebuilding Structure Definitions","admin/super/structuredefinitions")}function u(){md(e,"Rebuilding Search Parameters","admin/super/searchparameters")}function d(){md(e,"Rebuilding Value Sets","admin/super/valuesets")}function f(S){md(e,"Reindexing Resources","admin/super/reindex",S)}function h(S){e.post("admin/super/removebotidjobsfromqueue",S).then(()=>pe({color:"green",message:"Done"})).catch(b=>pe({color:"red",message:Ie(b),autoClose:!1}))}function m(S){e.post("admin/super/purge",{...S,before:kR(S.before)}).then(()=>pe({color:"green",message:"Done"})).catch(b=>pe({color:"red",message:Ie(b),autoClose:!1}))}function g(S){e.post("admin/super/setpassword",S).then(()=>pe({color:"green",message:"Done"})).catch(b=>pe({color:"red",message:Ie(b),autoClose:!1}))}function v(){e.post("fhir/R4/$db-stats",{}).then(S=>{var b,x;i("Database Stats"),l(s.jsx("pre",{children:(x=(b=S.parameter)==null?void 0:b.find(y=>y.name==="tableString"))==null?void 0:x.valueString})),n()}).catch(S=>pe({color:"red",message:Ie(S),autoClose:!1}))}return s.jsxs(Oe,{width:600,children:[s.jsx(be,{order:1,children:"Super Admin"}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Structure Definitions"}),s.jsx("p",{children:"StructureDefinition resources contain the metadata about resource types. They are provided with the FHIR specification. Medplum also includes some custom StructureDefinition resources for internal data types. Press this button to update the database StructureDefinitions from the FHIR specification."}),s.jsx(Qe,{children:s.jsx(ie,{onClick:c,children:"Rebuild StructureDefinitions"})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Search Parameters"}),s.jsx("p",{children:"SearchParameter resources contain the metadata about filters and sorting. They are provided with the FHIR specification. Medplum also includes some custom SearchParameter resources for internal data types. Press this button to update the database SearchParameters from the FHIR specification."}),s.jsx(Qe,{children:s.jsx(ie,{onClick:u,children:"Rebuild SearchParameters"})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Value Sets"}),s.jsx("p",{children:"ValueSet resources enum values for a wide variety of use cases. Press this button to update the database ValueSets from the FHIR specification."}),s.jsx(Qe,{children:s.jsx(ie,{onClick:d,children:"Rebuild ValueSets"})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Reindex Resources"}),s.jsx("p",{children:"When Medplum changes how resources are indexed, the system may require a reindex for old resources to be indexed properly."}),s.jsx(Qe,{onSubmit:f,children:s.jsxs(Ae,{children:[s.jsx(yt,{title:"Resource Type",htmlFor:"resourceType",children:s.jsx(ye,{id:"resourceType",name:"resourceType",placeholder:"Reindex Resource Type"})}),s.jsx(yt,{title:"Search Filter",htmlFor:"filter",children:s.jsx(ye,{id:"filter",name:"filter",placeholder:"e.g. name=Sam&birthdate=lt2000-01-01"})}),s.jsx(ie,{type:"submit",children:"Reindex"})]})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Purge Resources"}),s.jsx("p",{children:"As system generated resources accumulate, the system may require a purge to remove old resources."}),s.jsx(Qe,{onSubmit:m,children:s.jsxs(Ae,{children:[s.jsx(yt,{title:"Purge Resource Type",htmlFor:"purgeResourceType",children:s.jsx(Pt,{id:"purgeResourceType",name:"resourceType",data:["","AuditEvent","Login"]})}),s.jsx(yt,{title:"Purge Before",htmlFor:"before",children:s.jsx(Rs,{name:"before",placeholder:"Before Date"})}),s.jsx(ie,{type:"submit",children:"Purge"})]})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Remove Bot ID Jobs from Queue"}),s.jsx("p",{children:"Remove all queued jobs for a Bot ID"}),s.jsx(Qe,{onSubmit:h,children:s.jsxs(Ae,{children:[s.jsx(yt,{title:"Bot ID",children:s.jsx(ye,{name:"botId",placeholder:"Bot Id"})}),s.jsx(ie,{type:"submit",children:"Remove Jobs by Bot ID"})]})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Force Set Password"}),s.jsx("p",{children:'Note that this applies to all projects for the user. Therefore, this should only be used in extreme circumstances. Always prefer to use the "Forgot Password" flow first.'}),s.jsx(Qe,{onSubmit:g,children:s.jsxs(Ae,{children:[s.jsx(ye,{name:"email",label:"Email",required:!0}),s.jsx(Wr,{name:"password",label:"Password",required:!0}),s.jsx(ye,{name:"projectId",label:"Project ID"}),s.jsx(ie,{type:"submit",children:"Force Set Password"})]})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Database Stats"}),s.jsx("p",{children:"Query current table statistics from the database."}),s.jsx(Qe,{onSubmit:v,children:s.jsx(ie,{type:"submit",children:"Get Database Stats"})}),s.jsx(mn,{opened:t,onClose:r,title:o,centered:!0,children:a})]})}function md(e,t,n,r){mo.show({id:n,loading:!0,title:t,message:"Running...",autoClose:!1,withCloseButton:!1});const o={method:"POST",pollStatusOnAccepted:!0};r&&(o.body=JSON.stringify(r)),e.startAsyncRequest(n,o).then(()=>{mo.update({id:n,color:"green",title:t,message:"Done",icon:s.jsx(Ks,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}).catch(i=>{mo.update({id:n,color:"red",title:t,message:Ie(i),icon:s.jsx(Cf,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})})}function mY(){return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Users"}),s.jsx(sp,{resourceType:"Practitioner",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(ee,{justify:"flex-end",children:s.jsx(qe,{to:"/admin/invite",children:"Invite new user"})})]})}function gY(){const[e]=ll("ObservationDefinition","_count=100");return e?s.jsxs(fe,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Category"}),s.jsx("th",{children:"Code"}),s.jsx("th",{children:"Method"}),s.jsx("th",{children:"Unit"}),s.jsx("th",{children:"Precision"}),s.jsx("th",{children:"Ranges"})]})}),s.jsx("tbody",{children:e.map(t=>{var n,r,o,i;return s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(vo,{value:(n=t.category)==null?void 0:n[0]})}),s.jsx("td",{children:s.jsx(vo,{value:t.code})}),s.jsx("td",{children:s.jsx(vo,{value:t.method})}),s.jsx("td",{children:(o=(r=t.quantitativeDetails)==null?void 0:r.unit)==null?void 0:o.text}),s.jsx("td",{children:(i=t.quantitativeDetails)==null?void 0:i.decimalPrecision}),s.jsx("td",{children:s.jsx(nv,{ranges:t.qualifiedInterval})})]},t.id)})})]}):s.jsx(Tr,{})}function nv(e){const{ranges:t}=e;if(!t)return null;const n=WS(t.map(o=>o.gender));if(n.length>1)return Uc(n),s.jsx(s.Fragment,{children:n.map(o=>{var i;return s.jsxs(p.Fragment,{children:[s.jsx("div",{children:s.jsx("strong",{children:tn(o)})}),s.jsx(nv,{ranges:(i=e.ranges)==null?void 0:i.filter(a=>a.gender===o)})]},o)})});const r=WS(t.map(o=>o.age&&Bc(o.age)));return r.length>1?(Uc(r),s.jsx(s.Fragment,{children:r.map(o=>{var i;return s.jsxs(p.Fragment,{children:[s.jsx("div",{children:s.jsx("strong",{children:tn(o)})}),s.jsx(nv,{ranges:(i=e.ranges)==null?void 0:i.filter(a=>Bc(a.age)===o)})]},o)})})):s.jsx(s.Fragment,{children:t.map(o=>s.jsx("table",{children:s.jsx("tbody",{children:s.jsxs("tr",{children:[s.jsx("td",{children:o.condition}),s.jsx("td",{children:s.jsx(f0,{value:o.range})})]})})},`range-${o.condition}`))})}function WS(e){return[...new Set(e.filter(t=>!!t))]}function vY(){const[e]=ll("ActivityDefinition","_count=100"),[t]=ll("ObservationDefinition","_count=100");return!e||!t?s.jsx(Tr,{}):s.jsxs(fe,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Category"}),s.jsx("th",{children:"Assay"}),e.map(n=>s.jsx("th",{children:n.name},n.id))]})}),s.jsx("tbody",{children:t.map(n=>{var r;return s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(vo,{value:(r=n.category)==null?void 0:r[0]})}),s.jsx("td",{children:s.jsx(vo,{value:n.code})}),e.map(o=>{var i;return s.jsx("td",{children:(i=o.observationResultRequirement)!=null&&i.find(a=>{var l;return(l=a.reference)==null?void 0:l.includes(n.id)})?"✅":""},o.id)})]},n.id)})})]})}function yY(e){var a;const t=ae(),[n,r]=p.useState(),[o,i]=p.useState();return o?s.jsxs(s.Fragment,{children:[s.jsx("p",{children:"Request group created successfully."}),s.jsxs("ul",{children:[s.jsxs("li",{children:["Go to the"," ",s.jsx(qe,{to:o,suffix:"checklist",children:"Request Group"})]}),s.jsxs("li",{children:["Back to the ",s.jsx(qe,{to:e.planDefinition,children:"Plan Definition"})]})]})]}):s.jsx(Qe,{onSubmit:()=>{t.post(t.fhirUrl("PlanDefinition",e.planDefinition.id,"$apply"),{resourceType:"Parameters",parameter:[{name:"subject",valueString:n==null?void 0:n.reference}]}).then(i).catch(console.log)},children:s.jsxs(Ae,{children:[s.jsxs(be,{children:['Start "',e.planDefinition.title,'"']}),s.jsxs(he,{children:["Use the ",s.jsx("strong",{children:"Apply"})," operation to create a group of tasks for a workflow."]}),s.jsx(he,{children:"The following tasks will be created:"}),s.jsx("ul",{children:(a=e.planDefinition.action)==null?void 0:a.map((l,c)=>{var u;return s.jsxs("li",{children:[((u=l.definitionCanonical)==null?void 0:u.startsWith("Questionnaire/"))&&"Questionnaire request: ",l.title&&s.jsx(s.Fragment,{children:l.title}),l.code&&s.jsx(vo,{value:l.code[0]})]},`action-${c}`)})}),s.jsx(yt,{title:"Subject",children:s.jsx(Yh,{name:"subject",targetTypes:["Patient","Practitioner"],defaultValue:n,onChange:r})}),s.jsx(ee,{justify:"flex-end",mt:"xl",children:s.jsx(ie,{type:"submit",children:"Go"})})]})})}function xY(){const{resourceType:e,id:t}=ft(),n=St({reference:e+"/"+t});return n?s.jsx(Oe,{children:s.jsx(yY,{planDefinition:n})}):null}function bY(){const{resourceType:e,id:t}=ft(),n=St({reference:e+"/"+t}),[r,o]=ll("Questionnaire","subject-type="+e),[i,a]=ll("ClientApplication",{_count:1e3});if(!n||o||a)return s.jsx(Tr,{});const l=i==null?void 0:i.filter(d=>wY(e)&&!!d.launchUri);if((!r||r.length===0)&&(!l||l.length===0))return s.jsxs(Oe,{children:[s.jsx(be,{children:"Apps"}),s.jsxs("p",{children:["No apps found. Contact your administrator or ",s.jsx("a",{href:"mailto:support@medplum.com",children:"Medplum Support"})," to add automation here."]})]});let c,u;return n.resourceType==="Patient"?c=Tt(n):n.resourceType==="Encounter"&&(c=n.subject,u=Tt(n)),s.jsxs(Oe,{children:[r==null?void 0:r.map(d=>s.jsxs("div",{children:[s.jsx(be,{order:3,children:s.jsx(qe,{to:`/forms/${d.id}?subject=${ct(n)}`,children:d.title||d.name})}),s.jsx(he,{children:d.description})]},d.id)),l==null?void 0:l.map(d=>s.jsxs("div",{children:[s.jsx(be,{order:3,children:s.jsx(Wq,{client:d,patient:c,encounter:u,children:d.name})}),s.jsx(he,{children:d.description})]},d.id))]})}function wY(e){return e==="Patient"||e==="Encounter"}function SY(){const{resourceType:e,id:t}=ft(),n=Gt(),[r,o]=p.useState({resourceType:"AuditEvent",filters:[{code:"entity",operator:oe.EQUALS,value:`${e}/${t}`}],fields:["id","outcome","outcomeDesc","_lastUpdated"],sortRules:[{code:"-_lastUpdated"}],count:20});return s.jsx(Oe,{children:s.jsx(ku,{search:r,onClick:i=>n(`/${i.resource.resourceType}/${i.resource.id}`),onChange:i=>o(i.definition),hideFilters:!0})})}function jY(){const e=ae(),{resourceType:t,id:n}=ft(),r=e.readHistory(t,n).read();return s.jsx(Oe,{children:s.jsx(Aq,{history:r})})}const CY="_hl7Input_k5xm3_1",EY={hl7Input:CY};function TY(e){return s.jsx("iframe",{frameBorder:"0",src:"https://codeeditor.medplum.com/bot-runner.html",className:e.className,ref:e.iframeRef,"data-testid":e.testId,style:{width:"100%",height:"100%",minHeight:e.minHeight}})}function PY(e){const t=e.defaultValue,n=new URL(`https://codeeditor.medplum.com/${e.language}-editor.html`);return e.module&&n.searchParams.set("module",e.module),s.jsx("iframe",{frameBorder:"0",src:n.toString(),style:{width:"100%",height:"100%",minHeight:e.minHeight},ref:e.iframeRef,"data-testid":e.testId,onLoad:r=>{Md(r.currentTarget,{command:"setValue",value:t}).catch(console.error)}})}const kY=`{
571
+ */function If(){return If=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},If.apply(this,arguments)}function Xg(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(o=>[n,o]):[[n,r]])},[]))}function gQ(e,t){let n=Xg(e);return t&&t.forEach((r,o)=>{n.has(o)||t.getAll(o).forEach(i=>{n.append(o,i)})}),n}const vQ="6";try{window.__reactRouterVersion=vQ}catch{}function yQ(e,t){return _G({basename:void 0,future:If({},void 0,{v7_prependBasename:!0}),history:eG({window:void 0}),hydrationData:xQ(),routes:e,mapRouteProperties:mQ,dataStrategy:void 0,patchRoutesOnNavigation:void 0,window:void 0}).initialize()}function xQ(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=If({},t,{errors:bQ(t.errors)})),t}function bQ(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,o]of t)if(o&&o.__type==="RouteErrorResponse")n[r]=new _f(o.status,o.statusText,o.data,o.internal===!0);else if(o&&o.__type==="Error"){if(o.__subType){let i=window[o.__subType];if(typeof i=="function")try{let a=new i(o.message);a.stack="",n[r]=a}catch{}}if(n[r]==null){let i=new Error(o.message);i.stack="",n[r]=i}}else n[r]=o;return n}const wQ=p.createContext({isTransitioning:!1}),SQ=p.createContext(new Map),jQ="startTransition",kS=ij[jQ],CQ="flushSync",RS=s4[CQ];function EQ(e){kS?kS(e):e()}function Yl(e){RS?RS(e):e()}class TQ{constructor(){this.status="pending",this.promise=new Promise((t,n)=>{this.resolve=r=>{this.status==="pending"&&(this.status="resolved",t(r))},this.reject=r=>{this.status==="pending"&&(this.status="rejected",n(r))}})}}function PQ(e){let{fallbackElement:t,router:n,future:r}=e,[o,i]=p.useState(n.state),[a,l]=p.useState(),[c,u]=p.useState({isTransitioning:!1}),[d,f]=p.useState(),[h,m]=p.useState(),[g,v]=p.useState(),S=p.useRef(new Map),{v7_startTransition:b}=r||{},x=p.useCallback(E=>{b?EQ(E):E()},[b]),y=p.useCallback((E,R)=>{let{deletedFetchers:_,flushSync:N,viewTransitionOpts:O}=R;_.forEach(z=>S.current.delete(z)),E.fetchers.forEach((z,H)=>{z.data!==void 0&&S.current.set(H,z.data)});let F=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!O||F){N?Yl(()=>i(E)):x(()=>i(E));return}if(N){Yl(()=>{h&&(d&&d.resolve(),h.skipTransition()),u({isTransitioning:!0,flushSync:!0,currentLocation:O.currentLocation,nextLocation:O.nextLocation})});let z=n.window.document.startViewTransition(()=>{Yl(()=>i(E))});z.finished.finally(()=>{Yl(()=>{f(void 0),m(void 0),l(void 0),u({isTransitioning:!1})})}),Yl(()=>m(z));return}h?(d&&d.resolve(),h.skipTransition(),v({state:E,currentLocation:O.currentLocation,nextLocation:O.nextLocation})):(l(E),u({isTransitioning:!0,flushSync:!1,currentLocation:O.currentLocation,nextLocation:O.nextLocation}))},[n.window,h,d,S,x]);p.useLayoutEffect(()=>n.subscribe(y),[n,y]),p.useEffect(()=>{c.isTransitioning&&!c.flushSync&&f(new TQ)},[c]),p.useEffect(()=>{if(d&&a&&n.window){let E=a,R=d.promise,_=n.window.document.startViewTransition(async()=>{x(()=>i(E)),await R});_.finished.finally(()=>{f(void 0),m(void 0),l(void 0),u({isTransitioning:!1})}),m(_)}},[x,a,d,n.window]),p.useEffect(()=>{d&&a&&o.location.key===a.location.key&&d.resolve()},[d,h,o.location,a]),p.useEffect(()=>{!c.isTransitioning&&g&&(l(g.state),u({isTransitioning:!0,flushSync:!1,currentLocation:g.currentLocation,nextLocation:g.nextLocation}),v(void 0))},[c.isTransitioning,g]),p.useEffect(()=>{},[]);let w=p.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:E=>n.navigate(E),push:(E,R,_)=>n.navigate(E,{state:R,preventScrollReset:_==null?void 0:_.preventScrollReset}),replace:(E,R,_)=>n.navigate(E,{replace:!0,state:R,preventScrollReset:_==null?void 0:_.preventScrollReset})}),[n]),C=n.basename||"/",j=p.useMemo(()=>({router:n,navigator:w,static:!1,basename:C}),[n,w,C]),T=p.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return p.useEffect(()=>fQ(r,n.future),[r,n.future]),p.createElement(p.Fragment,null,p.createElement(tp.Provider,{value:j},p.createElement(z2.Provider,{value:o},p.createElement(SQ.Provider,{value:S.current},p.createElement(wQ.Provider,{value:c},p.createElement(hQ,{basename:C,location:o.location,navigationType:o.historyAction,navigator:w,future:T},o.initialized||n.future.v7_partialHydration?p.createElement(kQ,{routes:n.routes,future:n.future,state:o}):t))))),null)}const kQ=p.memo(RQ);function RQ(e){let{routes:t,future:n,state:r}=e;return V2(t,void 0,r,n)}var _S;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(_S||(_S={}));var DS;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(DS||(DS={}));function O0(e){let t=p.useRef(Xg(e)),n=p.useRef(!1),r=ri(),o=p.useMemo(()=>gQ(r.search,n.current?null:t.current),[r.search]),i=Gt(),a=p.useCallback((l,c)=>{const u=Xg(typeof l=="function"?l(o):l);n.current=!0,i("?"+u,c)},[i,o]);return[o,a]}const _Q=new Map([["aac","audio/aac"],["abw","application/x-abiword"],["arc","application/x-freearc"],["avif","image/avif"],["avi","video/x-msvideo"],["azw","application/vnd.amazon.ebook"],["bin","application/octet-stream"],["bmp","image/bmp"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["cda","application/x-cdf"],["csh","application/x-csh"],["css","text/css"],["csv","text/csv"],["doc","application/msword"],["docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],["eot","application/vnd.ms-fontobject"],["epub","application/epub+zip"],["gz","application/gzip"],["gif","image/gif"],["heic","image/heic"],["heif","image/heif"],["htm","text/html"],["html","text/html"],["ico","image/vnd.microsoft.icon"],["ics","text/calendar"],["jar","application/java-archive"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["js","text/javascript"],["json","application/json"],["jsonld","application/ld+json"],["mid","audio/midi"],["midi","audio/midi"],["mjs","text/javascript"],["mp3","audio/mpeg"],["mp4","video/mp4"],["mpeg","video/mpeg"],["mpkg","application/vnd.apple.installer+xml"],["odp","application/vnd.oasis.opendocument.presentation"],["ods","application/vnd.oasis.opendocument.spreadsheet"],["odt","application/vnd.oasis.opendocument.text"],["oga","audio/ogg"],["ogv","video/ogg"],["ogx","application/ogg"],["opus","audio/opus"],["otf","font/otf"],["png","image/png"],["pdf","application/pdf"],["php","application/x-httpd-php"],["ppt","application/vnd.ms-powerpoint"],["pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],["rar","application/vnd.rar"],["rtf","application/rtf"],["sh","application/x-sh"],["svg","image/svg+xml"],["swf","application/x-shockwave-flash"],["tar","application/x-tar"],["tif","image/tiff"],["tiff","image/tiff"],["ts","video/mp2t"],["ttf","font/ttf"],["txt","text/plain"],["vsd","application/vnd.visio"],["wav","audio/wav"],["weba","audio/webm"],["webm","video/webm"],["webp","image/webp"],["woff","font/woff"],["woff2","font/woff2"],["xhtml","application/xhtml+xml"],["xls","application/vnd.ms-excel"],["xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],["xml","application/xml"],["xul","application/vnd.mozilla.xul+xml"],["zip","application/zip"],["7z","application/x-7z-compressed"],["mkv","video/x-matroska"],["mov","video/quicktime"],["msg","application/vnd.ms-outlook"]]);function Du(e,t){const n=DQ(e);if(typeof n.path!="string"){const{webkitRelativePath:r}=e;Object.defineProperty(n,"path",{value:typeof t=="string"?t:typeof r=="string"&&r.length>0?r:e.name,writable:!1,configurable:!1,enumerable:!0})}return n}function DQ(e){const{name:t}=e;if(t&&t.lastIndexOf(".")!==-1&&!e.type){const r=t.split(".").pop().toLowerCase(),o=_Q.get(r);o&&Object.defineProperty(e,"type",{value:o,writable:!1,configurable:!1,enumerable:!0})}return e}var Rl=(e,t,n)=>new Promise((r,o)=>{var i=c=>{try{l(n.next(c))}catch(u){o(u)}},a=c=>{try{l(n.throw(c))}catch(u){o(u)}},l=c=>c.done?r(c.value):Promise.resolve(c.value).then(i,a);l((n=n.apply(e,t)).next())});const IQ=[".DS_Store","Thumbs.db"];function AQ(e){return Rl(this,null,function*(){return Af(e)&&NQ(e.dataTransfer)?$Q(e.dataTransfer,e.type):MQ(e)?OQ(e):Array.isArray(e)&&e.every(t=>"getFile"in t&&typeof t.getFile=="function")?LQ(e):[]})}function NQ(e){return Af(e)}function MQ(e){return Af(e)&&Af(e.target)}function Af(e){return typeof e=="object"&&e!==null}function OQ(e){return Jg(e.target.files).map(t=>Du(t))}function LQ(e){return Rl(this,null,function*(){return(yield Promise.all(e.map(n=>n.getFile()))).map(n=>Du(n))})}function $Q(e,t){return Rl(this,null,function*(){if(e.items){const n=Jg(e.items).filter(o=>o.kind==="file");if(t!=="drop")return n;const r=yield Promise.all(n.map(FQ));return IS(q2(r))}return IS(Jg(e.files).map(n=>Du(n)))})}function IS(e){return e.filter(t=>IQ.indexOf(t.name)===-1)}function Jg(e){if(e===null)return[];const t=[];for(let n=0;n<e.length;n++){const r=e[n];t.push(r)}return t}function FQ(e){if(typeof e.webkitGetAsEntry!="function")return AS(e);const t=e.webkitGetAsEntry();return t&&t.isDirectory?G2(t):AS(e)}function q2(e){return e.reduce((t,n)=>[...t,...Array.isArray(n)?q2(n):[n]],[])}function AS(e){const t=e.getAsFile();if(!t)return Promise.reject(`${e} is not a File`);const n=Du(t);return Promise.resolve(n)}function zQ(e){return Rl(this,null,function*(){return e.isDirectory?G2(e):UQ(e)})}function G2(e){const t=e.createReader();return new Promise((n,r)=>{const o=[];function i(){t.readEntries(a=>Rl(this,null,function*(){if(a.length){const l=Promise.all(a.map(zQ));o.push(l),i()}else try{const l=yield Promise.all(o);n(l)}catch(l){r(l)}}),a=>{r(a)})}i()})}function UQ(e){return Rl(this,null,function*(){return new Promise((t,n)=>{e.file(r=>{const o=Du(r,e.fullPath);t(o)},r=>{n(r)})})})}function BQ(e,t){if(e&&t){const n=Array.isArray(t)?t:t.split(","),r=e.name||"",o=(e.type||"").toLowerCase(),i=o.replace(/\/.*$/,"");return n.some(a=>{const l=a.trim().toLowerCase();return l.charAt(0)==="."?r.toLowerCase().endsWith(l):l.endsWith("/*")?i===l.replace(/\/.*$/,""):o===l})}return!0}var VQ=Object.defineProperty,WQ=Object.defineProperties,HQ=Object.getOwnPropertyDescriptors,NS=Object.getOwnPropertySymbols,qQ=Object.prototype.hasOwnProperty,GQ=Object.prototype.propertyIsEnumerable,MS=(e,t,n)=>t in e?VQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,QQ=(e,t)=>{for(var n in t||(t={}))qQ.call(t,n)&&MS(e,n,t[n]);if(NS)for(var n of NS(t))GQ.call(t,n)&&MS(e,n,t[n]);return e},KQ=(e,t)=>WQ(e,HQ(t));const YQ="file-invalid-type",XQ="file-too-large",JQ="file-too-small",ZQ="too-many-files",eK=e=>{e=Array.isArray(e)&&e.length===1?e[0]:e;const t=Array.isArray(e)?`one of ${e.join(", ")}`:e;return{code:YQ,message:`File type must be ${t}`}},OS=e=>({code:XQ,message:`File is larger than ${e} ${e===1?"byte":"bytes"}`}),LS=e=>({code:JQ,message:`File is smaller than ${e} ${e===1?"byte":"bytes"}`}),tK={code:ZQ,message:"Too many files"};function Q2(e,t){const n=e.type==="application/x-moz-file"||BQ(e,t);return[n,n?null:eK(t)]}function K2(e,t,n){if(ls(e.size))if(ls(t)&&ls(n)){if(e.size>n)return[!1,OS(n)];if(e.size<t)return[!1,LS(t)]}else{if(ls(t)&&e.size<t)return[!1,LS(t)];if(ls(n)&&e.size>n)return[!1,OS(n)]}return[!0,null]}function ls(e){return e!=null}function nK({files:e,accept:t,minSize:n,maxSize:r,multiple:o,maxFiles:i,validator:a}){return!o&&e.length>1||o&&i>=1&&e.length>i?!1:e.every(l=>{const[c]=Q2(l,t),[u]=K2(l,n,r),d=a?a(l):null;return c&&u&&!d})}function Nf(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function hd(e){return e.dataTransfer?Array.prototype.some.call(e.dataTransfer.types,t=>t==="Files"||t==="application/x-moz-file"):!!e.target&&!!e.target.files}function $S(e){e.preventDefault()}function rK(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function oK(e){return e.indexOf("Edge/")!==-1}function iK(e=window.navigator.userAgent){return rK(e)||oK(e)}function oo(...e){return(t,...n)=>e.some(r=>(!Nf(t)&&r&&r(t,...n),Nf(t)))}function sK(){return"showOpenFilePicker"in window}function aK(e){return ls(e)?[{description:"Files",accept:Object.entries(e).filter(([n,r])=>{let o=!0;return Y2(n)||(console.warn(`Skipped "${n}" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.`),o=!1),(!Array.isArray(r)||!r.every(X2))&&(console.warn(`Skipped "${n}" because an invalid file extension was provided.`),o=!1),o}).reduce((n,[r,o])=>KQ(QQ({},n),{[r]:o}),{})}]:e}function lK(e){if(ls(e))return Object.entries(e).reduce((t,[n,r])=>[...t,n,...r],[]).filter(t=>Y2(t)||X2(t)).join(",")}function cK(e){return e instanceof DOMException&&(e.name==="AbortError"||e.code===e.ABORT_ERR)}function uK(e){return e instanceof DOMException&&(e.name==="SecurityError"||e.code===e.SECURITY_ERR)}function Y2(e){return e==="audio/*"||e==="video/*"||e==="image/*"||e==="text/*"||/\w+\/[-+.\w]+/g.test(e)}function X2(e){return/^.*\.[\w]+$/.test(e)}var dK=Object.defineProperty,fK=Object.defineProperties,hK=Object.getOwnPropertyDescriptors,Mf=Object.getOwnPropertySymbols,J2=Object.prototype.hasOwnProperty,Z2=Object.prototype.propertyIsEnumerable,FS=(e,t,n)=>t in e?dK(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,An=(e,t)=>{for(var n in t||(t={}))J2.call(t,n)&&FS(e,n,t[n]);if(Mf)for(var n of Mf(t))Z2.call(t,n)&&FS(e,n,t[n]);return e},hi=(e,t)=>fK(e,hK(t)),Of=(e,t)=>{var n={};for(var r in e)J2.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Mf)for(var r of Mf(e))t.indexOf(r)<0&&Z2.call(e,r)&&(n[r]=e[r]);return n};const L0=p.forwardRef((e,t)=>{var n=e,{children:r}=n,o=Of(n,["children"]);const i=t_(o),{open:a}=i,l=Of(i,["open"]);return p.useImperativeHandle(t,()=>({open:a}),[a]),Jt.createElement(p.Fragment,null,r(hi(An({},l),{open:a})))});L0.displayName="Dropzone";const e_={disabled:!1,getFilesFromEvent:AQ,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!0,autoFocus:!1};L0.defaultProps=e_;L0.propTypes={children:vt.func,accept:vt.objectOf(vt.arrayOf(vt.string)),multiple:vt.bool,preventDropOnDocument:vt.bool,noClick:vt.bool,noKeyboard:vt.bool,noDrag:vt.bool,noDragEventsBubbling:vt.bool,minSize:vt.number,maxSize:vt.number,maxFiles:vt.number,disabled:vt.bool,getFilesFromEvent:vt.func,onFileDialogCancel:vt.func,onFileDialogOpen:vt.func,useFsAccessApi:vt.bool,autoFocus:vt.bool,onDragEnter:vt.func,onDragLeave:vt.func,onDragOver:vt.func,onDrop:vt.func,onDropAccepted:vt.func,onDropRejected:vt.func,onError:vt.func,validator:vt.func};const Zg={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function t_(e={}){const{accept:t,disabled:n,getFilesFromEvent:r,maxSize:o,minSize:i,multiple:a,maxFiles:l,onDragEnter:c,onDragLeave:u,onDragOver:d,onDrop:f,onDropAccepted:h,onDropRejected:m,onFileDialogCancel:g,onFileDialogOpen:v,useFsAccessApi:S,autoFocus:b,preventDropOnDocument:x,noClick:y,noKeyboard:w,noDrag:C,noDragEventsBubbling:j,onError:T,validator:E}=An(An({},e_),e),R=p.useMemo(()=>lK(t),[t]),_=p.useMemo(()=>aK(t),[t]),N=p.useMemo(()=>typeof v=="function"?v:zS,[v]),O=p.useMemo(()=>typeof g=="function"?g:zS,[g]),F=p.useRef(null),z=p.useRef(null),[H,D]=p.useReducer(pK,Zg),{isFocused:k,isFileDialogActive:P}=H,I=p.useRef(typeof window<"u"&&window.isSecureContext&&S&&sK()),L=()=>{!I.current&&P&&setTimeout(()=>{if(z.current){const{files:J}=z.current;J.length||(D({type:"closeDialog"}),O())}},300)};p.useEffect(()=>(window.addEventListener("focus",L,!1),()=>{window.removeEventListener("focus",L,!1)}),[z,P,O,I]);const $=p.useRef([]),Q=J=>{F.current&&F.current.contains(J.target)||(J.preventDefault(),$.current=[])};p.useEffect(()=>(x&&(document.addEventListener("dragover",$S,!1),document.addEventListener("drop",Q,!1)),()=>{x&&(document.removeEventListener("dragover",$S),document.removeEventListener("drop",Q))}),[F,x]),p.useEffect(()=>(!n&&b&&F.current&&F.current.focus(),()=>{}),[F,b,n]);const ue=p.useCallback(J=>{T?T(J):console.error(J)},[T]),Re=p.useCallback(J=>{J.preventDefault(),J.persist(),ne(J),$.current=[...$.current,J.target],hd(J)&&Promise.resolve(r(J)).then(se=>{if(Nf(J)&&!j)return;const G=se.length,Se=G>0&&nK({files:se,accept:R,minSize:i,maxSize:o,multiple:a,maxFiles:l,validator:E}),He=G>0&&!Se;D({isDragAccept:Se,isDragReject:He,isDragActive:!0,type:"setDraggedFiles"}),c&&c(J)}).catch(se=>ue(se))},[r,c,ue,j,R,i,o,a,l,E]),me=p.useCallback(J=>{J.preventDefault(),J.persist(),ne(J);const se=hd(J);if(se&&J.dataTransfer)try{J.dataTransfer.dropEffect="copy"}catch{}return se&&d&&d(J),!1},[d,j]),ge=p.useCallback(J=>{J.preventDefault(),J.persist(),ne(J);const se=$.current.filter(Se=>F.current&&F.current.contains(Se)),G=se.indexOf(J.target);G!==-1&&se.splice(G,1),$.current=se,!(se.length>0)&&(D({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),hd(J)&&u&&u(J))},[F,u,j]),De=p.useCallback((J,se)=>{const G=[],Se=[];J.forEach(He=>{const[kt,lt]=Q2(He,R),[Nt,rn]=K2(He,i,o),un=E?E(He):null;if(kt&&Nt&&!un)G.push(He);else{let eo=[lt,rn];un&&(eo=eo.concat(un)),Se.push({file:He,errors:eo.filter(Bn=>Bn)})}}),(!a&&G.length>1||a&&l>=1&&G.length>l)&&(G.forEach(He=>{Se.push({file:He,errors:[tK]})}),G.splice(0)),D({acceptedFiles:G,fileRejections:Se,type:"setFiles"}),f&&f(G,Se,se),Se.length>0&&m&&m(Se,se),G.length>0&&h&&h(G,se)},[D,a,R,i,o,l,f,h,m,E]),le=p.useCallback(J=>{J.preventDefault(),J.persist(),ne(J),$.current=[],hd(J)&&Promise.resolve(r(J)).then(se=>{Nf(J)&&!j||De(se,J)}).catch(se=>ue(se)),D({type:"reset"})},[r,De,ue,j]),Ne=p.useCallback(()=>{if(I.current){D({type:"openDialog"}),N();const J={multiple:a,types:_};window.showOpenFilePicker(J).then(se=>r(se)).then(se=>{De(se,null),D({type:"closeDialog"})}).catch(se=>{cK(se)?(O(se),D({type:"closeDialog"})):uK(se)?(I.current=!1,z.current?(z.current.value=null,z.current.click()):ue(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no <input> was provided."))):ue(se)});return}z.current&&(D({type:"openDialog"}),N(),z.current.value=null,z.current.click())},[D,N,O,S,De,ue,_,a]),it=p.useCallback(J=>{!F.current||!F.current.isEqualNode(J.target)||(J.key===" "||J.key==="Enter"||J.keyCode===32||J.keyCode===13)&&(J.preventDefault(),Ne())},[F,Ne]),Ue=p.useCallback(()=>{D({type:"focus"})},[]),Je=p.useCallback(()=>{D({type:"blur"})},[]),st=p.useCallback(()=>{y||(iK()?setTimeout(Ne,0):Ne())},[y,Ne]),Be=J=>n?null:J,Ze=J=>w?null:Be(J),at=J=>C?null:Be(J),ne=J=>{j&&J.stopPropagation()},X=p.useMemo(()=>(J={})=>{var se=J,{refKey:G="ref",role:Se,onKeyDown:He,onFocus:kt,onBlur:lt,onClick:Nt,onDragEnter:rn,onDragOver:un,onDragLeave:eo,onDrop:Bn}=se,Js=Of(se,["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"]);return An(An({onKeyDown:Ze(oo(He,it)),onFocus:Ze(oo(kt,Ue)),onBlur:Ze(oo(lt,Je)),onClick:Be(oo(Nt,st)),onDragEnter:at(oo(rn,Re)),onDragOver:at(oo(un,me)),onDragLeave:at(oo(eo,ge)),onDrop:at(oo(Bn,le)),role:typeof Se=="string"&&Se!==""?Se:"presentation",[G]:F},!n&&!w?{tabIndex:0}:{}),Js)},[F,it,Ue,Je,st,Re,me,ge,le,w,C,n]),ce=p.useCallback(J=>{J.stopPropagation()},[]),ke=p.useMemo(()=>(J={})=>{var se=J,{refKey:G="ref",onChange:Se,onClick:He}=se,kt=Of(se,["refKey","onChange","onClick"]);const lt={accept:R,multiple:a,type:"file",style:{display:"none"},onChange:Be(oo(Se,le)),onClick:Be(oo(He,ce)),tabIndex:-1,[G]:z};return An(An({},lt),kt)},[z,t,a,le,n]);return hi(An({},H),{isFocused:k&&!n,getRootProps:X,getInputProps:ke,rootRef:F,inputRef:z,open:Be(Ne)})}function pK(e,t){switch(t.type){case"focus":return hi(An({},e),{isFocused:!0});case"blur":return hi(An({},e),{isFocused:!1});case"openDialog":return hi(An({},Zg),{isFileDialogActive:!0});case"closeDialog":return hi(An({},e),{isFileDialogActive:!1});case"setDraggedFiles":return hi(An({},e),{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return hi(An({},e),{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return An({},Zg);default:return e}}function zS(){}const[mK,gK]=Fn("Dropzone component was not found in tree");function $0(e){const t=n=>{const{children:r,...o}=W(`Dropzone${Z0(e)}`,{},n),i=gK(),a=qo(r)?r:s.jsx("span",{children:r});return i[e]?p.cloneElement(a,o):null};return t.displayName=`@mantine/dropzone/${Z0(e)}`,t}const vK=$0("accept"),yK=$0("reject"),xK=$0("idle");var Kc={root:"m_d46a4834",inner:"m_b85f7144",fullScreen:"m_96f6e9ad",dropzone:"m_7946116d"};const bK={loading:!1,multiple:!0,maxSize:1/0,autoFocus:!1,activateOnClick:!0,activateOnDrag:!0,dragEventsBubbling:!0,activateOnKeyboard:!0,useFsAccessApi:!0,variant:"light",rejectColor:"red"},wK=(e,{radius:t,variant:n,acceptColor:r,rejectColor:o})=>{const i=e.variantColorResolver({color:r||e.primaryColor,theme:e,variant:n}),a=e.variantColorResolver({color:o||"red",theme:e,variant:n});return{root:{"--dropzone-radius":dt(t),"--dropzone-accept-color":i.color,"--dropzone-accept-bg":i.background,"--dropzone-reject-color":a.color,"--dropzone-reject-bg":a.background}}},Hi=Y((e,t)=>{const n=W("Dropzone",bK,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,radius:u,disabled:d,loading:f,multiple:h,maxSize:m,accept:g,children:v,onDropAny:S,onDrop:b,onReject:x,openRef:y,name:w,maxFiles:C,autoFocus:j,activateOnClick:T,activateOnDrag:E,dragEventsBubbling:R,activateOnKeyboard:_,onDragEnter:N,onDragLeave:O,onDragOver:F,onFileDialogCancel:z,onFileDialogOpen:H,preventDropOnDocument:D,useFsAccessApi:k,getFilesFromEvent:P,validator:I,rejectColor:L,acceptColor:$,enablePointerEvents:Q,loaderProps:ue,inputProps:Re,mod:me,...ge}=n,De=de({name:"Dropzone",classes:Kc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:wK}),{getRootProps:le,getInputProps:Ne,isDragAccept:it,isDragReject:Ue,open:Je}=t_({onDrop:S,onDropAccepted:b,onDropRejected:x,disabled:d||f,accept:Array.isArray(g)?g.reduce((Be,Ze)=>({...Be,[Ze]:[]}),{}):g,multiple:h,maxSize:m,maxFiles:C,autoFocus:j,noClick:!T,noDrag:!E,noDragEventsBubbling:!R,noKeyboard:!_,onDragEnter:N,onDragLeave:O,onDragOver:F,onFileDialogCancel:z,onFileDialogOpen:H,preventDropOnDocument:D,useFsAccessApi:k,validator:I,...P?{getFilesFromEvent:P}:null});Uf(y,Je);const st=!it&&!Ue;return s.jsx(mK,{value:{accept:it,reject:Ue,idle:st},children:s.jsxs(q,{...le(),...De("root",{focusable:!0}),...ge,mod:[{accept:it,reject:Ue,idle:st,disabled:d,loading:f,"activate-on-click":T},me],children:[s.jsx(ix,{visible:f,overlayProps:{radius:u},unstyled:l,loaderProps:ue}),s.jsx("input",{...Ne(Re),name:w}),s.jsx("div",{...De("inner"),ref:t,"data-enable-pointer-events":Q||void 0,children:v})]})})});Hi.classes=Kc;Hi.displayName="@mantine/dropzone/Dropzone";Hi.Accept=vK;Hi.Idle=xK;Hi.Reject=yK;const SK={loading:!1,maxSize:1/0,activateOnClick:!1,activateOnDrag:!0,dragEventsBubbling:!0,activateOnKeyboard:!0,active:!0,zIndex:Yr("max"),withinPortal:!0},F0=Y((e,t)=>{const n=W("DropzoneFullScreen",SK,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,active:u,onDrop:d,onReject:f,zIndex:h,withinPortal:m,portalProps:g,...v}=n,S=de({name:"DropzoneFullScreen",classes:Kc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,rootSelector:"fullScreen"}),{resolvedClassNames:b,resolvedStyles:x}=Xc({classNames:r,styles:a,props:n}),[y,w]=p.useState(0),[C,{open:j,close:T}]=Bf(!1),E=_=>{var N;(N=_.dataTransfer)!=null&&N.types.includes("Files")&&(w(O=>O+1),j())},R=()=>{w(_=>_-1)};return p.useEffect(()=>{y===0&&T()},[y]),p.useEffect(()=>{if(u)return document.addEventListener("dragenter",E,!1),document.addEventListener("dragleave",R,!1),()=>{document.removeEventListener("dragenter",E,!1),document.removeEventListener("dragleave",R,!1)}},[u]),s.jsx(zs,{...g,withinPortal:m,children:s.jsx(q,{...S("fullScreen",{style:{opacity:C?1:0,pointerEvents:C?"all":"none",zIndex:h}}),ref:t,children:s.jsx(Hi,{...v,classNames:b,styles:x,unstyled:l,className:Kc.dropzone,onDrop:_=>{d==null||d(_),T(),w(0)},onReject:_=>{f==null||f(_),T(),w(0)}})})})});F0.classes=Kc;F0.displayName="@mantine/dropzone/DropzoneFullScreen";Hi.FullScreen=F0;const pd=Hi,jK='{"resourceType": "Bundle"}';function pm({id:e,title:t,message:n,color:r,icon:o,withCloseButton:i=!1,method:a="show",loading:l}){mo[a]({id:e,loading:l,title:t,message:n,color:r,icon:o,withCloseButton:i,autoClose:!1})}function CK(){const e=At(),t=ae(),[n,r]=p.useState({}),o=p.useCallback(async(l,c)=>{const u="batch-upload";pm({id:u,title:"Batch Upload in Progress",message:"Your batch data is being uploaded. This may take a moment...",method:"show",loading:!0});try{r({});let d=JSON.parse(l);d.type!=="batch"&&d.type!=="transaction"&&(d=Gk(d));const f=await t.executeBatch(d);r(h=>({...h,[c]:f})),pm({id:u,title:"Batch Upload Successful",message:"Your batch data was successfully uploaded.",color:"green",method:"update",icon:s.jsx(Ks,{size:"1rem"}),withCloseButton:!0})}catch(d){pm({id:u,title:"Batch Upload Failed",color:"red",message:Ie(d),method:"update",icon:s.jsx(Cf,{size:"1rem"}),withCloseButton:!0})}},[t]),i=p.useCallback(async l=>{for(const c of l){const u=new FileReader;u.onload=d=>{var f;return o((f=d.target)==null?void 0:f.result,c.name)},u.readAsText(c)}},[o]),a=p.useCallback(async l=>{await o(l.input,"JSON Data")},[o]);return s.jsxs(Oe,{children:[s.jsx(be,{children:"Batch Create"}),s.jsxs("p",{children:["Use this page to create, read, or update multiple resources. For more details, see ",s.jsx("a",{href:"https://www.hl7.org/fhir/http.html#transaction",children:"FHIR Batch and Transaction"}),"."]}),Object.keys(n).length===0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{children:"Input"}),s.jsxs(et,{defaultValue:"upload",children:[s.jsxs(et.List,{children:[s.jsx(et.Tab,{value:"upload",children:"File Upload"}),s.jsx(et.Tab,{value:"json",children:"JSON"})]}),s.jsx(et.Panel,{value:"upload",pt:"xs",children:s.jsx(pd,{onDrop:i,accept:["application/json"],children:s.jsxs(ee,{justify:"center",gap:"xl",style:{minHeight:220,pointerEvents:"none"},children:[s.jsx(pd.Accept,{children:s.jsx(zw,{size:50,stroke:1.5,color:e.colors[e.primaryColor][5]})}),s.jsx(pd.Reject,{children:s.jsx(Cf,{size:50,stroke:1.5,color:e.colors.red[5]})}),s.jsx(pd.Idle,{children:s.jsx(zw,{size:50,stroke:1.5})}),s.jsxs("div",{children:[s.jsx(he,{size:"xl",inline:!0,children:"Drag files here or click to select files"}),s.jsx(he,{size:"sm",color:"dimmed",inline:!0,mt:7,children:"Attach as many files as you like"})]})]})})}),s.jsx(et.Panel,{value:"json",pt:"xs",children:s.jsxs(Qe,{onSubmit:a,children:[s.jsx(yl,{"data-testid":"batch-input",name:"input",autosize:!0,minRows:20,defaultValue:jK,deserialize:JSON.parse}),s.jsx(ee,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ie,{type:"submit",children:"Submit"})})]})})]})]}),Object.keys(n).length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{children:"Output"}),s.jsxs(et,{defaultValue:Object.keys(n)[0],children:[s.jsx(et.List,{children:Object.keys(n).map(l=>s.jsx(et.Tab,{value:l,children:l},l))}),Object.keys(n).map(l=>s.jsx(et.Panel,{value:l,children:s.jsx("pre",{style:{border:"1px solid #888"},children:JSON.stringify(n[l],void 0,2)})},l))]}),s.jsx(ee,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ie,{onClick:()=>r({}),children:"Start over"})})]})]})}function EK(){const{resourceType:e}=ft(),n=(Object.fromEntries(new URLSearchParams(location.search).entries()).ids||"").split(",").filter(o=>!!o),[r]=ll("Questionnaire",`subject-type=${e}`);return r?r.length===0?s.jsxs(Oe,{children:[s.jsxs(be,{children:["No apps for ",e]}),s.jsx(qe,{to:`/${e}`,children:"Return to search page"})]}):s.jsx(Oe,{children:s.jsx("div",{children:r.map(o=>s.jsxs("div",{children:[s.jsx("h3",{children:s.jsx(qe,{to:`/forms/${o.id}?subject=`+n.map(i=>`${e}/${i}`).join(","),children:o.name})}),s.jsx("p",{children:o.description})]},o.id))})}):s.jsx(Tr,{})}function TK(){const e=ae(),[t,n]=p.useState(),[r,o]=p.useState(!1);return s.jsx(Oe,{width:450,children:s.jsxs(Qe,{onSubmit:i=>{n(void 0),e.post("auth/changepassword",i).then(()=>o(!0)).catch(a=>n(mt(a)))},children:[s.jsxs(vn,{style:{flexDirection:"column"},children:[s.jsx(Zr,{size:32}),s.jsx(be,{children:"Change password"})]}),!r&&s.jsxs(Ae,{gap:"xl",mt:"xl",children:[s.jsx(Wr,{name:"oldPassword",label:"Old password",required:!0,autoFocus:!0,error:Ye(t,"oldPassword")}),s.jsx(Wr,{name:"newPassword",label:"New password",required:!0,error:Ye(t,"newPassword")}),s.jsx(Wr,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Ye(t,"confirmPassword")}),s.jsx(ee,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ie,{type:"submit",children:"Change password"})})]}),r&&s.jsx("div",{"data-testid":"success",children:"Password changed successfully"})]})})}const ev=["Form","JSON","Profiles"],PK=["Profiles"],mm=ev[0].toLowerCase();function kK(){const e=Gt(),t=At(),{resourceType:n}=ft(),[r,o]=p.useState(()=>{const a=window.location.pathname.split("/").pop();return a&&ev.map(l=>l.toLowerCase()).includes(a)?a:mm});function i(a){a||(a=mm),o(a),e(`/${n}/new/${a}`)}return s.jsxs(s.Fragment,{children:[s.jsxs(Xn,{children:[s.jsxs(he,{p:"md",fw:500,children:["New ",n]}),s.jsx(kr,{children:s.jsx(et,{defaultValue:mm,value:r,onChange:i,children:s.jsx(et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:ev.map(a=>s.jsx(et.Tab,{value:a.toLowerCase(),px:"md",children:PK.includes(a)?s.jsxs(ee,{gap:"xs",wrap:"nowrap",children:[a,s.jsx(uu,{color:t.primaryColor,size:"sm",children:"Beta"})]}):a},a))})})})]}),s.jsx(M0,{})]})}function RK(){return s.jsx(Oe,{children:s.jsxs(Ae,{children:[s.jsx(be,{order:1,children:"Unexpected Error"}),s.jsx(he,{children:"We're sorry, something went wrong."}),s.jsxs(he,{children:["Please contact ",s.jsx(Xe,{href:"mailto:support@medplum.com",children:"support"})," for assistance."]})]})})}const _K="_root_1fbwr_1",DK="_entry_1fbwr_8",IK="_key_1fbwr_13",AK="_value_1fbwr_20",ip={root:_K,entry:DK,key:IK,value:AK};function ze(e){return s.jsx(kr,{children:s.jsx("div",{className:ip.root,children:e.children})})}ze.Entry=function(t){return s.jsx("div",{className:ip.entry,children:t.children})};ze.Key=function(t){return s.jsx("div",{className:ip.key,children:t.children})};ze.Value=function(t){return s.jsx("div",{className:ip.value,children:t.children})};function NK(e){if(e.gender==="male")return"blue";if(e.gender==="female")return"pink"}function n_(e){var n,r;const t=St(e.patient);return t?s.jsxs(ze,{children:[s.jsx(Vi,{value:t,size:"lg",color:NK(t)}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Name"}),s.jsx(ze.Value,{children:s.jsx(qe,{to:t,fw:500,children:t.name?s.jsx(s0,{value:t.name[0],options:{use:!1}}):"[blank]"})})]}),t.birthDate&&s.jsxs(s.Fragment,{children:[s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"DoB"}),s.jsx(ze.Value,{children:t.birthDate})]}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Age"}),s.jsx(ze.Value,{children:P6(t.birthDate)})]})]}),t.gender&&s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Gender"}),s.jsx(ze.Value,{children:t.gender})]}),t.address&&s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"State"}),s.jsx(ze.Value,{children:(n=t.address[0])==null?void 0:n.state})]}),(r=t.identifier)==null?void 0:r.map(o=>s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:o==null?void 0:o.system}),s.jsx(ze.Value,{children:o==null?void 0:o.value})]},`${o==null?void 0:o.system}-${o==null?void 0:o.value}`))]}):null}function r_(e){const t=St(e.resource);if(!t)return null;const n=[{key:"Type",value:s.jsx(qe,{to:`/${t.resourceType}`,children:t.resourceType})}];function r(a,l){a&&l&&n.push({key:a,value:l})}function o(a){a&&r(a.system,a.value)}function i(a,l){Array.isArray(l)?l.forEach(c=>i(a,c)):typeof l=="string"?r(a,l):l&&(Array.isArray(l.coding)?r(a,l.coding.map(c=>c.display||c.code).join(", ")):r(a,l.text))}if("name"in t){const a=Wo(t);a!==ct(t)&&r("Name",a)}return"category"in t&&i("Category",t.category),t.resourceType!=="Bot"&&"code"in t&&i("Code",t.code),"identifier"in t&&(Array.isArray(t.identifier)?t.identifier.forEach(o):o(t.identifier)),n.length===1&&n.push({key:"ID",value:t.id}),s.jsx(ze,{children:n.map(a=>s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:a.key}),s.jsx(ze.Value,{children:a.value})]},`${a.key}-${a.value}`))})}function z0(e){if(e.resourceType==="Patient")return e;if(e.resourceType==="DiagnosticReport"||e.resourceType==="Encounter"||e.resourceType==="Observation"||e.resourceType==="ServiceRequest")return e.subject}function MK(e){var t;if(e.resourceType==="Specimen")return e;if(e.resourceType==="Observation")return e.specimen;if(e.resourceType==="DiagnosticReport"||e.resourceType==="ServiceRequest")return(t=e.specimen)==null?void 0:t[0]}function Md(e,t){return new Promise((n,r)=>{var i;const o=new MessageChannel;o.port1.onmessage=({data:a})=>{o.port1.close(),a.error?r(a.error):n(a.result)},(i=e.contentWindow)==null||i.postMessage(t,"https://codeeditor.medplum.com",[o.port2])})}function qi(e){var t;return sl((t=e.getActiveLogin())==null?void 0:t.project)}function OK(e,t){const n=new Blob([e],{type:sn.JSON}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r;const i=new Date().toISOString().replace(/\D/g,"");o.download=`${i}.json`,document.body.appendChild(o),o.click(),URL.revokeObjectURL(r)}function LK(){const{id:e}=ft(),t=ri(),r=Object.fromEntries(new URLSearchParams(t.search).entries()).subject,o=ae(),[i,a]=p.useState(!0),[l,c]=p.useState(),[u,d]=p.useState(),[f,h]=p.useState(),[m,g]=p.useState(),[v,S]=p.useState();if(p.useEffect(()=>{const y={resourceType:"Bundle",type:"batch",entry:[{request:{method:"GET",url:`Questionnaire/${e}`}}]};if(r){const w=r.split(",").filter(C=>!!C);w.length===1&&y.entry.push({request:{method:"GET",url:w[0]}}),d(w)}o.executeBatch(y).then(w=>{var C,j,T,E,R,_,N,O;((T=(j=(C=w.entry)==null?void 0:C[0])==null?void 0:j.response)==null?void 0:T.status)!=="200"?g((_=(R=(E=w.entry)==null?void 0:E[0])==null?void 0:R.response)==null?void 0:_.outcome):(c((N=w.entry[0])==null?void 0:N.resource),h((O=w.entry[1])==null?void 0:O.resource)),a(!1)}).catch(w=>{g(w),a(!1)})},[o,e,r]),m)return s.jsx(Oe,{children:s.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)})});if(v)return s.jsxs(Oe,{children:[s.jsx(be,{children:l==null?void 0:l.title}),s.jsx("p",{children:"Your response has been recorded."}),s.jsxs("ul",{children:[v.length===1&&s.jsx("li",{children:s.jsx(qe,{to:v[0],children:"Review your answers"})}),v.length>1&&s.jsxs("li",{children:["Review your answers:",s.jsx("ul",{children:v.map(y=>s.jsx("li",{children:s.jsx(qe,{to:y,children:ct(y)})},y.id))})]}),f&&s.jsx("li",{children:s.jsxs(qe,{to:f,children:["Back to ",Wo(f)]})}),s.jsx("li",{children:s.jsx(qe,{to:"/",children:"Go back home"})})]})]});if(i||!l)return s.jsx(Tr,{});const b=f&&z0(f);return s.jsxs(s.Fragment,{children:[s.jsxs(Xn,{shadow:"xs",radius:0,children:[b&&s.jsx(n_,{patient:b}),f&&f.resourceType!=="Patient"&&s.jsx(r_,{resource:f}),s.jsx(q,{px:"xl",py:"md",children:s.jsxs(he,{children:[Wo(l),u&&u.length>1&&s.jsxs(s.Fragment,{children:[" (for ",u.length," resources)"]})]})})]}),s.jsx(Oe,{children:s.jsx(y2,{questionnaire:l,subject:f&&Tt(f),onSubmit:x})})]});async function x(y){const w=[];if(!u||u.length===0)w.push(await o.createResource(y));else for(const C of u)w.push(await o.createResource({...y,subject:{reference:C}}));S(w)}}const $K="_paper_unw9o_1",FK={paper:$K},zK={Bot:"/admin/bots/new",ClientApplication:"/admin/clients/new"};function o_(e,t){const n=e.resourceType||UK(t),r=e.fields??BK(n),o=e.filters??(e.resourceType?void 0:VK(n)),i=e.sortRules??WK(n),a=e.offset??0,l=e.count??Vh;return{...e,resourceType:n,fields:r,filters:o,sortRules:i,offset:a,count:l}}function UK(e){var t,n;return localStorage.getItem("defaultResourceType")??((n=(t=e==null?void 0:e.option)==null?void 0:t.find(r=>r.id==="defaultResourceType"))==null?void 0:n.valueString)??"Patient"}function BK(e){const t=U0(e);if(t!=null&&t.fields)return t.fields;const n=["id","_lastUpdated"];switch(e){case"Patient":n.push("name","birthDate","gender");break;case"AccessPolicy":case"Bot":case"ClientApplication":case"Practitioner":case"Project":case"Organization":case"Questionnaire":case"UserConfiguration":n.push("name");break;case"CodeSystem":case"ValueSet":n.push("name","title","status");break;case"Condition":n.push("subject","code","clinicalStatus");break;case"Device":n.push("manufacturer","deviceName","patient");break;case"DeviceDefinition":n.push("manufacturer[x]","deviceName");break;case"DeviceRequest":n.push("code[x]","subject");break;case"DiagnosticReport":case"Observation":n.push("subject","code","status");break;case"Encounter":n.push("subject");break;case"ServiceRequest":n.push("subject","code","status","orderDetail");break;case"Subscription":n.push("criteria");break;case"User":n.push("email");break}return n}function VK(e){var t;return(t=U0(e))==null?void 0:t.filters}function WK(e){const t=U0(e);return t!=null&&t.sortRules?t.sortRules:[{code:"_lastUpdated",descending:!0}]}function U0(e){const t=localStorage.getItem(e+"-defaultSearch");return t?JSON.parse(t):void 0}function HK(e){localStorage.setItem("defaultResourceType",e.resourceType),localStorage.setItem(e.resourceType+"-defaultSearch",JSON.stringify(e))}async function qK(e,t){const n={resourceType:e.resourceType,count:1e3,offset:0,filters:e.filters},r=o_(n,t.getUserConfiguration()),o=await t.search(r.resourceType,Aa({...r,total:"accurate",fields:void 0}));return Gk(o)}function US(){const e=ae(),t=Gt(),n=ri(),[r,o]=p.useState();return p.useEffect(()=>{const i=Bk(n.pathname+n.search),a=o_(i,e.getUserConfiguration());n.pathname===`/${a.resourceType}`&&n.search===Aa(a)?(HK(a),o(a)):t(`/${a.resourceType}${Aa(a)}`)},[e,t,n]),!(r!=null&&r.resourceType)||!r.fields||r.fields.length===0?s.jsx(Tr,{}):s.jsx(Xn,{shadow:"xs",m:"md",p:"xs",className:FK.paper,children:s.jsx(ku,{checkboxesEnabled:!0,search:r,onClick:i=>t(`/${i.resource.resourceType}/${i.resource.id}`),onAuxClick:i=>window.open(`/${i.resource.resourceType}/${i.resource.id}`,"_blank"),onChange:i=>{t(`/${r.resourceType}${Aa(i.definition)}`)},onNew:()=>{t(zK[r.resourceType]??`/${r.resourceType}/new`)},onExportCsv:()=>{const i=e.fhirUrl(r.resourceType,"$csv")+Aa(r);e.download(i).then(a=>{window.open(window.URL.createObjectURL(a),"_blank")}).catch(a=>pe({color:"red",message:Ie(a),autoClose:!1}))},onExportTransactionBundle:async()=>{qK(r,e).then(i=>OK(JSON.stringify(i,void 0,2))).catch(i=>pe({color:"red",message:Ie(i),autoClose:!1}))},onDelete:i=>{window.confirm("Are you sure you want to delete these resources?")&&(e.invalidateSearches(r.resourceType),e.executeBatch({resourceType:"Bundle",type:"batch",entry:i.map(a=>({request:{method:"DELETE",url:`${r.resourceType}/${a}`}}))}).then(()=>o({...r})).catch(a=>pe({color:"red",message:Ie(a),autoClose:!1})))},onBulk:i=>{t(`/bulk/${r.resourceType}?ids=${i.join(",")}`)}})})}function GK(){const e=ae(),[t,n]=p.useState(),[r,o]=p.useState(void 0);p.useEffect(()=>{e.get("auth/mfa/status").then(l=>{n(l.enrollQrCode),o(l.enrolled)}).catch(l=>pe({color:"red",message:Ie(l),autoClose:!1}))},[e]);const i=p.useCallback(l=>{e.post("auth/mfa/enroll",l).then(()=>{o(!0),pe({color:"green",message:"Success"})}).catch(c=>pe({color:"red",message:Ie(c),autoClose:!1}))},[e]),a=p.useCallback(()=>{e.post("auth/mfa/disable",{}).catch(console.log)},[e]);return r===void 0?null:r?s.jsx(Oe,{children:s.jsxs(ee,{children:[s.jsx(be,{children:"MFA is enabled"}),s.jsx(ie,{onClick:a,children:"Disable MFA"})]})}):s.jsx(Oe,{width:400,children:s.jsxs(Qe,{onSubmit:i,children:[s.jsx(be,{children:"Multi Factor Auth Setup"}),s.jsx(vn,{children:s.jsx("img",{src:t})}),s.jsx(ye,{name:"token",label:"Code"}),s.jsx(ee,{justify:"flex-end",mt:"xl",children:s.jsx(ie,{type:"submit",children:"Enroll"})})]})})}const gm={BASE_URL:"/",DEV:!1,GOOGLE_CLIENT_ID:"__GOOGLE_CLIENT_ID__",MEDPLUM_BASE_URL:"__MEDPLUM_BASE_URL__",MEDPLUM_CLIENT_ID:"__MEDPLUM_CLIENT_ID__",MEDPLUM_REGISTER_ENABLED:"__MEDPLUM_REGISTER_ENABLED__",MEDPLUM_VERSION:"3.2.22-a936b292a",MODE:"production",PROD:!0,RECAPTCHA_SITE_KEY:"__RECAPTCHA_SITE_KEY__",SSR:!1},tv={baseUrl:"__MEDPLUM_BASE_URL__",clientId:"__MEDPLUM_CLIENT_ID__",googleClientId:"__GOOGLE_CLIENT_ID__",recaptchaSiteKey:"__RECAPTCHA_SITE_KEY__",registerEnabled:"__MEDPLUM_REGISTER_ENABLED__",awsTextractEnabled:gm==null?void 0:gm.MEDPLUM_AWS_TEXTRACT_ENABLED};function Iu(){return tv}function i_(){return s_("registerEnabled")}function QK(){return s_("awsTextractEnabled")}function s_(e){try{return tv[e]!==!1&&tv[e]!=="false"}catch{return!0}}function KK(){const e=Gt(),[t]=O0(),n=t.get("client_id");if(!n)return null;const r=t.get("scope")||"openid";function o(i){const a=new URL(t.get("redirect_uri"));for(const l of["scope","state","nonce"])t.has(l)&&a.searchParams.set(l,t.get(l));a.searchParams.set("code",i),window.location.assign(a.toString())}return s.jsxs(P2,{onCode:o,onForgotPassword:()=>e("/resetpassword"),onRegister:()=>e("/register"),googleClientId:Iu().googleClientId,clientId:n||void 0,redirectUri:t.get("redirect_uri")||void 0,scope:r,nonce:t.get("nonce")||void 0,launch:t.get("launch")||void 0,codeChallenge:t.get("code_challenge")||void 0,codeChallengeMethod:t.get("code_challenge_method")||void 0,chooseScopes:r!=="openid",children:[s.jsx(Zr,{size:32}),s.jsx(be,{children:"Sign in to Medplum"})]})}function YK(){const e=ae(),t=Gt(),n=Iu();return p.useEffect(()=>{e.getProfile()&&t("/signin?project=new")},[e,t]),i_()?s.jsxs(qq,{type:"project",projectId:"new",onSuccess:()=>t("/"),googleClientId:n.googleClientId,recaptchaSiteKey:n.recaptchaSiteKey,children:[s.jsx(Zr,{size:32}),s.jsx(be,{children:"Create a new account"})]}):s.jsx(Oe,{width:450,children:s.jsx(Ui,{icon:s.jsx(Tl,{size:16}),title:"New projects disabled",color:"red",children:"New projects are disabled on this server."})})}function XK(){const e=Gt(),t=ae(),[n,r]=p.useState(),[o,i]=p.useState(!1),a=Iu().recaptchaSiteKey;return p.useEffect(()=>{a&&E2(a)},[a]),s.jsx(Oe,{width:450,children:s.jsxs(Qe,{onSubmit:async l=>{let c="";a&&(c=await T2(a)),t.post("auth/resetpassword",{...l,recaptchaToken:c}).then(()=>i(!0)).catch(u=>r(mt(u)))},children:[s.jsxs(Ae,{gap:"lg",mb:"xl",align:"center",children:[s.jsx(Zr,{size:32}),s.jsx(be,{children:"Medplum Password Reset"})]}),s.jsxs(Ae,{gap:"xl",children:[s.jsx(Dr,{issues:Eu(n,void 0)}),!o&&s.jsxs(s.Fragment,{children:[s.jsx(ye,{name:"email",type:"email",label:"Email",required:!0,autoFocus:!0,error:Ye(n,"email")}),s.jsxs(ee,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[s.jsx(Xe,{component:"button",type:"button",color:"dimmed",onClick:()=>e("/register"),size:"xs",children:"Register"}),s.jsx(ie,{type:"submit",children:"Reset password"})]})]}),o&&s.jsx("div",{children:"If the account exists on our system, a password reset email will be sent."})]})]})})}function JK(){var i;const e=Gt(),t=ae(),[n,r]=p.useState();p.useEffect(()=>{t.get("auth/me",{cache:"no-cache"}).then(r).catch(a=>pe({color:"red",message:Ie(a),autoClose:!1}))},[t]);function o(a){t.post("auth/revoke",{loginId:a}).then(()=>t.get("auth/me",{cache:"no-cache"})).then(r).then(()=>pe({color:"green",message:"Login revoked"})).catch(l=>pe({color:"red",message:Ie(l),autoClose:!1}))}return n?s.jsxs(s.Fragment,{children:[s.jsxs(Oe,{children:[s.jsx(be,{children:"Security"}),s.jsxs(u0,{children:[s.jsx(Ao,{term:"ID",children:s.jsx(Xe,{href:`/${ct(n.profile)}`,children:n.profile.id})}),s.jsx(Ao,{term:"Resource Type",children:n.profile.resourceType}),s.jsx(Ao,{term:"Name",children:bu((i=n.profile.name)==null?void 0:i[0])})]})]}),s.jsxs(Oe,{children:[s.jsx(be,{children:"Sessions"}),s.jsxs(fe,{children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"OS"}),s.jsx("th",{children:"Browser"}),s.jsx("th",{children:"IP Address"}),s.jsx("th",{children:"Auth Method"}),s.jsx("th",{children:"Last Updated"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:n.security.sessions.map(a=>s.jsxs("tr",{children:[s.jsx("td",{children:a.os}),s.jsx("td",{children:a.browser}),s.jsx("td",{children:a.remoteAddress}),s.jsx("td",{children:a.authMethod}),s.jsx("td",{children:Ln(a.lastUpdated)}),s.jsx("td",{children:s.jsx(Xe,{href:"#",onClick:()=>o(a.id),children:"Revoke"})})]},a.id))})]})]}),s.jsxs(Oe,{children:[s.jsx(be,{children:"Password"}),s.jsx(ie,{onClick:()=>e("/changepassword"),children:"Change password"})]}),s.jsxs(Oe,{children:[s.jsx(be,{children:"Multi Factor Auth"}),s.jsxs("p",{children:["Enrolled: ",n.security.mfaEnrolled.toString()]}),!n.security.mfaEnrolled&&s.jsx(ie,{onClick:()=>e("/mfa"),children:"Enroll"})]})]}):null}function ZK(){const{id:e,secret:t}=ft(),n=ae(),[r,o]=p.useState(),[i,a]=p.useState(!1),l=Eu(r,void 0);return s.jsxs(Oe,{width:450,children:[s.jsx(Dr,{issues:l}),s.jsxs(Qe,{onSubmit:c=>{if(c.password!==c.confirmPassword){o(go("Passwords do not match","confirmPassword"));return}o(void 0);const u={id:e,secret:t,password:c.password};n.post("auth/setpassword",u).then(()=>a(!0)).catch(d=>o(mt(d)))},children:[s.jsxs(vn,{style:{flexDirection:"column"},children:[s.jsx(Zr,{size:32}),s.jsx(be,{children:"Set password"})]}),!i&&s.jsxs(Ae,{children:[s.jsx(Wr,{name:"password",label:"New password",required:!0,error:Ye(r,"password")}),s.jsx(Wr,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Ye(r,"confirmPassword")}),s.jsx(ee,{justify:"flex-end",mt:"xl",children:s.jsx(ie,{type:"submit",children:"Set password"})})]}),i&&s.jsxs("div",{"data-testid":"success",children:["Password set. You can now ",s.jsx(qe,{to:"/signin",children:"sign in"}),"."]})]})]})}function eY(){const e=Qh(),t=Gt(),[n]=O0(),r=Iu(),o=p.useCallback(()=>{const i=n.get("next");t(i!=null&&i.startsWith("/")?i:"/")},[n,t]);return p.useEffect(()=>{e&&n.has("next")&&o()},[e,n,o]),s.jsxs(P2,{onSuccess:()=>o(),onForgotPassword:()=>t("/resetpassword"),onRegister:i_()?()=>t("/register"):void 0,googleClientId:r.googleClientId,login:n.get("login")||void 0,projectId:n.get("project")||void 0,children:[s.jsx(Zr,{size:32}),s.jsx(be,{children:"Sign in to Medplum"}),n.get("project")==="new"&&s.jsx("div",{children:"Sign in again to create a new project"})]})}function tY(){const e=Gt(),t=ri(),[n,r]=p.useState(),[o,i]=p.useState(),[a,l]=p.useState();return p.useEffect(()=>{const c=Object.fromEntries(new URLSearchParams(t.search).entries());r(c.resourceType),i(c.query),l(JSON.parse(c.fields))},[t]),!n||!o||!a?null:s.jsx(QW,{resourceType:n,checkboxesEnabled:!0,query:o,fields:a,onClick:c=>e(`/${n}/${c.resource.id}`),onAuxClick:c=>window.open(`/${n}/${c.resource.id}`,"_blank"),onBulk:c=>{e(`/bulk/${n}?ids=${c.join(",")}`)}})}function sp(e){const t=ae(),n=qi(t),r=Gt(),[o,i]=p.useState({resourceType:"ProjectMembership",filters:[{code:"project",operator:oe.EQUALS,value:"Project/"+n},{code:"profile-type",operator:oe.EQUALS,value:e.resourceType}],fields:e.fields,count:100});return s.jsx(ku,{search:o,onClick:a=>r(`/admin/members/${a.resource.id}`),onChange:a=>i(a.definition),hideFilters:!0,hideToolbar:!0})}function nY(){return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Bots"}),s.jsx(sp,{resourceType:"Bot",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(ee,{justify:"flex-end",children:s.jsx(qe,{to:"/admin/bots/new",children:"Create new bot"})})]})}function rY(){return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Clients"}),s.jsx(sp,{resourceType:"ClientApplication",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(ee,{justify:"flex-end",children:s.jsx(qe,{to:"/admin/clients/new",children:"Create new client"})})]})}function ap(e){return s.jsx(Ys,{resourceType:"AccessPolicy",name:"accessPolicy",defaultValue:e.defaultValue,placeholder:"Access Policy",onChange:t=>{ti(t)?e.onChange(Tt(t)):e.onChange(void 0)}})}function oY(){const e=ae(),t=qi(e),[n,r]=p.useState(""),[o,i]=p.useState(""),[a,l]=p.useState(),[c,u]=p.useState(),[d,f]=p.useState(void 0);return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Create new Bot"}),s.jsxs(Qe,{onSubmit:()=>{const h={name:n,description:o,accessPolicy:a};e.post("admin/projects/"+t+"/bot",h).then(m=>{e.invalidateSearches("Bot"),e.invalidateSearches("ProjectMembership"),f(m),pe({color:"green",message:"Bot created"})}).catch(m=>{pe({color:"red",message:Ie(m),autoClose:!1}),u(mt(m))})},children:[!d&&s.jsxs(Ae,{children:[s.jsx(yt,{title:"Name",htmlFor:"name",outcome:c,children:s.jsx(ye,{id:"name",name:"name",required:!0,autoFocus:!0,onChange:h=>r(h.currentTarget.value),error:Ye(c,"name")})}),s.jsx(yt,{title:"Description",htmlFor:"description",outcome:c,children:s.jsx(ye,{id:"description",name:"description",onChange:h=>i(h.currentTarget.value),error:Ye(c,"description")})}),s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:c,children:s.jsx(ap,{name:"accessPolicy",onChange:l})}),s.jsx(ee,{justify:"flex-end",children:s.jsx(ie,{type:"submit",children:"Create Bot"})})]}),d&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(he,{children:"Bot created"}),s.jsxs(Mn,{children:[s.jsx(Mn.Item,{children:s.jsx(qe,{to:d,children:"Go to new bot"})}),s.jsx(Mn.Item,{children:s.jsx(qe,{to:"/admin/bots",children:"Back to bots list"})})]})]})]})]})}function iY(){const e=ae(),t=qi(e),[n,r]=p.useState(""),[o,i]=p.useState(""),[a,l]=p.useState(""),[c,u]=p.useState(),[d,f]=p.useState(),[h,m]=p.useState(void 0);return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Create new Client"}),s.jsxs(Qe,{onSubmit:()=>{const g={name:n,description:o,redirectUri:a,accessPolicy:c};e.post("admin/projects/"+t+"/client",g).then(v=>{e.invalidateSearches("ClientApplication"),e.invalidateSearches("ProjectMembership"),m(v),pe({color:"green",message:"Client created"})}).catch(v=>{pe({color:"red",message:Ie(v),autoClose:!1}),f(mt(v))})},children:[!h&&s.jsxs(Ae,{children:[s.jsx(yt,{title:"Name",htmlFor:"name",outcome:d,children:s.jsx(ye,{id:"name",name:"name",required:!0,autoFocus:!0,onChange:g=>r(g.currentTarget.value),error:Ye(d,"name")})}),s.jsx(yt,{title:"Description",htmlFor:"description",outcome:d,children:s.jsx(ye,{id:"description",name:"description",onChange:g=>i(g.currentTarget.value),error:Ye(d,"description")})}),s.jsx(yt,{title:"Redirect URI",htmlFor:"redirectUri",outcome:d,children:s.jsx(ye,{id:"redirectUri",name:"redirectUri",onChange:g=>l(g.currentTarget.value),error:Ye(d,"redirectUri")})}),s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:d,children:s.jsx(ap,{name:"accessPolicy",onChange:u})}),s.jsx(ee,{justify:"flex-end",children:s.jsx(ie,{type:"submit",children:"Create Client"})})]}),h&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(he,{children:"Client created"}),s.jsxs(Mn,{children:[s.jsx(Mn.Item,{children:s.jsx(qe,{to:h,children:"Go to new client"})}),s.jsx(Mn.Item,{children:s.jsx(qe,{to:"/admin/clients",children:"Back to clients list"})})]})]})]})]})}function sY(e){return s.jsx(Ys,{resourceType:"UserConfiguration",name:"userConfiguration",defaultValue:e.defaultValue,placeholder:"User Configuration",onChange:t=>{ti(t)?e.onChange(Tt(t)):e.onChange(void 0)}})}function aY(){const{membershipId:e}=ft(),t=ae(),n=qi(t),r=Gt(),o=t.get(`admin/projects/${n}/members/${e}`).read(),[i,a]=p.useState(o.accessPolicy),[l,c]=p.useState(o.userConfiguration),[u,d]=p.useState(o.admin),[f,h]=p.useState(),[m,g]=p.useState(!1);function v(){window.confirm("Are you sure?")&&t.delete(`admin/projects/${n}/members/${e}`).then(()=>t.get(`admin/projects/${n}`,{cache:"no-cache"})).then(()=>r("/admin/project")).catch(S=>h(mt(S)))}return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Edit membership"}),s.jsx("h3",{children:s.jsx(Ha,{value:o.profile,link:!0})}),s.jsxs(Qe,{onSubmit:()=>{const S={...o,accessPolicy:i,userConfiguration:l,admin:u};t.post(`admin/projects/${n}/members/${e}`,S).then(()=>g(!0)).catch(b=>h(mt(b)))},children:[!m&&s.jsxs(Ae,{children:[s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:f,children:s.jsx(ap,{name:"accessPolicy",defaultValue:i,onChange:a})}),s.jsx(yt,{title:"User Configuration",htmlFor:"userConfiguration",outcome:f,children:s.jsx(sY,{name:"userConfiguration",defaultValue:l,onChange:c})}),s.jsx(yt,{title:"Admin",htmlFor:"admin",outcome:f,children:s.jsx(kn,{id:"admin",name:"admin",defaultChecked:u,onChange:S=>d(S.currentTarget.checked)})}),s.jsxs(ee,{justify:"flex-end",mt:"xl",children:[s.jsx(ie,{type:"submit",children:"Save"}),s.jsx(ie,{type:"button",color:"red",variant:"outline",onClick:v,children:"Remove user"})]})]}),m&&s.jsxs("div",{"data-testid":"success",children:[s.jsx("p",{children:"User updated"}),s.jsx("pre",{children:JSON.stringify(f,void 0,2)}),s.jsxs("p",{children:["Click ",s.jsx(qe,{to:"/admin/project",children:"here"})," to return to the project admin page."]})]})]})]})}function lY(){const e=ae(),[t,n]=p.useState(e.getProject()),[r,o]=p.useState(),[i,a]=p.useState(),[l,c]=p.useState(!1),[u,d]=p.useState(void 0),f=p.useCallback(h=>{const m={resourceType:h.resourceType,firstName:h.firstName,lastName:h.lastName,email:h.email,sendEmail:h.sendEmail==="on",accessPolicy:r,admin:h.isAdmin==="on"};e.invite(t==null?void 0:t.id,m).then(g=>{e.invalidateSearches("Patient"),e.invalidateSearches("Practitioner"),e.invalidateSearches("ProjectMembership"),zh(g)?a(g):d(g),c(m.sendEmail??!1),pe({color:"green",message:"Invite success"})}).catch(g=>{pe({color:"red",message:Ie(g),autoClose:!1}),a(mt(g))})},[e,t,r]);return s.jsxs(Qe,{onSubmit:f,children:[!u&&!i&&s.jsxs(Ae,{children:[s.jsx(be,{children:"Invite new member"}),e.isSuperAdmin()&&s.jsx(yt,{title:"Project",htmlFor:"project",outcome:i,children:s.jsx(Ys,{resourceType:"Project",name:"project",defaultValue:t,onChange:n})}),s.jsx(Pt,{name:"resourceType",label:"Role",defaultValue:"Practitioner",data:["Practitioner","Patient","RelatedPerson"],error:Ye(i,"resourceType")}),s.jsx(ye,{name:"firstName",label:"First Name",required:!0,autoFocus:!0,error:Ye(i,"firstName")}),s.jsx(ye,{name:"lastName",label:"Last Name",required:!0,error:Ye(i,"lastName")}),s.jsx(ye,{name:"email",type:"email",label:"Email",required:!0,error:Ye(i,"email")}),s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:i,children:s.jsx(ap,{name:"accessPolicy",onChange:o})}),s.jsx(kn,{name:"sendEmail",label:"Send email",defaultChecked:!0}),s.jsx(kn,{name:"isAdmin",label:"Admin"}),s.jsx(ee,{justify:"flex-end",children:s.jsx(ie,{type:"submit",children:"Invite"})})]}),i&&s.jsxs("div",{"data-testid":"success",children:[s.jsx("p",{children:"User created, email couldn't be sent"}),s.jsx("p",{children:"Could not send email. Make sure you have AWS SES set up."}),s.jsxs("p",{children:["Click ",s.jsx(qe,{to:"/admin/project",children:"here"})," to return to the project admin page."]})]}),u&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(he,{children:"User created"}),l&&s.jsx(he,{children:"Email sent"}),s.jsxs(Mn,{children:[s.jsx(Mn.Item,{children:s.jsx(qe,{to:u,children:"Go to new membership"})}),s.jsx(Mn.Item,{children:s.jsx(qe,{to:u.profile,children:"Go to new profile"})}),s.jsx(Mn.Item,{children:s.jsx(qe,{to:"/admin/users",children:"Back to users list"})})]})]})]})}function cY(){return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Patients"}),s.jsx(sp,{resourceType:"Patient",fields:["user","profile","_lastUpdated"]}),s.jsx(ee,{justify:"flex-end",children:s.jsx(qe,{to:"/admin/invite",children:"Invite new patient"})})]})}function uY(){const e=ae();if(!e.isLoading()&&!e.isProjectAdmin())return s.jsx(Dr,{outcome:hk});function t(n){e.post("admin/projects/setpassword",n).then(()=>pe({color:"green",message:"Done"})).catch(r=>pe({color:"red",message:Ie(r),autoClose:!1}))}return s.jsxs(Oe,{width:600,children:[s.jsx(be,{order:1,children:"Project Admin"}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Force Set Password"}),s.jsx(he,{children:"Sets the password for the specified user in this project."}),s.jsx(he,{children:"This action can only be performed by project administrators. Passwords can only be set for users scoped in this project."}),s.jsx(Qe,{onSubmit:t,children:s.jsxs(Ae,{children:[s.jsx(ye,{name:"email",label:"Email",required:!0}),s.jsx(Wr,{name:"password",label:"Password",required:!0}),s.jsx(ie,{type:"submit",children:"Force Set Password"})]})})]})}function BS(){const e=ae(),t=qi(e),n=e.get(`admin/projects/${t}`).read();return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Details"}),s.jsxs(u0,{children:[s.jsx(Ao,{term:"ID",children:n.project.id}),s.jsx(Ao,{term:"Name",children:n.project.name})]})]})}const VS=["Details","Users","Patients","Clients","Bots","Secrets","Sites"];function dY(){const e=Gt(),n=ri().pathname.replace("/admin/","")||VS[0],r=ae(),o=qi(r),i=p.useMemo(()=>r.get("admin/projects/"+o).read(),[r,o]);function a(l){e(`/admin/${l}`)}return s.jsxs(s.Fragment,{children:[s.jsxs(Xn,{children:[s.jsx(ze,{children:s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Project"}),s.jsx(ze.Value,{children:i.project.name})]})}),s.jsx(kr,{children:s.jsx(et,{value:n.toLowerCase(),onChange:a,children:s.jsx(et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:VS.map(l=>s.jsx(et.Tab,{value:l.toLowerCase(),children:l},l))})})})]}),s.jsx(Oe,{children:s.jsx(M0,{})})]})}function fY(){const e=ae(),t=qi(e),n=e.get(`admin/projects/${t}`).read(),[r,o]=p.useState(!1),[i,a]=p.useState();return p.useEffect(()=>{e.requestSchema("Project").then(()=>o(!0)).catch(console.log)},[e]),p.useEffect(()=>{n&&a(Qr(n.project.secret||[]))},[e,n]),!r||!i?s.jsx("div",{children:"Loading..."}):s.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:l=>{l.preventDefault(),e.post(`admin/projects/${t}/secrets`,i).then(()=>e.get(`admin/projects/${t}`,{cache:"reload"})).then(()=>pe({color:"green",message:"Saved"})).catch(console.log)},children:[s.jsx(be,{children:"Project Secrets"}),s.jsx("p",{children:"Use project secrets to store sensitive information such as API keys or other access credentials."}),s.jsx(Pl,{property:Gs("Project","secret"),name:"secret",path:"Project.secret",defaultValue:i,onChange:a,outcome:void 0}),s.jsx(ie,{type:"submit",children:"Save"})]})}function hY(){const e=ae(),t=qi(e),n=e.get(`admin/projects/${t}`).read(),[r,o]=p.useState(!1),[i,a]=p.useState();return p.useEffect(()=>{e.requestSchema("Project").then(()=>o(!0)).catch(console.log)},[e]),p.useEffect(()=>{n&&a(Qr(n.project.site||[]))},[e,n]),!r||!i?s.jsx("div",{children:"Loading..."}):s.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:l=>{l.preventDefault(),e.post(`admin/projects/${t}/sites`,i).then(()=>e.get(`admin/projects/${t}`,{cache:"reload"})).then(()=>pe({color:"green",message:"Saved"})).catch(c=>{var d,f,h,m;const u=mt(c);pe({color:"red",message:`Error ${(f=(d=u.issue)==null?void 0:d[0].details)==null?void 0:f.text} ${(m=(h=u.issue)==null?void 0:h[0].expression)==null?void 0:m[0]}`,autoClose:!1})})},children:[s.jsx(be,{children:"Project Sites"}),s.jsx("p",{children:"Use project sites configure your project on a separate domain."}),s.jsx(Pl,{property:Gs("Project","site"),name:"site",path:"Project.site",defaultValue:i,onChange:a,outcome:void 0}),s.jsx(ie,{type:"submit",children:"Save"})]})}function pY(){const e=ae(),[t,{open:n,close:r}]=Bf(!1),[o,i]=p.useState(""),[a,l]=p.useState();if(!e.isLoading()&&!e.isSuperAdmin())return s.jsx(Dr,{outcome:hk});function c(){md(e,"Rebuilding Structure Definitions","admin/super/structuredefinitions")}function u(){md(e,"Rebuilding Search Parameters","admin/super/searchparameters")}function d(){md(e,"Rebuilding Value Sets","admin/super/valuesets")}function f(S){md(e,"Reindexing Resources","admin/super/reindex",S)}function h(S){e.post("admin/super/removebotidjobsfromqueue",S).then(()=>pe({color:"green",message:"Done"})).catch(b=>pe({color:"red",message:Ie(b),autoClose:!1}))}function m(S){e.post("admin/super/purge",{...S,before:kR(S.before)}).then(()=>pe({color:"green",message:"Done"})).catch(b=>pe({color:"red",message:Ie(b),autoClose:!1}))}function g(S){e.post("admin/super/setpassword",S).then(()=>pe({color:"green",message:"Done"})).catch(b=>pe({color:"red",message:Ie(b),autoClose:!1}))}function v(){e.post("fhir/R4/$db-stats",{}).then(S=>{var b,x;i("Database Stats"),l(s.jsx("pre",{children:(x=(b=S.parameter)==null?void 0:b.find(y=>y.name==="tableString"))==null?void 0:x.valueString})),n()}).catch(S=>pe({color:"red",message:Ie(S),autoClose:!1}))}return s.jsxs(Oe,{width:600,children:[s.jsx(be,{order:1,children:"Super Admin"}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Structure Definitions"}),s.jsx("p",{children:"StructureDefinition resources contain the metadata about resource types. They are provided with the FHIR specification. Medplum also includes some custom StructureDefinition resources for internal data types. Press this button to update the database StructureDefinitions from the FHIR specification."}),s.jsx(Qe,{children:s.jsx(ie,{onClick:c,children:"Rebuild StructureDefinitions"})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Search Parameters"}),s.jsx("p",{children:"SearchParameter resources contain the metadata about filters and sorting. They are provided with the FHIR specification. Medplum also includes some custom SearchParameter resources for internal data types. Press this button to update the database SearchParameters from the FHIR specification."}),s.jsx(Qe,{children:s.jsx(ie,{onClick:u,children:"Rebuild SearchParameters"})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Value Sets"}),s.jsx("p",{children:"ValueSet resources enum values for a wide variety of use cases. Press this button to update the database ValueSets from the FHIR specification."}),s.jsx(Qe,{children:s.jsx(ie,{onClick:d,children:"Rebuild ValueSets"})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Reindex Resources"}),s.jsx("p",{children:"When Medplum changes how resources are indexed, the system may require a reindex for old resources to be indexed properly."}),s.jsx(Qe,{onSubmit:f,children:s.jsxs(Ae,{children:[s.jsx(yt,{title:"Resource Type",htmlFor:"resourceType",children:s.jsx(ye,{id:"resourceType",name:"resourceType",placeholder:"Reindex Resource Type"})}),s.jsx(yt,{title:"Search Filter",htmlFor:"filter",children:s.jsx(ye,{id:"filter",name:"filter",placeholder:"e.g. name=Sam&birthdate=lt2000-01-01"})}),s.jsx(ie,{type:"submit",children:"Reindex"})]})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Purge Resources"}),s.jsx("p",{children:"As system generated resources accumulate, the system may require a purge to remove old resources."}),s.jsx(Qe,{onSubmit:m,children:s.jsxs(Ae,{children:[s.jsx(yt,{title:"Purge Resource Type",htmlFor:"purgeResourceType",children:s.jsx(Pt,{id:"purgeResourceType",name:"resourceType",data:["","AuditEvent","Login"]})}),s.jsx(yt,{title:"Purge Before",htmlFor:"before",children:s.jsx(Rs,{name:"before",placeholder:"Before Date"})}),s.jsx(ie,{type:"submit",children:"Purge"})]})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Remove Bot ID Jobs from Queue"}),s.jsx("p",{children:"Remove all queued jobs for a Bot ID"}),s.jsx(Qe,{onSubmit:h,children:s.jsxs(Ae,{children:[s.jsx(yt,{title:"Bot ID",children:s.jsx(ye,{name:"botId",placeholder:"Bot Id"})}),s.jsx(ie,{type:"submit",children:"Remove Jobs by Bot ID"})]})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Force Set Password"}),s.jsx("p",{children:'Note that this applies to all projects for the user. Therefore, this should only be used in extreme circumstances. Always prefer to use the "Forgot Password" flow first.'}),s.jsx(Qe,{onSubmit:g,children:s.jsxs(Ae,{children:[s.jsx(ye,{name:"email",label:"Email",required:!0}),s.jsx(Wr,{name:"password",label:"Password",required:!0}),s.jsx(ye,{name:"projectId",label:"Project ID"}),s.jsx(ie,{type:"submit",children:"Force Set Password"})]})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Database Stats"}),s.jsx("p",{children:"Query current table statistics from the database."}),s.jsx(Qe,{onSubmit:v,children:s.jsx(ie,{type:"submit",children:"Get Database Stats"})}),s.jsx(mn,{opened:t,onClose:r,title:o,centered:!0,children:a})]})}function md(e,t,n,r){mo.show({id:n,loading:!0,title:t,message:"Running...",autoClose:!1,withCloseButton:!1});const o={method:"POST",pollStatusOnAccepted:!0};r&&(o.body=JSON.stringify(r)),e.startAsyncRequest(n,o).then(()=>{mo.update({id:n,color:"green",title:t,message:"Done",icon:s.jsx(Ks,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}).catch(i=>{mo.update({id:n,color:"red",title:t,message:Ie(i),icon:s.jsx(Cf,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})})}function mY(){return s.jsxs(s.Fragment,{children:[s.jsx(be,{children:"Users"}),s.jsx(sp,{resourceType:"Practitioner",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(ee,{justify:"flex-end",children:s.jsx(qe,{to:"/admin/invite",children:"Invite new user"})})]})}function gY(){const[e]=ll("ObservationDefinition","_count=100");return e?s.jsxs(fe,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Category"}),s.jsx("th",{children:"Code"}),s.jsx("th",{children:"Method"}),s.jsx("th",{children:"Unit"}),s.jsx("th",{children:"Precision"}),s.jsx("th",{children:"Ranges"})]})}),s.jsx("tbody",{children:e.map(t=>{var n,r,o,i;return s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(vo,{value:(n=t.category)==null?void 0:n[0]})}),s.jsx("td",{children:s.jsx(vo,{value:t.code})}),s.jsx("td",{children:s.jsx(vo,{value:t.method})}),s.jsx("td",{children:(o=(r=t.quantitativeDetails)==null?void 0:r.unit)==null?void 0:o.text}),s.jsx("td",{children:(i=t.quantitativeDetails)==null?void 0:i.decimalPrecision}),s.jsx("td",{children:s.jsx(nv,{ranges:t.qualifiedInterval})})]},t.id)})})]}):s.jsx(Tr,{})}function nv(e){const{ranges:t}=e;if(!t)return null;const n=WS(t.map(o=>o.gender));if(n.length>1)return Uc(n),s.jsx(s.Fragment,{children:n.map(o=>{var i;return s.jsxs(p.Fragment,{children:[s.jsx("div",{children:s.jsx("strong",{children:tn(o)})}),s.jsx(nv,{ranges:(i=e.ranges)==null?void 0:i.filter(a=>a.gender===o)})]},o)})});const r=WS(t.map(o=>o.age&&Bc(o.age)));return r.length>1?(Uc(r),s.jsx(s.Fragment,{children:r.map(o=>{var i;return s.jsxs(p.Fragment,{children:[s.jsx("div",{children:s.jsx("strong",{children:tn(o)})}),s.jsx(nv,{ranges:(i=e.ranges)==null?void 0:i.filter(a=>Bc(a.age)===o)})]},o)})})):s.jsx(s.Fragment,{children:t.map(o=>s.jsx("table",{children:s.jsx("tbody",{children:s.jsxs("tr",{children:[s.jsx("td",{children:o.condition}),s.jsx("td",{children:s.jsx(f0,{value:o.range})})]})})},`range-${o.condition}`))})}function WS(e){return[...new Set(e.filter(t=>!!t))]}function vY(){const[e]=ll("ActivityDefinition","_count=100"),[t]=ll("ObservationDefinition","_count=100");return!e||!t?s.jsx(Tr,{}):s.jsxs(fe,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Category"}),s.jsx("th",{children:"Assay"}),e.map(n=>s.jsx("th",{children:n.name},n.id))]})}),s.jsx("tbody",{children:t.map(n=>{var r;return s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(vo,{value:(r=n.category)==null?void 0:r[0]})}),s.jsx("td",{children:s.jsx(vo,{value:n.code})}),e.map(o=>{var i;return s.jsx("td",{children:(i=o.observationResultRequirement)!=null&&i.find(a=>{var l;return(l=a.reference)==null?void 0:l.includes(n.id)})?"✅":""},o.id)})]},n.id)})})]})}function yY(e){var a;const t=ae(),[n,r]=p.useState(),[o,i]=p.useState();return o?s.jsxs(s.Fragment,{children:[s.jsx("p",{children:"Request group created successfully."}),s.jsxs("ul",{children:[s.jsxs("li",{children:["Go to the"," ",s.jsx(qe,{to:o,suffix:"checklist",children:"Request Group"})]}),s.jsxs("li",{children:["Back to the ",s.jsx(qe,{to:e.planDefinition,children:"Plan Definition"})]})]})]}):s.jsx(Qe,{onSubmit:()=>{t.post(t.fhirUrl("PlanDefinition",e.planDefinition.id,"$apply"),{resourceType:"Parameters",parameter:[{name:"subject",valueString:n==null?void 0:n.reference}]}).then(i).catch(console.log)},children:s.jsxs(Ae,{children:[s.jsxs(be,{children:['Start "',e.planDefinition.title,'"']}),s.jsxs(he,{children:["Use the ",s.jsx("strong",{children:"Apply"})," operation to create a group of tasks for a workflow."]}),s.jsx(he,{children:"The following tasks will be created:"}),s.jsx("ul",{children:(a=e.planDefinition.action)==null?void 0:a.map((l,c)=>{var u;return s.jsxs("li",{children:[((u=l.definitionCanonical)==null?void 0:u.startsWith("Questionnaire/"))&&"Questionnaire request: ",l.title&&s.jsx(s.Fragment,{children:l.title}),l.code&&s.jsx(vo,{value:l.code[0]})]},`action-${c}`)})}),s.jsx(yt,{title:"Subject",children:s.jsx(Yh,{name:"subject",targetTypes:["Patient","Practitioner"],defaultValue:n,onChange:r})}),s.jsx(ee,{justify:"flex-end",mt:"xl",children:s.jsx(ie,{type:"submit",children:"Go"})})]})})}function xY(){const{resourceType:e,id:t}=ft(),n=St({reference:e+"/"+t});return n?s.jsx(Oe,{children:s.jsx(yY,{planDefinition:n})}):null}function bY(){const{resourceType:e,id:t}=ft(),n=St({reference:e+"/"+t}),[r,o]=ll("Questionnaire","subject-type="+e),[i,a]=ll("ClientApplication",{_count:1e3});if(!n||o||a)return s.jsx(Tr,{});const l=i==null?void 0:i.filter(d=>wY(e)&&!!d.launchUri);if((!r||r.length===0)&&(!l||l.length===0))return s.jsxs(Oe,{children:[s.jsx(be,{children:"Apps"}),s.jsxs("p",{children:["No apps found. Contact your administrator or ",s.jsx("a",{href:"mailto:support@medplum.com",children:"Medplum Support"})," to add automation here."]})]});let c,u;return n.resourceType==="Patient"?c=Tt(n):n.resourceType==="Encounter"&&(c=n.subject,u=Tt(n)),s.jsxs(Oe,{children:[r==null?void 0:r.map(d=>s.jsxs("div",{children:[s.jsx(be,{order:3,children:s.jsx(qe,{to:`/forms/${d.id}?subject=${ct(n)}`,children:d.title||d.name})}),s.jsx(he,{children:d.description})]},d.id)),l==null?void 0:l.map(d=>s.jsxs("div",{children:[s.jsx(be,{order:3,children:s.jsx(Wq,{client:d,patient:c,encounter:u,children:d.name})}),s.jsx(he,{children:d.description})]},d.id))]})}function wY(e){return e==="Patient"||e==="Encounter"}function SY(){const{resourceType:e,id:t}=ft(),n=Gt(),[r,o]=p.useState({resourceType:"AuditEvent",filters:[{code:"entity",operator:oe.EQUALS,value:`${e}/${t}`}],fields:["id","outcome","outcomeDesc","_lastUpdated"],sortRules:[{code:"-_lastUpdated"}],count:20});return s.jsx(Oe,{children:s.jsx(ku,{search:r,onClick:i=>n(`/${i.resource.resourceType}/${i.resource.id}`),onChange:i=>o(i.definition),hideFilters:!0})})}function jY(){const e=ae(),{resourceType:t,id:n}=ft(),r=e.readHistory(t,n).read();return s.jsx(Oe,{children:s.jsx(Aq,{history:r})})}const CY="_hl7Input_k5xm3_1",EY={hl7Input:CY};function TY(e){return s.jsx("iframe",{frameBorder:"0",src:"https://codeeditor.medplum.com/bot-runner.html",className:e.className,ref:e.iframeRef,"data-testid":e.testId,style:{width:"100%",height:"100%",minHeight:e.minHeight}})}function PY(e){const t=e.defaultValue,n=new URL(`https://codeeditor.medplum.com/${e.language}-editor.html`);return e.module&&n.searchParams.set("module",e.module),s.jsx("iframe",{frameBorder:"0",src:n.toString(),style:{width:"100%",height:"100%",minHeight:e.minHeight},ref:e.iframeRef,"data-testid":e.testId,onLoad:r=>{Md(r.currentTarget,{command:"setValue",value:t}).catch(console.error)}})}const kY=`{
572
572
  "resourceType": "Patient",
573
573
  "name": [
574
574
  {
@@ -579,4 +579,4 @@ Error generating stack: `+i.message+`
579
579
  }
580
580
  ]
581
581
  }`,RY="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 _Y(){const e=ae(),{id:t}=ft(),[n,r]=p.useState(),[o,i]=p.useState(),[a,l]=p.useState(kY),[c,u]=p.useState(RY),[d,f]=p.useState(sn.FHIR_JSON),h=p.useRef(null),m=p.useRef(null),[g,v]=p.useState(!1);p.useEffect(()=>{e.readResource("Bot",t).then(async j=>{r(j),i(await DY(e,j))}).catch(j=>pe({color:"red",message:Ie(j),autoClose:!1}))},[e,t]);const S=p.useCallback(()=>Md(h.current,{command:"getValue"}),[]),b=p.useCallback(()=>Md(h.current,{command:"getOutput"}),[]),x=p.useCallback(async()=>d===sn.FHIR_JSON?JSON.parse(a):c,[d,a,c]),y=p.useCallback(async j=>{j.preventDefault(),j.stopPropagation(),v(!0);try{const T=await S(),E=await b(),R=await e.createAttachment(T,"index.ts","text/typescript"),_=await e.createAttachment(E,"index.js","text/typescript"),N=[{op:"add",path:"/sourceCode",value:R},{op:"add",path:"/executableCode",value:_}];await e.patchResource("Bot",t,N),pe({color:"green",message:"Saved"})}catch(T){pe({color:"red",message:Ie(T),autoClose:!1})}finally{v(!1)}},[e,t,S,b]),w=p.useCallback(async j=>{j.preventDefault(),j.stopPropagation(),v(!0);try{await e.post(e.fhirUrl("Bot",t,"$deploy")),pe({color:"green",message:"Deployed"})}catch(T){pe({color:"red",message:Ie(T),autoClose:!1})}finally{v(!1)}},[e,t]),C=p.useCallback(async j=>{j.preventDefault(),j.stopPropagation(),v(!0);try{const T=await x(),E=await e.post(e.fhirUrl("Bot",t,"$execute"),T,d);await Md(m.current,{command:"setValue",value:E}),pe({color:"green",message:"Success"})}catch(T){pe({color:"red",message:Ie(T),autoClose:!1})}finally{v(!1)}},[e,t,x,d]);return!n||o===void 0?null:s.jsxs(ar,{m:0,gutter:0,style:{overflow:"hidden"},children:[s.jsx(ar.Col,{span:8,children:s.jsxs(Xn,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[s.jsx(PY,{iframeRef:h,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:o,minHeight:"528px"}),s.jsxs(ee,{justify:"flex-end",gap:"xs",children:[s.jsx(ie,{type:"button",onClick:y,loading:g,leftSection:s.jsx(Oz,{size:"1rem"}),children:"Save"}),s.jsx(ie,{type:"button",onClick:w,loading:g,leftSection:s.jsx(n0,{size:"1rem"}),children:"Deploy"}),s.jsx(ie,{type:"button",onClick:C,loading:g,leftSection:s.jsx(Yz,{size:"1rem"}),children:"Execute"})]})]})}),s.jsxs(ar.Col,{span:4,children:[s.jsxs(Xn,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[s.jsx(Pt,{data:[{label:"FHIR",value:sn.FHIR_JSON},{label:"HL7",value:sn.HL7_V2}],onChange:j=>f(j.currentTarget.value)}),d===sn.FHIR_JSON?s.jsx(yl,{value:a,onChange:j=>l(j),autosize:!0,minRows:15}):s.jsx("textarea",{className:EY.hl7Input,value:c,onChange:j=>u(j.currentTarget.value),rows:15})]}),s.jsx(Xn,{m:2,p:"xs",shadow:"md",children:s.jsx(TY,{iframeRef:m,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function DY(e,t){var n,r,o;if((n=t.sourceCode)!=null&&n.url){const i=(o=(r=t.sourceCode.url)==null?void 0:r.split("/"))==null?void 0:o.find(kk);return(await e.download(e.fhirUrl("Binary",i))).text()}return t.code??""}function Xs(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function IY(){const e=ae(),{resourceType:t,id:n}=ft(),r={reference:t+"/"+n},o=p.useCallback(i=>{e.updateResource(Xs(i)).then(()=>{pe({color:"green",message:"Success"})}).catch(a=>{pe({color:"red",message:Ie(a),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return s.jsx(Oe,{children:s.jsx(sH,{value:r,onSubmit:o})});case"Questionnaire":return s.jsx(Oe,{children:s.jsx(HH,{questionnaire:r,onSubmit:o})});default:return null}}function AY(){const{resourceType:e,id:t}=ft(),n=St({reference:e+"/"+t}),r=Gt();return n?s.jsx(Oe,{children:s.jsx(mq,{value:n,onStart:(o,i)=>r(`/forms/${sl(i)}`),onEdit:(o,i,a)=>r(`/${a.reference}}`)})}):null}function NY(){const e=ae(),{resourceType:t,id:n}=ft(),r=Gt();return s.jsxs(Oe,{children:[s.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),s.jsx(ie,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>r(`/${t}`)).catch(o=>pe({color:"red",message:Ie(o),autoClose:!1}))},children:"Delete"})]})}const MY="_selectProfileBtn_tbaz6_1",OY="_chevron_tbaz6_13",HS={selectProfileBtn:MY,chevron:OY};function LY(){var c,u;const{resourceType:e,id:t}=ft(),n=St({reference:e+"/"+t}),[r,o]=p.useState(),i=cu({onDropdownClose:()=>i.resetSelectedOption()}),a=p.useMemo(()=>{var d;if(Ft((d=n==null?void 0:n.meta)==null?void 0:d.profile))return[s.jsx(Le.Option,{value:"",children:"None"},""),...n.meta.profile.map(f=>s.jsx(Le.Option,{value:f,children:f},f))]},[(c=n==null?void 0:n.meta)==null?void 0:c.profile]);if(p.useEffect(()=>{var d,f;((f=(d=n==null?void 0:n.meta)==null?void 0:d.profile)==null?void 0:f.length)===1&&o(n.meta.profile[0])},[(u=n==null?void 0:n.meta)==null?void 0:u.profile]),!n)return null;let l;return Ft(a)&&(l=s.jsx(ee,{justify:"flex-end",children:s.jsxs(Ae,{align:"flex-end",gap:"xs",children:[s.jsxs(Le,{store:i,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:d=>{o(d),i.closeDropdown()},children:[s.jsx(Le.Target,{children:s.jsx(wn,{onClick:()=>i.toggleDropdown(),children:s.jsxs(Jy,{fw:"bold",fs:"sm",className:HS.selectProfileBtn,children:[s.jsx("span",{children:"Pick profile"}),s.jsx(t0,{stroke:1.5,className:HS.chevron})]})})}),s.jsx(Le.Dropdown,{w:"max-content",children:s.jsx(Le.Options,{children:a})})]}),s.jsx(q,{children:r?s.jsxs(s.Fragment,{children:[s.jsx(he,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),s.jsx(he,{span:!0,size:"sm",children:r||"Nothing selected"})]}):s.jsx(he,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),s.jsx(Oe,{children:s.jsxs(Ae,{gap:"xl",children:[l,s.jsx(C0,{value:n,profileUrl:r})]})})}function $Y(){const e=ae(),{resourceType:t,id:n}=ft(),[r,o]=p.useState(),[i,a]=p.useState(),l=Gt(),[c,u]=p.useState();p.useEffect(()=>{e.readResource(t,n).then(m=>{o(Qr(m)),a(Qr(m))}).catch(m=>{u(mt(m)),pe({color:"red",message:Ie(m),autoClose:!1})})},[e,t,n]);const d=p.useCallback(m=>{u(void 0),e.updateResource(Xs(m)).then(()=>{l(`/${t}/${n}/details`),pe({id:"succes",color:"green",message:"Success"})}).catch(g=>{u(mt(g)),pe({color:"red",message:Ie(g),autoClose:!1})})},[e,t,n,l]),f=p.useCallback(m=>{u(void 0);const g=x0.createPatch(r,m);e.patchResource(t,n,g).then(()=>{l(`/${t}/${n}/details`),pe({id:"succes",color:"green",message:"Success"})}).catch(v=>{u(mt(v)),pe({color:"red",message:Ie(v),autoClose:!1})})},[e,t,n,r,l]),h=p.useCallback(()=>l(`/${t}/${n}/delete`),[l,t,n]);return i?s.jsx(Oe,{children:s.jsx(kf,{defaultValue:i,onSubmit:d,onPatch:f,onDelete:h,outcome:c})}):null}function a_({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,o=ae(),[i,a]=p.useState();return p.useEffect(()=>{o.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(l=>{a(l.filter(xB))}).catch(console.error)},[o,n,r]),s.jsx(et,{value:t==null?void 0:t.url,onChange:l=>{const c=i==null?void 0:i.find(u=>u.url===l);c&&n(c)},children:s.jsx(et.List,{children:i==null?void 0:i.map(l=>{var d,f;const c=(f=(d=e.meta)==null?void 0:d.profile)==null?void 0:f.includes(l.url),u=c?"This profile is present in this resource's meta.profile property.":"This profile is not included in this resource's meta.profile property.";return s.jsx(et.Tab,{value:l.url,title:u,rightSection:c&&s.jsx(Nx,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:s.jsx(uU,{size:"90%"})}),children:l.title||l.name},l.url)})})})}function l_(e,t){const n=ae(),r=Gt();return{defaultValue:{resourceType:e},handleSubmit:a=>{t&&t(void 0),n.createResource(a).then(l=>r("/"+l.resourceType+"/"+l.id)).catch(l=>{t&&t(mt(l)),pe({color:"red",message:Ie(l),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function vm(){const{resourceType:e}=ft(),t=ri(),[n,r]=p.useState(),{defaultValue:o,handleSubmit:i}=l_(e,r),[a,l]=p.useState(),c=t.pathname.toLowerCase().endsWith("profiles"),u=p.useCallback(d=>{const f=Xs(d);a&&Ak(f,a.url),i(f)},[a,i]);return c?s.jsx(Oe,{children:s.jsxs(Ae,{children:[s.jsx(a_,{resource:o,currentProfile:a,onChange:l}),a?s.jsx(kf,{defaultValue:o,onSubmit:u,outcome:n,profileUrl:a.url},a.url):s.jsx(he,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):s.jsx(Oe,{children:s.jsx(kf,{defaultValue:o,onSubmit:i,outcome:n})})}function FY(){const e=ae(),{resourceType:t,id:n}=ft(),r=e.readHistory(t,n).read();return s.jsx(Oe,{children:s.jsx(zq,{history:r})})}function zY(){const{resourceType:e}=ft(),[t,n]=p.useState(),{defaultValue:r,handleSubmit:o}=l_(e,n),i=p.useCallback(a=>{o(JSON.parse(a["new-resource"]))},[o]);return s.jsxs(Oe,{children:[t&&s.jsx(Dr,{outcome:t}),s.jsxs(Qe,{onSubmit:i,children:[s.jsx(yl,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:dr(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),s.jsx(ee,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ie,{type:"submit",children:"OK"})})]})]})}function UY(){const e=ae(),{resourceType:t,id:n}=ft(),r=St({reference:t+"/"+n}),o=Gt(),[i,a]=p.useState(),l=p.useCallback(c=>{e.updateResource(Xs(JSON.parse(c.resource))).then(()=>{a(void 0),o(`/${t}/${n}/details`),pe({color:"green",message:"Success"})}).catch(u=>{pe({color:"red",message:Ie(u),autoClose:!1})})},[e,t,n,o]);return r?s.jsxs(Oe,{children:[i&&s.jsx(Dr,{outcome:i}),s.jsxs(Qe,{onSubmit:l,children:[s.jsx(yl,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:dr(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),s.jsx(ee,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ie,{type:"submit",children:"OK"})})]})]}):null}function BY(){const{resourceType:e,id:t}=ft();return St({reference:e+"/"+t})?s.jsxs(Oe,{children:[s.jsxs(Ui,{icon:s.jsx(Tl,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",s.jsx("br",{}),s.jsx(Xe,{href:`/forms/${t}`,children:`/forms/${t}`})]}),s.jsx(y2,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function VY(){const e=ae(),{resourceType:t,id:n}=ft(),[r,o]=p.useState(),[i,a]=p.useState();return p.useEffect(()=>{e.readResource(t,n).then(l=>o(Qr(l))).catch(l=>{pe({color:"red",message:Ie(l)})})},[e,t,n]),r?s.jsxs(Oe,{children:[s.jsxs(be,{order:2,children:["Available ",t," profiles"]}),s.jsx(Ae,{children:s.jsxs(s.Fragment,{children:[s.jsx(a_,{resource:r,currentProfile:i,onChange:a}),i?s.jsx(WY,{profile:i,resource:r,onResourceUpdated:l=>o(l)},i.url):s.jsx(he,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const WY=({profile:e,resource:t,onResourceUpdated:n})=>{const r=ae(),[o,i]=p.useState(),[a,l]=p.useState(()=>{var u,d;return(d=(u=t.meta)==null?void 0:u.profile)==null?void 0:d.includes(e.url)}),c=p.useCallback(u=>{i(void 0);const d=Xs(u);a?Ak(d,e.url):V6(d,e.url),r.updateResource(d).then(f=>{n(f),pe({color:"green",message:"Success"})}).catch(f=>{i(mt(f)),pe({color:"red",message:Ie(f),autoClose:!1})})},[r,e.url,n,a]);return s.jsxs(Ae,{children:[s.jsx(mu,{size:"md",checked:a,label:`Conform resource to ${e.title}`,onChange:u=>l(u.currentTarget.checked),"data-testid":"profile-toggle"}),a?s.jsx(kf,{profileUrl:e.url,defaultValue:t,onSubmit:c,outcome:o}):s.jsx("form",{noValidate:!0,onSubmit:u=>{u.preventDefault(),c(t)},children:s.jsx(ee,{justify:"flex-end",mt:"xl",children:s.jsx(ie,{type:"submit",children:"OK"})})})]})},c_={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},HY=Object.keys(c_);function qY(){const e=ae(),{id:t}=ft(),[n,r]=p.useState(),[o,i]=p.useState("create"),[a,l]=p.useState(0),c=e.searchResources("Subscription","status=active&_count=100").read().filter(d=>GY(d,t));function u(){n&&e.createResource({resourceType:"Subscription",status:"active",reason:`Connect bot ${n.name} to questionnaire responses`,criteria:"QuestionnaireResponse?questionnaire=Questionnaire/"+t,channel:{type:"rest-hook",endpoint:ct(n)},...o?{extension:[{url:"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",valueCode:o}]}:void 0}).then(()=>{r(void 0),l(Date.now()),e.invalidateSearches("Subscription"),pe({color:"green",message:"Success"})}).catch(d=>pe({color:"red",message:Ie(d),autoClose:!1}))}return s.jsxs(Oe,{children:[s.jsx(be,{children:"Bots"}),s.jsxs(Ae,{children:[c.length===0&&s.jsx("p",{children:"No bots found."}),c.map(d=>{var f;return s.jsxs("div",{children:[s.jsx("h3",{children:s.jsx(kl,{value:{reference:(f=d.channel)==null?void 0:f.endpoint},link:!0})}),s.jsxs("p",{children:["Criteria: ",d.criteria]})]},d.id)})]}),s.jsx(ln,{}),s.jsxs(Ae,{mt:10,children:[s.jsx(iu,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),s.jsxs(ee,{children:[s.jsx(Ys,{name:"bot",resourceType:"Bot",onChange:d=>r(d)}),s.jsx(ie,{onClick:u,children:"Connect"})]}),s.jsx(ee,{children:s.jsx(Pt,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:HY,onChange:d=>i(c_[d.target.value])})})]}),s.jsx("div",{style:{display:"none"},children:a})]})}function GY(e,t){var o;const n=e.criteria||"",r=((o=e.channel)==null?void 0:o.endpoint)||"";return n.startsWith("QuestionnaireResponse?")&&n.includes(t)&&r.startsWith("Bot/")}function QY(){const{id:e}=ft(),t=Gt(),[n,r]=p.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:oe.EQUALS,value:"Questionnaire/"+e}],fields:["id","_lastUpdated"]});return s.jsx(Oe,{children:s.jsx(ku,{search:n,onClick:o=>t(`/${o.resource.resourceType}/${o.resource.id}`),onChange:o=>r(o.definition),hideFilters:!0,hideToolbar:!0})})}function KY(){const e=ae(),{resourceType:t,id:n}=ft(),r=St({reference:t+"/"+n}),o=p.useCallback(i=>{e.updateResource(Xs(i)).then(()=>{pe({color:"green",message:"Success"})}).catch(a=>{pe({color:"red",message:Ie(a),autoClose:!1})})},[e]);return r?s.jsx(Oe,{children:s.jsx(aq,{onSubmit:o,definition:r})}):null}function YY(){const{resourceType:e,id:t}=ft(),n=St({reference:e+"/"+t});return n?s.jsx(Oe,{children:e==="MeasureReport"?s.jsx(eH,{measureReport:n}):s.jsx(v0,{value:n})}):null}const XY="_container_1ue98_1",JY="_entry_1ue98_14",ZY="_active_1ue98_21",ym={container:XY,entry:JY,active:ZY};function eX(e){const t=ae(),n=St(e.value),[r,o]=p.useState();return p.useEffect(()=>{if(!n)return;const i=z0(n);if(!i)return;const a="reference"in i?i.reference:ct(i);t.search("ServiceRequest","subject="+a).then(l=>{const u=(l.entry??[]).map(d=>d.resource);KR(u),u.reverse(),o(u)}).catch(l=>pe({color:"red",message:Ie(l),autoClose:!1}))},[t,n]),r?s.jsx("div",{"data-testid":"quick-service-requests",className:ym.container,children:r.map(i=>{var a,l,c,u,d,f,h;return s.jsxs("div",{className:rt(ym.entry,{[ym.active]:i.id===(n==null?void 0:n.id)}),children:[s.jsx("p",{children:s.jsx(qe,{to:i,children:tX(i)})}),((l=(a=i.category)==null?void 0:a[0])==null?void 0:l.text)&&s.jsx("p",{children:(c=i.category[0])==null?void 0:c.text}),((f=(d=(u=i.code)==null?void 0:u.coding)==null?void 0:d[0])==null?void 0:f.code)&&s.jsx("p",{children:(h=i.code.coding[0])==null?void 0:h.code}),s.jsx("p",{children:nX(i)})]},i.id)})}):null}function tX(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function nX(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const rX="_container_1l2dh_1",oX={container:rX};function iX(e){var o,i,a,l;const t=St(e.valueSet);if(!t)return null;const n=[""],r=(l=(a=(i=(o=t.compose)==null?void 0:o.include)==null?void 0:i[0])==null?void 0:a.concept)==null?void 0:l.map(c=>c.code);return r&&n.push(...r),e.defaultValue&&!n.includes(e.defaultValue)&&n.push(e.defaultValue),s.jsx("div",{className:oX.container,children:s.jsx(Pt,{defaultValue:e.defaultValue,onChange:c=>e.onChange(c.currentTarget.value),data:n})})}function sX(e){var n,r;const t=St(e.specimen);return t?s.jsxs(ze,{children:[s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Type"}),s.jsx(ze.Value,{children:"Specimen"})]}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Collected"}),s.jsx(ze.Value,{children:Ln((n=t.collection)==null?void 0:n.collectedDateTime)})]}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Specimen Age"}),s.jsx(ze.Value,{children:aX(t)})]}),(r=t.collection)!=null&&r.collectedDateTime&&t.receivedTime?s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Specimen Stability"}),s.jsx(ze.Value,{children:lX(t)})]}):s.jsx(s.Fragment,{})]}):null}function aX(e){var o;const t=(o=e.collection)==null?void 0:o.collectedDateTime;if(!t)return;const n=new Date(t);return u_(d_(n,new Date))}function lX(e){var r;if(!((r=e.collection)!=null&&r.collectedDateTime)||!e.receivedTime)return;const t=new Date(e.collection.collectedDateTime),n=new Date(e.receivedTime);return u_(d_(t,n))}function u_(e){return e.toString().padStart(3,"0")+"D"}function d_(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function cX(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"),t}const uX=[];function dX(){var y,w,C,j,T,E,R;const e=ae(),{resourceType:t,id:n}=ft(),r={reference:t+"/"+n},o=Gt(),[i,a]=p.useState(),l=St(r,a),c=cX(t),[u,d]=p.useState(()=>{const _=window.location.pathname.split("/").pop();return _&&c.map(N=>N.toLowerCase()).includes(_)?_:c[0].toLowerCase()}),f=At();async function h(){var O,F;const N=(F=(O=(await e.readHistory(t,n)).entry)==null?void 0:O.find(z=>!!z.resource))==null?void 0:F.resource;N?m(N):pe({color:"red",message:"No history to restore",autoClose:!1})}function m(_){e.updateResource(Xs(_)).then(()=>{a(void 0),pe({color:"green",message:"Success"})}).catch(N=>{pe({color:"red",message:Ie(N),autoClose:!1})})}if(i)return f7(i)?s.jsxs(Oe,{children:[s.jsx(be,{children:"Deleted"}),s.jsx("p",{children:"The resource was deleted."}),s.jsx(ie,{color:"red",onClick:h,children:"Restore"})]}):s.jsx(Dr,{outcome:i});function g(_){_||(_=c[0].toLowerCase()),d(_),o(`/${t}/${n}/${_}`)}function v(_){const N=l,O=N.orderDetail||[];O.length===0&&O.push({}),O[0].text!==_&&(O[0].text=_,m({...N,orderDetail:O}))}const S=l&&z0(l),b=l&&MK(l),x=(C=(w=(y=e.getUserConfiguration())==null?void 0:y.option)==null?void 0:w.find(_=>_.id==="statusValueSet"))==null?void 0:C.valueString;return s.jsxs(s.Fragment,{children:[(l==null?void 0:l.resourceType)==="ServiceRequest"&&x&&s.jsx(iX,{valueSet:{reference:x},defaultValue:(T=(j=l.orderDetail)==null?void 0:j[0])==null?void 0:T.text,onChange:v},ct(l)+"-"+((R=(E=l.orderDetail)==null?void 0:E[0])==null?void 0:R.text)),l&&s.jsx(eX,{value:l}),l&&s.jsxs(Xn,{children:[S&&s.jsx(n_,{patient:S}),b&&s.jsx(sX,{specimen:b}),t!=="Patient"&&s.jsx(r_,{resource:r}),s.jsx(kr,{children:s.jsx(et,{value:u.toLowerCase(),onChange:g,children:s.jsx(et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:c.map(_=>s.jsx(et.Tab,{value:_.toLowerCase(),children:uX.includes(_)?s.jsxs(ee,{gap:"xs",wrap:"nowrap",children:[_,s.jsx(uu,{color:f.primaryColor,size:"sm",children:"Beta"})]}):_},_))})})})]}),s.jsx(M0,{})]})}function qS(){var b,x,y,w;const e=Gt(),{resourceType:t,id:n,versionId:r,tab:o}=ft(),i=ae(),[a,l]=p.useState(!0),[c,u]=p.useState(),[d,f]=p.useState();if(p.useEffect(()=>{f(void 0),l(!0),i.readHistory(t,n).then(C=>u(C)).then(()=>l(!1)).catch(C=>{f(C),l(!1)})},[i,t,n]),a)return s.jsx(Tr,{});if(!c)return s.jsxs(Oe,{children:[s.jsx(be,{children:"Resource not found"}),s.jsx(qe,{to:`/${t}`,children:"Return to search page"})]});const h=c.entry??[],m=h.findIndex(C=>{var j,T;return((T=(j=C.resource)==null?void 0:j.meta)==null?void 0:T.versionId)===r});if(m===-1)return s.jsxs(Oe,{children:[s.jsx(be,{children:"Version not found"}),s.jsx(qe,{to:`/${t}/${n}`,children:"Return to resource"})]});const g=h[m].resource,v=m<h.length-1?h[m+1].resource:void 0,S="diff";return s.jsxs(et,{value:o||S,onChange:C=>e(`/${t}/${n}/_history/${r}/${C||S}`),children:[s.jsxs(Xn,{children:[s.jsx(Tu,{fluid:!0,p:"md",children:s.jsx(he,{children:`${t} ${n}`})}),s.jsxs(et.List,{children:[s.jsx(et.Tab,{value:"diff",children:"Diff"}),s.jsx(et.Tab,{value:"raw",children:"Raw"})]})]}),s.jsxs(Oe,{children:[d&&s.jsx("pre",{"data-testid":"error",children:JSON.stringify(d,void 0,2)}),s.jsx(et.Panel,{value:"diff",children:v?s.jsxs(s.Fragment,{children:[s.jsxs("ul",{children:[s.jsxs("li",{children:["Current: ",(b=g.meta)==null?void 0:b.versionId]}),s.jsxs("li",{children:["Previous:"," ",s.jsx(qe,{to:`/${t}/${n}/_history/${(x=v.meta)==null?void 0:x.versionId}`,children:(y=v.meta)==null?void 0:y.versionId})]})]}),s.jsx(Oq,{original:v,revised:g})]}):s.jsxs(s.Fragment,{children:[s.jsxs("ul",{children:[s.jsxs("li",{children:["Current: ",(w=g.meta)==null?void 0:w.versionId]}),s.jsx("li",{children:"Previous: (none)"})]}),s.jsx("pre",{children:JSON.stringify(g,void 0,2)})]})}),s.jsx(et.Panel,{value:"raw",children:s.jsx("pre",{children:JSON.stringify(g,void 0,2)})})]})]})}function fX(){const{resourceType:e,id:t}=ft(),n=Gt(),[r,o]=p.useState({resourceType:"Subscription",filters:[{code:"url",operator:oe.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return s.jsx(Oe,{children:s.jsx(BW,{search:r,onClick:i=>n(`/${i.resource.resourceType}/${i.resource.id}`),onChange:i=>o(i.definition),hideFilters:!0})})}function hX(e){const t=ae(),{resource:n,opened:r,onClose:o}=e,[i,a]=p.useState(!1),[l,c]=p.useState(),[u,d]=p.useState(!1),f=p.useCallback(async()=>{if(n!=null&&n.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:i&&l?ct(l):void 0,verbose:u}),pe({color:"green",message:"Done"}),o()}catch(h){pe({color:"red",message:Ie(h),autoClose:!1})}},[t,n,o,i,l,u]);return s.jsx(mn,{opened:r,onClose:o,title:"Resend Subscriptions",children:s.jsx(Qe,{onSubmit:f,children:s.jsxs(Ae,{children:[s.jsx(kn,{label:"Choose subscription (all subscriptions by default)",onChange:h=>a(h.currentTarget.checked)}),i&&s.jsx(Ys,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:c}),s.jsx(kn,{label:"Verbose mode",onChange:h=>d(h.currentTarget.checked)}),s.jsx(ee,{justify:"flex-end",children:s.jsx(ie,{type:"submit",children:"Resend"})})]})})})}function GS(){const e=ae(),t=Gh(),{resourceType:n,id:r}=ft(),o={reference:n+"/"+r},[i,a]=p.useState(),l=Bf(!1);function c(x,y){return e.updateResource({...x,priority:y})}function u(x,y){c(x,"stat").then(y).catch(console.error)}function d(x,y){c(x,"routine").then(y).catch(console.error)}function f(x){t(`/${x.resourceType}/${x.id}`)}function h(x){t(`/${x.resourceType}/${x.id}/edit`)}function m(x){t(`/${x.resourceType}/${x.id}/delete`)}function g(x){a(x),l[1].open()}function v(x){var y;t(`/${x.resourceType}/${x.id}/_history/${(y=x.meta)==null?void 0:y.versionId}`)}function S(x,y){e.post(e.fhirUrl(x.resourceType,x.id,"$aws-textract"),{}).then(y).catch(console.error)}function b(x){var D;const{primaryResource:y,currentResource:w,reloadTimeline:C}=x,j=w.resourceType===y.resourceType&&w.id===y.id,T=w.resourceType==="Communication"&&w.priority!=="stat",E=w.resourceType==="Communication"&&w.priority==="stat",R=j,_=!j,N=!j,O=!j,F=(D=e.getProjectMembership())==null?void 0:D.admin,z=F,H=QK()&&(w.resourceType==="DocumentReference"||w.resourceType==="Media");return s.jsxs(Z.Dropdown,{children:[s.jsx(Z.Label,{children:"Resource"}),T&&s.jsx(Z.Item,{leftSection:s.jsx(Qz,{size:14}),onClick:()=>u(w,C),"aria-label":`Pin ${ct(w)}`,children:"Pin"}),E&&s.jsx(Z.Item,{leftSection:s.jsx(Kz,{size:14}),onClick:()=>d(w,C),"aria-label":`Unpin ${ct(w)}`,children:"Unpin"}),_&&s.jsx(Z.Item,{leftSection:s.jsx(Fw,{size:14}),onClick:()=>f(w),"aria-label":`Details ${ct(w)}`,children:"Details"}),R&&s.jsx(Z.Item,{leftSection:s.jsx(Fw,{size:14}),onClick:()=>v(w),"aria-label":`Details ${ct(w)}`,children:"Details"}),N&&s.jsx(Z.Item,{leftSection:s.jsx(lR,{size:14}),onClick:()=>h(w),"aria-label":`Edit ${ct(w)}`,children:"Edit"}),F&&s.jsxs(s.Fragment,{children:[s.jsx(Z.Divider,{}),s.jsx(Z.Label,{children:"Admin"}),z&&s.jsx(Z.Item,{leftSection:s.jsx(eU,{size:14}),onClick:()=>g(w),"aria-label":`Resend Subscriptions ${ct(w)}`,children:"Resend Subscriptions"})]}),H&&s.jsxs(s.Fragment,{children:[s.jsx(Z.Divider,{}),s.jsx(Z.Label,{children:"AWS AI"}),s.jsx(Z.Item,{leftSection:s.jsx(lU,{size:14}),onClick:()=>S(w,C),"aria-label":`AWS Textract ${ct(w)}`,children:"AWS Textract"})]}),O&&s.jsxs(s.Fragment,{children:[s.jsx(Z.Divider,{}),s.jsx(Z.Label,{children:"Danger zone"}),s.jsx(Z.Item,{color:"red",leftSection:s.jsx(i0,{size:14}),onClick:()=>m(w),"aria-label":`Delete ${ct(w)}`,children:"Delete"})]})]})}return s.jsxs(s.Fragment,{children:[n==="Encounter"&&s.jsx(XV,{encounter:o,getMenu:b}),n==="Patient"&&s.jsx(tH,{patient:o,getMenu:b}),n==="ServiceRequest"&&s.jsx(Vq,{serviceRequest:o,getMenu:b}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&s.jsx(YV,{resource:o,getMenu:b}),s.jsx(hX,{resource:i,opened:l[0],onClose:l[1].close},`resend-subscriptions-${i==null?void 0:i.id}`)]})}function pX(e){const{opened:t,close:n,version:r,loadingStatus:o,handleStatus:i,handleUpgrade:a}=e,[l,c]=p.useState();return p.useEffect(()=>{t&&(l||cz().then(c).catch(console.error),i())},[t,l,i]),l&&r&&!o?r==="unknown"?s.jsx("p",{children:"Unable to determine the current version of the agent. Check the network connectivity of the agent."}):r.startsWith(l)?s.jsxs("p",{children:["This agent is already on the latest version (",l,")."]}):s.jsxs(s.Fragment,{children:[s.jsxs("p",{children:["Are you sure you want to upgrade this agent from version ",r," to version ",l,"?"]}),s.jsx(ie,{onClick:()=>{a(),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"})]}):s.jsx(Tr,{})}function mX(){const e=ae(),{id:t}=ft(),n=p.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,o]=p.useState(!1),[i,a]=p.useState(!1),[l,c]=p.useState(!1),[u,d]=p.useState(),[f,h]=p.useState(),[m,g]=p.useState(),[v,S]=p.useState(),[b,x]=p.useState(!1),[y,w]=p.useState(!1),[C,{open:j,close:T}]=Bf(!1);p.useEffect(()=>{if(r||i||l||b){w(!0);return}w(!1)},[r,i,l,b]);const E=p.useCallback(()=>{o(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(z=>{var H,D,k,P,I,L;d((D=(H=z.parameter)==null?void 0:H.find($=>$.name==="status"))==null?void 0:D.valueCode),h((P=(k=z.parameter)==null?void 0:k.find($=>$.name==="version"))==null?void 0:P.valueString),g((L=(I=z.parameter)==null?void 0:I.find($=>$.name==="lastUpdated"))==null?void 0:L.valueInstant)}).catch(z=>F(Ie(z))).finally(()=>o(!1))},[e,t]),R=p.useCallback(z=>{const H=z.host,D=z.pingCount||1;H&&(x(!0),e.pushToAgent(n,H,`PING ${D}`,sn.PING,!0).then(k=>S(k)).catch(k=>F(Ie(k))).finally(()=>x(!1)))},[e,n]),_=p.useCallback(()=>{a(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(z=>{O("Agent config reloaded successfully.")}).catch(z=>F(Ie(z))).finally(()=>a(!1))},[e,t]),N=p.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$upgrade"),{cache:"reload"}).then(z=>{O("Agent upgraded successfully.")}).catch(z=>F(Ie(z))).finally(()=>c(!1))},[e,t]);function O(z){pe({color:"green",title:"Success",icon:s.jsx(Ks,{size:"1rem"}),message:z})}function F(z){pe({color:"red",title:"Error",message:z,autoClose:!1})}return s.jsxs(Oe,{children:[s.jsx(mn,{opened:C,onClose:T,title:"Upgrade Agent",centered:!0,children:s.jsx(pX,{opened:C,close:T,version:f,loadingStatus:r,handleStatus:E,handleUpgrade:N})}),s.jsx(be,{order:1,children:"Agent Tools"}),s.jsxs("div",{style:{marginBottom:10},children:["Agent: ",s.jsx(kl,{value:n,link:!0})]}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Agent Status"}),s.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."}),s.jsx(ie,{onClick:E,loading:r,disabled:y&&!r,children:"Get Status"}),!r&&u&&s.jsx(fe,{children:s.jsxs(fe.Tbody,{children:[s.jsxs(fe.Tr,{children:[s.jsx(fe.Td,{children:"Status"}),s.jsx(fe.Td,{children:s.jsx(g0,{status:u})})]}),s.jsxs(fe.Tr,{children:[s.jsx(fe.Td,{children:"Version"}),s.jsx(fe.Td,{children:f})]}),s.jsxs(fe.Tr,{children:[s.jsx(fe.Td,{children:"Last Updated"}),s.jsx(fe.Td,{children:Ln(m,void 0,{timeZoneName:"longOffset"})})]})]})}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Reload Config"}),s.jsx("p",{children:"Reload the configuration of this agent, syncing it with the current version of the Agent resource on the Medplum server."}),s.jsx(ie,{onClick:_,loading:i,disabled:y&&!i,"aria-label":"Reload config",children:"Reload Config"}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Upgrade Agent"}),s.jsx("p",{children:"Upgrade the version of this agent, to either the latest (default) or a specified version."}),s.jsx(ie,{onClick:j,loading:l,disabled:y&&!l,"aria-label":"Upgrade agent",children:"Upgrade"}),s.jsx(ln,{my:"lg"}),s.jsx(be,{order:2,children:"Ping from Agent"}),s.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."}),s.jsx(Qe,{onSubmit:R,children:s.jsxs(ee,{children:[s.jsx(ye,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:s.jsx(en,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:b,disabled:y&&!b,children:s.jsx(nU,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),s.jsx(gx,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!b&&v&&s.jsxs(s.Fragment,{children:[s.jsx(be,{order:5,mt:"sm",mb:0,children:"Last Ping"}),s.jsx("pre",{children:v})]})]})}function gX(){return s.jsx(pQ,{children:s.jsxs(Ee,{errorElement:s.jsx(RK,{}),children:[s.jsx(Ee,{path:"/signin",element:s.jsx(eY,{})}),s.jsx(Ee,{path:"/oauth",element:s.jsx(KK,{})}),s.jsx(Ee,{path:"/resetpassword",element:s.jsx(XK,{})}),s.jsx(Ee,{path:"/setpassword/:id/:secret",element:s.jsx(ZK,{})}),s.jsx(Ee,{path:"/register",element:s.jsx(YK,{})}),s.jsx(Ee,{path:"/changepassword",element:s.jsx(TK,{})}),s.jsx(Ee,{path:"/security",element:s.jsx(JK,{})}),s.jsx(Ee,{path:"/mfa",element:s.jsx(GK,{})}),s.jsx(Ee,{path:"/batch",element:s.jsx(CK,{})}),s.jsx(Ee,{path:"/bulk/:resourceType",element:s.jsx(EK,{})}),s.jsx(Ee,{path:"/smart",element:s.jsx(tY,{})}),s.jsx(Ee,{path:"/forms/:id",element:s.jsx(LK,{})}),s.jsx(Ee,{path:"/admin/super",element:s.jsx(pY,{})}),s.jsx(Ee,{path:"/admin/config",element:s.jsx(uY,{})}),s.jsxs(Ee,{path:"/admin",element:s.jsx(dY,{}),children:[s.jsx(Ee,{path:"patients",element:s.jsx(cY,{})}),s.jsx(Ee,{path:"bots/new",element:s.jsx(oY,{})}),s.jsx(Ee,{path:"bots",element:s.jsx(nY,{})}),s.jsx(Ee,{path:"clients/new",element:s.jsx(iY,{})}),s.jsx(Ee,{path:"clients",element:s.jsx(rY,{})}),s.jsx(Ee,{path:"details",element:s.jsx(BS,{})}),s.jsx(Ee,{path:"invite",element:s.jsx(lY,{})}),s.jsx(Ee,{path:"users",element:s.jsx(mY,{})}),s.jsx(Ee,{path:"project",element:s.jsx(BS,{})}),s.jsx(Ee,{path:"secrets",element:s.jsx(fY,{})}),s.jsx(Ee,{path:"sites",element:s.jsx(hY,{})}),s.jsx(Ee,{path:"members/:membershipId",element:s.jsx(aY,{})})]}),s.jsx(Ee,{path:"/lab/assays",element:s.jsx(gY,{})}),s.jsx(Ee,{path:"/lab/panels",element:s.jsx(vY,{})}),s.jsx(Ee,{path:"/:resourceType/:id/_history/:versionId/:tab",element:s.jsx(qS,{})}),s.jsx(Ee,{path:"/:resourceType/:id/_history/:versionId",element:s.jsx(qS,{})}),s.jsxs(Ee,{path:"/:resourceType/new",element:s.jsx(kK,{}),children:[s.jsx(Ee,{index:!0,element:s.jsx(vm,{})}),s.jsx(Ee,{path:"form",element:s.jsx(vm,{})}),s.jsx(Ee,{path:"json",element:s.jsx(zY,{})}),s.jsx(Ee,{path:"profiles",element:s.jsx(vm,{})})]}),s.jsxs(Ee,{path:"/:resourceType/:id",element:s.jsx(dX,{}),children:[s.jsx(Ee,{index:!0,element:s.jsx(GS,{})}),s.jsx(Ee,{path:"apply",element:s.jsx(xY,{})}),s.jsx(Ee,{path:"apps",element:s.jsx(bY,{})}),s.jsx(Ee,{path:"event",element:s.jsx(SY,{})}),s.jsx(Ee,{path:"blame",element:s.jsx(jY,{})}),s.jsx(Ee,{path:"bots",element:s.jsx(qY,{})}),s.jsx(Ee,{path:"builder",element:s.jsx(IY,{})}),s.jsx(Ee,{path:"checklist",element:s.jsx(AY,{})}),s.jsx(Ee,{path:"delete",element:s.jsx(NY,{})}),s.jsx(Ee,{path:"details",element:s.jsx(LY,{})}),s.jsx(Ee,{path:"edit",element:s.jsx($Y,{})}),s.jsx(Ee,{path:"editor",element:s.jsx(_Y,{})}),s.jsx(Ee,{path:"history",element:s.jsx(FY,{})}),s.jsx(Ee,{path:"json",element:s.jsx(UY,{})}),s.jsx(Ee,{path:"preview",element:s.jsx(BY,{})}),s.jsx(Ee,{path:"responses",element:s.jsx(QY,{})}),s.jsx(Ee,{path:"report",element:s.jsx(YY,{})}),s.jsx(Ee,{path:"ranges",element:s.jsx(KY,{})}),s.jsx(Ee,{path:"subscriptions",element:s.jsx(fX,{})}),s.jsx(Ee,{path:"timeline",element:s.jsx(GS,{})}),s.jsx(Ee,{path:"tools",element:s.jsx(mX,{})}),s.jsx(Ee,{path:"profiles",element:s.jsx(VY,{})})]}),s.jsx(Ee,{path:"/:resourceType",element:s.jsx(US,{})}),s.jsx(Ee,{path:"/",element:s.jsx(US,{})})]})})}function vX(){const e=ae(),t=e.getUserConfiguration(),n=ri(),[r]=O0();return e.isLoading()?s.jsx(Tr,{}):s.jsx(nB,{logo:s.jsx(Zr,{size:24}),pathname:n.pathname,searchParams:r,version:F8,menus:yX(t),displayAddBookmark:!!(t!=null&&t.id),children:s.jsx(p.Suspense,{fallback:s.jsx(Tr,{}),children:s.jsx(gX,{})})})}function yX(e){var n;const t=((n=e==null?void 0:e.menu)==null?void 0:n.map(r=>{var o;return{title:r.title,links:((o=r.link)==null?void 0:o.map(i=>({label:i.name,href:i.target,icon:xX(i.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:s.jsx(Vz,{})}]}),t}const QS={Patient:iU,Practitioner:Uz,Organization:Iz,ServiceRequest:Jz,DiagnosticReport:tU,Questionnaire:zz,admin:Rz,AccessPolicy:Bz,Subscription:cU,batch:Gz,Observation:qz};function xX(e){try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in QS){const n=QS[t];return s.jsx(n,{})}}catch{}return s.jsx(Fh,{w:30})}"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.getRegistrations().then(e=>Promise.all(e.map(t=>t.unregister()))).catch(e=>console.error("SW registration failed: ",e))});async function bX(){const e=Iu(),t=new Jk({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=yQ([{path:"*",element:s.jsx(vX,{})}]),o=a=>r.navigate(a);k2(document.getElementById("root")).render(s.jsx(p.StrictMode,{children:s.jsx(uz,{medplum:t,navigate:o,children:s.jsxs(_j,{theme:n,children:[s.jsx(ei,{position:"bottom-right"}),s.jsx(PQ,{router:r})]})})}))}bX().catch(console.error);
582
- //# sourceMappingURL=index-vRi7vk4h.js.map
582
+ //# sourceMappingURL=index-BG7zHNvz.js.map