@medplum/app 3.2.7 → 3.2.8

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 Ba={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let lw=!1;function m8(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Ba.Event=globalThis.Event,Ba.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Ba.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function g8(e,t){if(!e)throw new Error(t)}function id(e){return new e.constructor(e.type,e)}const Zi={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 cw=!1;class hi extends Mh{constructor(t,n,r={}){lw||(m8(),lw=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",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=Zi.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),i),g8(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(id(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(id(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(id(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(id(o))},this._url=t,this._protocols=n,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),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 hi.CONNECTING}get OPEN(){return hi.OPEN}get CLOSING(){return hi.CLOSING}get CLOSED(){return hi.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?hi.CLOSED:hi.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=Zi.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=Zi.reconnectionDelayGrowFactor,minReconnectionDelay:n=Zi.minReconnectionDelay,maxReconnectionDelay:r=Zi.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=Zi.maxRetries,connectionTimeout:n=Zi.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"&&!cw&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),cw=!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 Ba.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Ba.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Ba.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 v8=5e3;class jg extends Mh{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 y8{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new jg(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class x8{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof Ck))throw new qe(_t("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new qe(_t("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 hi(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 jg,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??v8,this.setupWebSocketListeners()}setupWebSocketListeners(){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=nl(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(nl(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 qe(U$(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))})}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 ${st(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 qe(_t("Failed to get token"));if(!i)throw new qe(_t("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(Mi(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!Mi(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(De(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 y8(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()}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new jg(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const b8="3.2.7-a4111e333",w8=on.FHIR_JSON+", */*; q=0.1",S8="https://api.medplum.com/",j8=1e3,C8=6e4,E8=0,T8="Binary/",uw={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]};class Ck extends Mh{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)??P8(),this.storage=(t==null?void 0:t.storage)??new h8,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=ok((t==null?void 0:t.baseUrl)??S8),this.fhirBaseUrl=Eo(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Eo(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Eo(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Eo(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),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.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?E8:C8),this.cacheTime>0?this.requestCache=new wk((t==null?void 0:t.resourceCacheSize)??j8):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}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=Eo(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 Fr(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,on.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(Eo(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=S6(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 Fr((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 Fr(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 Fr(this.search(t,n,r).then(hw));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 hw(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 uw;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 Fr(Promise.reject(new Error("Missing reference")));if(r==="system")return new Fr(Promise.resolve(uw));const[o,i]=r.split("/");return!o||!i?new Fr(Promise.reject(new Error("Invalid reference"))):this.readResource(o,i,n)}requestSchema(t){if(GP(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Fr((async()=>{const i=`{
101
+ */const Ba={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let lw=!1;function m8(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Ba.Event=globalThis.Event,Ba.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Ba.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function g8(e,t){if(!e)throw new Error(t)}function id(e){return new e.constructor(e.type,e)}const Zi={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 cw=!1;class hi extends Mh{constructor(t,n,r={}){lw||(m8(),lw=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",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=Zi.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),i),g8(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(id(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(id(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(id(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(id(o))},this._url=t,this._protocols=n,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),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 hi.CONNECTING}get OPEN(){return hi.OPEN}get CLOSING(){return hi.CLOSING}get CLOSED(){return hi.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?hi.CLOSED:hi.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=Zi.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=Zi.reconnectionDelayGrowFactor,minReconnectionDelay:n=Zi.minReconnectionDelay,maxReconnectionDelay:r=Zi.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=Zi.maxRetries,connectionTimeout:n=Zi.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"&&!cw&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),cw=!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 Ba.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Ba.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Ba.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 v8=5e3;class jg extends Mh{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 y8{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new jg(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class x8{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof Ck))throw new qe(_t("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new qe(_t("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 hi(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 jg,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??v8,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=nl(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(nl(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 qe(U$(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 ${st(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 qe(_t("Failed to get token"));if(!i)throw new qe(_t("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(Mi(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!Mi(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(De(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 y8(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 jg(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const b8="3.2.8-b2b7ed8c5",w8=on.FHIR_JSON+", */*; q=0.1",S8="https://api.medplum.com/",j8=1e3,C8=6e4,E8=0,T8=3e5,P8="Binary/",uw={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]};class Ck extends Mh{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)??k8(),this.storage=(t==null?void 0:t.storage)??new h8,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=ok((t==null?void 0:t.baseUrl)??S8),this.fhirBaseUrl=Eo(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Eo(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Eo(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Eo(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),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)??T8,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?E8:C8),this.cacheTime>0?this.requestCache=new wk((t==null?void 0:t.resourceCacheSize)??j8):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}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=Eo(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 Fr(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,on.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(Eo(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=S6(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 Fr((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 Fr(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 Fr(this.search(t,n,r).then(hw));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 hw(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 uw;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 Fr(Promise.reject(new Error("Missing reference")));if(r==="system")return new Fr(Promise.resolve(uw));const[o,i]=r.split("/");return!o||!i?new Fr(Promise.reject(new Error("Invalid reference"))):this.readResource(o,i,n)}requestSchema(t){if(GP(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Fr((async()=>{const i=`{
102
102
  StructureDefinitionList(name: "${t}") {
103
103
  resourceType,
104
104
  name,
@@ -138,22 +138,22 @@ Error generating stack: `+i.message+`
138
138
  expression,
139
139
  target
140
140
  }
141
- }`.replace(/\s+/g," "),a=await this.graphql(i);qb(a.data.StructureDefinitionList);for(const l of a.data.SearchParameterList)N6(l)})());return this.setCacheEntry(n,o),o}requestProfileSchema(t,n){if(!(n!=null&&n.expandProfile)&&jx(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 Fr((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(),{});qb(l)}else{const a=await this.searchOne("StructureDefinition",{url:t,_sort:"-_lastUpdated"});if(!a){console.warn(`No StructureDefinition found for ${t}!`);return}qP(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=pw(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=pw(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 Error("Request aborted")),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 qe(ht(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),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=_8(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=Et(t),a=t.subject),t.resourceType==="ServiceRequest"&&(i=t.encounter,a=t.subject),t.resourceType==="Patient"&&(a=Et(t)),this.createResource({resourceType:"Communication",status:"completed",basedOn:[Et(t)],encounter:i,subject:a,sender:o?Et(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,on.JSON,n)}graphql(t,n,r,o){return this.post(this.fhirUrl("$graphql"),{query:t,operationName:n,variables:r},on.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",nl(t),"$push"),{destination:typeof n=="string"?n:st(n),body:r,contentType:o,waitForResponse:i},on.FHIR_JSON,a)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(t){var n,r;(!((n=this.sessionDetails)!=null&&n.profile)||st(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=d8(t),this.medplumServer=u8(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.dispatchEvent({type:"profileRefreshing"}),this.get("auth/me").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"}),this.dispatchEvent({type:"profileRefreshed"}),t(r.profile)}).catch(n)}),this.profilePromise):Promise.resolve(void 0)}isLoading(){return!this.isInitialized||!!this.profilePromise}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(T8)&&(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=Et(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 f8(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 Fr(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 qe(B$);const c=await this.parseBody(i,l);if(i.status===200&&r.followRedirectOnOk||i.status===201&&r.followRedirectOnCreated){const u=await fw(i,c);if(u)return this.request("GET",u,{...r,body:void 0})}if(i.status===202&&r.pollStatusOnAccepted){const d=await fw(i,c)??o.statusUrl;if(d)return this.pollStatus(d,r,o)}if(i.status>=400)throw new qe(ht(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=Eo(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 ew(o)}throw new Error("Unreachable")}logRequest(t,n){if(console.log(`> ${n.method} ${t}`),n.headers){const r=n.headers;for(const o of Nc(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 ew(i),r.pollCount++}return this.request("GET",t,o,r)}async executeAutoBatch(){var o,i;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,Eo(this.fhirBaseUrl,a.url),a.options))}catch(l){a.reject(new qe(ht(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&&!UP(c.response.outcome)?l.reject(new qe(c.response.outcome)):l.resolve(c==null?void 0:c.resource)}}addFetchOptionsDefaults(t){this.setRequestHeader(t,"X-Medplum","extended"),this.setRequestHeader(t,"Accept",w8,!0),t.body&&this.setRequestHeader(t,"Content-Type",on.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.constructor.name==="Blob")||typeof File<"u"&&(n instanceof File||n.constructor.name==="File")||typeof Uint8Array<"u"&&(n instanceof Uint8Array||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 Error("Unauthenticated")))}async startPkce(){const t=ow();sessionStorage.setItem("pkceState",t);const n=ow();sessionStorage.setItem("codeVerifier",n);const r=await QF(n),o=g6(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??dw()),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)??dw()),typeof sessionStorage<"u"){const o=sessionStorage.getItem("codeVerifier");o&&r.set("code_verifier",o)}return this.fetchTokens(r)}refreshIfExpired(){return!this.refreshPromise&&this.accessTokenExpires!==void 0&&this.accessTokenExpires<Date.now()&&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=GF(t+":"+n)}async fhircastSubscribe(t,n){if(!(typeof t=="string"&&t!==""))throw new qe(_t("Invalid topic provided. Topic must be a valid string."));if(!(typeof n=="object"&&Array.isArray(n)&&n.length>0))throw new qe(_t("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("/fhircast/STU3",iw(r),on.FORM_URL_ENCODED))["hub.channel.endpoint"];if(!i)throw new Error("Invalid response!");return r.endpoint=i,r}async fhircastUnsubscribe(t){if(!$x(t))throw new qe(_t("Invalid topic or subscriptionRequest. SubscriptionRequest must be an object."));if(!(t.endpoint&&typeof t.endpoint=="string"&&t.endpoint.startsWith("ws")))throw new qe(_t("Provided subscription request must have an endpoint in order to unsubscribe."));t.mode="unsubscribe",await this.post("/fhircast/STU3",iw(t),on.FORM_URL_ENCODED)}fhircastConnect(t){return new a8(t)}async fhircastPublish(t,n,r,o){return t8(n)?this.post(`/fhircast/STU3/${t}`,aw(t,n,r,o),on.JSON):(n8(n),this.post(`/fhircast/STU3/${t}`,aw(t,n,r),on.JSON))}async fhircastGetContext(t){return this.get(`/fhircast/STU3/${t}`)}async invite(t,n){return this.post("admin/projects/"+t+"/invite",n)}async fetchTokens(t){const n={method:"POST",headers:{"Content-Type":on.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 qe(Ri(a.error_description))}catch(a){throw new qe(Ri("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(c8(n)){const r=Fx(n);if(Date.now()>=r.exp*1e3)throw this.clearActiveLogin(),new Error("Token expired");if(r.cid){if(r.cid!==this.clientId)throw this.clearActiveLogin(),new Error("Token was not issued for this audience")}else if(this.clientId&&r.client_id!==this.clientId)throw this.clearActiveLogin(),new Error("Token was not issued for this audience")}return this.setActiveLogin({accessToken:n,refreshToken:t.refresh_token,project:t.project,profile:t.profile})}setupStorageListener(){try{window.addEventListener("storage",t=>{(t.key===null||t.key==="activeLogin")&&window.location.reload()})}catch{}}getSubscriptionManager(){return this.subscriptionManager||(this.subscriptionManager=new x8(this,w6(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 P8(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}function dw(){return typeof window>"u"?"":window.location.protocol+"//"+window.location.host+"/"}async function fw(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(_h(t)&&((i=(o=t.issue)==null?void 0:o[0])!=null&&i.diagnostics))return t.issue[0].diagnostics}function hw(e){var n;const t=((n=e.entry)==null?void 0:n.map(r=>r.resource))??[];return Object.assign(t,{bundle:e})}function k8(e){return kn(e)&&"data"in e&&"contentType"in e}function pw(e,t,n,r){return k8(e)?e:{data:e,filename:t,contentType:n,onProgress:r}}function R8(e){return kn(e)&&"docDefinition"in e}function _8(e,t,n,r){return R8(e)?e:{docDefinition:e,filename:t,tableLayouts:n,fonts:r}}function rl({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=D8(t,n,e,!!o);const l=xg(t,".",2)[1];a=I8(a,i,l),a=A8(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=xg(f,".",2)[1];if(h){if(!d[h]){const m=mf(h,i==null?void 0:i.hiddenFields);d[h]={hidden:m,readonly:m||mf(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 D8(e,t,n,r){const o=Object.create(null);if(n)for(const[a,l]of Object.entries(n.elementsByPath)){const c=Ac(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 I8(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])=>!mf(r+i,t.hiddenFields)))}function A8(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))mf(o+a,t.readonlyFields)?r[a]={...l,readonly:!0}:r[a]=l;return r}function mf(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 Ek(e){return e.type!==void 0&&e.type.length>0}function N8(e,t,n,r){var i;const o=V7(e,t.path,{profileUrl:r});if(o){const a=((i=n.typeSchema)==null?void 0:i.elements)??n.elements;return o.some(l=>q7(l,t,n,a))??!1}return console.assert(!1,"getNestedProperty[%s] in isDiscriminatorComponentMatch missed",t.path),!1}function Tk(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 N8(l,c,a,((u=a.typeSchema)==null?void 0:u.url)??r)}))return a.name}}class M8{constructor(t,n,r){if(t.type===void 0)throw new Error("schema must include a type");this.rootSchema=t;const o=rl({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(!Bt(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=O8(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);Bt((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(!Ek(l))continue;const c=(a=(i=l.type.find(u=>Bt(u.profile)))==null?void 0:i.profile)==null?void 0:a[0];if(Bt(c)){const u=yl(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;Bt(a)&&(i=rl({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 O8(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 Gp="__sliceName";function L8(e,t){const n=new $8(e,e.resourceType,"resource");return new M8(t,n).crawlResource(),n.getDefaultValue()}function mw(e,t,n){for(const[r,o]of Object.entries(t)){if(n===void 0||n===r){gf(e,r,o,t);continue}const i=Ac(n,r);i!==void 0&&gf(e,i,o,t)}return e}class $8{constructor(t,n,r){this.schemaStack=[],this.valueStack=[],this.rootValue=Xr(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=Ac(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){F8(d,a,n,r.elements),gf(d,a,n,r.elements);const f=Eg(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=Ac(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=Eg(a,i,n,r.elements);if(Array.isArray(l))for(let c=l.length-1;c>=0;c--){const u=l[c];Bt(u)||l.splice(c,1)}Gt(l)&&Cg(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[Gp]??Tk(i,[n],r.discriminator,this.schema.url))===n.name&&o.push(i);for(let i=o.length;i<n.min;i++)if(Px(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];Gp in o&&delete o[Gp]}}getDefaultValue(){return this.rootValue}}function F8(e,t,n,r){const o=Eg(e,t,n,r);n.min>0&&o===void 0&&Px(n.type[0].code)&&(n.isArray?Cg(e,[Object.create(null)],t,n):Cg(e,Object.create(null),t,n))}function Cg(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]",nn(i))}t===void 0?delete e[o]:e[o]=t}function Eg(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]",nn(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(kn(i)){if(i[c]===void 0)return;i=i[c]}else return}return a}function gf(e,t,n,r){if(!(n.fixed||n.pattern))return e;if(Array.isArray(e))return e.map(l=>gf(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]",nn(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]=Pk(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 Pk(e,t){if(Array.isArray(t)&&(Array.isArray(e)||e===void 0))return((e==null?void 0:e.length)??0)>0?e:Xr(t);if(kn(t)&&(kn(e)&&!Array.isArray(e)||e===void 0)){const n=Xr(e)??Object.create(null);for(const r of Object.keys(t))n[r]=Pk(n[r],t[r]);return n}return e}const kk=p.createContext(void 0);function Oh(){return p.useContext(kk)}function se(){return Oh().medplum}function Lh(){return Oh().navigate}function $h(){return Oh().profile}const gw=["change","storageInitialized","storageInitFailed","profileRefreshing","profileRefreshed"];function z8(e){const t=e.medplum,n=e.navigate??B8,[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 gw)t.addEventListener(l,a);return()=>{for(const l of gw)t.removeEventListener(l,a)}},[t]);const i=p.useMemo(()=>({...r,medplum:t,navigate:n}),[r,t,n]);return s.jsx(kk.Provider,{value:i,children:e.children})}function B8(e){window.location.assign(e)}const vw=new Map,Rk=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=vw.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 vw.set(t,e),e},[e]);function wt(e,t){const n=se(),[r,o]=p.useState(()=>yw(n,e)),i=p.useCallback(a=>{Mi(a,r)||o(a)},[r]);return p.useEffect(()=>{let a=!0;const l=yw(n,e);return!l&&Qs(e)?n.readReference(e).then(c=>{a&&i(c)}).catch(c=>{a&&(i(void 0),t&&t(ht(c)))}):i(l),()=>a=!1},[n,e,i,t]),r}function yw(e,t){if(t){if(ni(t))return t;if(Qs(t))return e.getCachedReference(t)}}function U8(e,t){return _k("searchOne",e,t)}function ol(e,t){return _k("searchResources",e,t)}function _k(e,t,n){const r=se(),[o,i]=p.useState(),[a,l]=p.useState(!0),[c,u]=p.useState(),[d,f]=p.useState();return p.useEffect(()=>{const h=r.fhirSearchUrl(t,n).toString();h!==o&&(i(h),r[e](t,n).then(m=>{l(!1),u(m),f(z$)}).catch(m=>{l(!1),u(void 0),f(ht(m))}))},[r,e,t,n,o]),[c,a,d]}function V8(e){const t=e.value;return t?s.jsx(s.Fragment,{children:C6(t)}):null}const Dk=["meta","implicitRules","contained","extension","modifierExtension"],Ik=["language","text"],bt=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});bt.displayName="ElementsContext";const zx=["extension","modifierExtension"],W8=["id",...Dk].filter(e=>!zx.includes(e));function H8(e){return Object.entries(e).filter(([n,r])=>{var o;return!Bt(r.type)||r.max===0||r.path.toLowerCase().endsWith("extension.url")&&r.fixed||zx.includes(n)&&!Bt((o=r.slicing)==null?void 0:o.slices)||W8.includes(n)?!1:!(Ik.includes(n)&&r.path.split(".").length===2||n.includes("."))})}function xw(e,t){return e.line&&e.line.length>t?e.line[t]:""}function bw(e,t,n){const r=e.line||[];for(;r.length<=t;)r.push("");return r[t]=n,{...e,line:r}}function q8(e){const[t,n]=p.useState(e.defaultValue||{}),r=p.useRef();r.current=t;const{getExtendedProps:o}=p.useContext(bt),[i,a,l,c,u,d,f]=p.useMemo(()=>["use","type","line1","line2","city","state","postalCode"].map(x=>o(e.path+"."+x)),[o,e.path]);function h(x){n(x),e.onChange&&e.onChange(x)}function m(x){h({...r.current,use:x})}function g(x){h({...r.current,type:x})}function v(x){h(bw(r.current||{},0,x))}function S(x){h(bw(r.current||{},1,x))}function y(x){h({...r.current,city:x})}function w(x){h({...r.current,state:x})}function b(x){h({...r.current,postalCode:x})}return s.jsxs(te,{gap:"xs",wrap:"nowrap",grow:!0,children:[s.jsx(It,{disabled:e.disabled||(i==null?void 0:i.readonly),"data-testid":"address-use",defaultValue:t.use,onChange:x=>m(x.currentTarget.value),data:["","home","work","temp","old","billing"]}),s.jsx(It,{disabled:e.disabled||(a==null?void 0:a.readonly),"data-testid":"address-type",defaultValue:t.type,onChange:x=>g(x.currentTarget.value),data:["","postal","physical","both"]}),s.jsx(ve,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"Line 1",defaultValue:xw(t,0),onChange:x=>v(x.currentTarget.value)}),s.jsx(ve,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Line 2",defaultValue:xw(t,1),onChange:x=>S(x.currentTarget.value)}),s.jsx(ve,{disabled:e.disabled||(u==null?void 0:u.readonly),placeholder:"City",defaultValue:t.city,onChange:x=>y(x.currentTarget.value)}),s.jsx(ve,{disabled:e.disabled||(d==null?void 0:d.readonly),placeholder:"State",defaultValue:t.state,onChange:x=>w(x.currentTarget.value)}),s.jsx(ve,{disabled:e.disabled||(f==null?void 0:f.readonly),placeholder:"Postal Code",defaultValue:t.postalCode,onChange:x=>b(x.currentTarget.value)})]})}function G8(e){const t=$h(),[n,r]=p.useState(e.defaultValue||{});function o(i){const a=i?{text:i,authorReference:t&&Et(t),time:new Date().toISOString()}:{};r(a),e.onChange&&e.onChange(a)}return s.jsx(ve,{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);qb(a.data.StructureDefinitionList);for(const l of a.data.SearchParameterList)N6(l)})());return this.setCacheEntry(n,o),o}requestProfileSchema(t,n){if(!(n!=null&&n.expandProfile)&&jx(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 Fr((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(),{});qb(l)}else{const a=await this.searchOne("StructureDefinition",{url:t,_sort:"-_lastUpdated"});if(!a){console.warn(`No StructureDefinition found for ${t}!`);return}qP(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=pw(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=pw(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 Error("Request aborted")),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 qe(ht(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),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=D8(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=Et(t),a=t.subject),t.resourceType==="ServiceRequest"&&(i=t.encounter,a=t.subject),t.resourceType==="Patient"&&(a=Et(t)),this.createResource({resourceType:"Communication",status:"completed",basedOn:[Et(t)],encounter:i,subject:a,sender:o?Et(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,on.JSON,n)}graphql(t,n,r,o){return this.post(this.fhirUrl("$graphql"),{query:t,operationName:n,variables:r},on.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",nl(t),"$push"),{destination:typeof n=="string"?n:st(n),body:r,contentType:o,waitForResponse:i},on.FHIR_JSON,a)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(t){var n,r;(!((n=this.sessionDetails)!=null&&n.profile)||st(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=d8(t),this.medplumServer=u8(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.dispatchEvent({type:"profileRefreshing"}),this.get("auth/me").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"}),this.dispatchEvent({type:"profileRefreshed"}),t(r.profile)}).catch(n)}),this.profilePromise):Promise.resolve(void 0)}isLoading(){return!this.isInitialized||!!this.profilePromise}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(P8)&&(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=Et(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 f8(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 Fr(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 qe(B$);const c=await this.parseBody(i,l);if(i.status===200&&r.followRedirectOnOk||i.status===201&&r.followRedirectOnCreated){const u=await fw(i,c);if(u)return this.request("GET",u,{...r,body:void 0})}if(i.status===202&&r.pollStatusOnAccepted){const d=await fw(i,c)??o.statusUrl;if(d)return this.pollStatus(d,r,o)}if(i.status>=400)throw new qe(ht(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=Eo(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 ew(o)}throw new Error("Unreachable")}logRequest(t,n){if(console.log(`> ${n.method} ${t}`),n.headers){const r=n.headers;for(const o of Nc(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 ew(i),r.pollCount++}return this.request("GET",t,o,r)}async executeAutoBatch(){var o,i;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,Eo(this.fhirBaseUrl,a.url),a.options))}catch(l){a.reject(new qe(ht(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&&!UP(c.response.outcome)?l.reject(new qe(c.response.outcome)):l.resolve(c==null?void 0:c.resource)}}addFetchOptionsDefaults(t){this.setRequestHeader(t,"X-Medplum","extended"),this.setRequestHeader(t,"Accept",w8,!0),t.body&&this.setRequestHeader(t,"Content-Type",on.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.constructor.name==="Blob")||typeof File<"u"&&(n instanceof File||n.constructor.name==="File")||typeof Uint8Array<"u"&&(n instanceof Uint8Array||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 Error("Unauthenticated")))}async startPkce(){const t=ow();sessionStorage.setItem("pkceState",t);const n=ow();sessionStorage.setItem("codeVerifier",n);const r=await QF(n),o=g6(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??dw()),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)??dw()),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=GF(t+":"+n)}async fhircastSubscribe(t,n){if(!(typeof t=="string"&&t!==""))throw new qe(_t("Invalid topic provided. Topic must be a valid string."));if(!(typeof n=="object"&&Array.isArray(n)&&n.length>0))throw new qe(_t("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("/fhircast/STU3",iw(r),on.FORM_URL_ENCODED))["hub.channel.endpoint"];if(!i)throw new Error("Invalid response!");return r.endpoint=i,r}async fhircastUnsubscribe(t){if(!$x(t))throw new qe(_t("Invalid topic or subscriptionRequest. SubscriptionRequest must be an object."));if(!(t.endpoint&&typeof t.endpoint=="string"&&t.endpoint.startsWith("ws")))throw new qe(_t("Provided subscription request must have an endpoint in order to unsubscribe."));t.mode="unsubscribe",await this.post("/fhircast/STU3",iw(t),on.FORM_URL_ENCODED)}fhircastConnect(t){return new a8(t)}async fhircastPublish(t,n,r,o){return t8(n)?this.post(`/fhircast/STU3/${t}`,aw(t,n,r,o),on.JSON):(n8(n),this.post(`/fhircast/STU3/${t}`,aw(t,n,r),on.JSON))}async fhircastGetContext(t){return this.get(`/fhircast/STU3/${t}`)}async invite(t,n){return this.post("admin/projects/"+t+"/invite",n)}async fetchTokens(t){const n={method:"POST",headers:{"Content-Type":on.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 qe(Ri(a.error_description))}catch(a){throw new qe(Ri("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(c8(n)){const r=Fx(n);if(Date.now()>=r.exp*1e3)throw this.clearActiveLogin(),new Error("Token expired");if(r.cid){if(r.cid!==this.clientId)throw this.clearActiveLogin(),new Error("Token was not issued for this audience")}else if(this.clientId&&r.client_id!==this.clientId)throw this.clearActiveLogin(),new Error("Token was not issued for this audience")}return this.setActiveLogin({accessToken:n,refreshToken:t.refresh_token,project:t.project,profile:t.profile})}setupStorageListener(){try{window.addEventListener("storage",t=>{(t.key===null||t.key==="activeLogin")&&window.location.reload()})}catch{}}getSubscriptionManager(){return this.subscriptionManager||(this.subscriptionManager=new x8(this,w6(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 k8(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}function dw(){return typeof window>"u"?"":window.location.protocol+"//"+window.location.host+"/"}async function fw(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(_h(t)&&((i=(o=t.issue)==null?void 0:o[0])!=null&&i.diagnostics))return t.issue[0].diagnostics}function hw(e){var n;const t=((n=e.entry)==null?void 0:n.map(r=>r.resource))??[];return Object.assign(t,{bundle:e})}function R8(e){return kn(e)&&"data"in e&&"contentType"in e}function pw(e,t,n,r){return R8(e)?e:{data:e,filename:t,contentType:n,onProgress:r}}function _8(e){return kn(e)&&"docDefinition"in e}function D8(e,t,n,r){return _8(e)?e:{docDefinition:e,filename:t,tableLayouts:n,fonts:r}}function rl({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=I8(t,n,e,!!o);const l=xg(t,".",2)[1];a=A8(a,i,l),a=N8(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=xg(f,".",2)[1];if(h){if(!d[h]){const m=mf(h,i==null?void 0:i.hiddenFields);d[h]={hidden:m,readonly:m||mf(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 I8(e,t,n,r){const o=Object.create(null);if(n)for(const[a,l]of Object.entries(n.elementsByPath)){const c=Ac(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 A8(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])=>!mf(r+i,t.hiddenFields)))}function N8(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))mf(o+a,t.readonlyFields)?r[a]={...l,readonly:!0}:r[a]=l;return r}function mf(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 Ek(e){return e.type!==void 0&&e.type.length>0}function M8(e,t,n,r){var i;const o=V7(e,t.path,{profileUrl:r});if(o){const a=((i=n.typeSchema)==null?void 0:i.elements)??n.elements;return o.some(l=>q7(l,t,n,a))??!1}return console.assert(!1,"getNestedProperty[%s] in isDiscriminatorComponentMatch missed",t.path),!1}function Tk(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 M8(l,c,a,((u=a.typeSchema)==null?void 0:u.url)??r)}))return a.name}}class O8{constructor(t,n,r){if(t.type===void 0)throw new Error("schema must include a type");this.rootSchema=t;const o=rl({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(!Bt(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=L8(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);Bt((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(!Ek(l))continue;const c=(a=(i=l.type.find(u=>Bt(u.profile)))==null?void 0:i.profile)==null?void 0:a[0];if(Bt(c)){const u=yl(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;Bt(a)&&(i=rl({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 L8(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 Gp="__sliceName";function $8(e,t){const n=new F8(e,e.resourceType,"resource");return new O8(t,n).crawlResource(),n.getDefaultValue()}function mw(e,t,n){for(const[r,o]of Object.entries(t)){if(n===void 0||n===r){gf(e,r,o,t);continue}const i=Ac(n,r);i!==void 0&&gf(e,i,o,t)}return e}class F8{constructor(t,n,r){this.schemaStack=[],this.valueStack=[],this.rootValue=Xr(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=Ac(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){z8(d,a,n,r.elements),gf(d,a,n,r.elements);const f=Eg(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=Ac(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=Eg(a,i,n,r.elements);if(Array.isArray(l))for(let c=l.length-1;c>=0;c--){const u=l[c];Bt(u)||l.splice(c,1)}Gt(l)&&Cg(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[Gp]??Tk(i,[n],r.discriminator,this.schema.url))===n.name&&o.push(i);for(let i=o.length;i<n.min;i++)if(Px(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];Gp in o&&delete o[Gp]}}getDefaultValue(){return this.rootValue}}function z8(e,t,n,r){const o=Eg(e,t,n,r);n.min>0&&o===void 0&&Px(n.type[0].code)&&(n.isArray?Cg(e,[Object.create(null)],t,n):Cg(e,Object.create(null),t,n))}function Cg(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]",nn(i))}t===void 0?delete e[o]:e[o]=t}function Eg(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]",nn(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(kn(i)){if(i[c]===void 0)return;i=i[c]}else return}return a}function gf(e,t,n,r){if(!(n.fixed||n.pattern))return e;if(Array.isArray(e))return e.map(l=>gf(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]",nn(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]=Pk(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 Pk(e,t){if(Array.isArray(t)&&(Array.isArray(e)||e===void 0))return((e==null?void 0:e.length)??0)>0?e:Xr(t);if(kn(t)&&(kn(e)&&!Array.isArray(e)||e===void 0)){const n=Xr(e)??Object.create(null);for(const r of Object.keys(t))n[r]=Pk(n[r],t[r]);return n}return e}const kk=p.createContext(void 0);function Oh(){return p.useContext(kk)}function se(){return Oh().medplum}function Lh(){return Oh().navigate}function $h(){return Oh().profile}const gw=["change","storageInitialized","storageInitFailed","profileRefreshing","profileRefreshed"];function B8(e){const t=e.medplum,n=e.navigate??U8,[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 gw)t.addEventListener(l,a);return()=>{for(const l of gw)t.removeEventListener(l,a)}},[t]);const i=p.useMemo(()=>({...r,medplum:t,navigate:n}),[r,t,n]);return s.jsx(kk.Provider,{value:i,children:e.children})}function U8(e){window.location.assign(e)}const vw=new Map,Rk=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=vw.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 vw.set(t,e),e},[e]);function wt(e,t){const n=se(),[r,o]=p.useState(()=>yw(n,e)),i=p.useCallback(a=>{Mi(a,r)||o(a)},[r]);return p.useEffect(()=>{let a=!0;const l=yw(n,e);return!l&&Qs(e)?n.readReference(e).then(c=>{a&&i(c)}).catch(c=>{a&&(i(void 0),t&&t(ht(c)))}):i(l),()=>a=!1},[n,e,i,t]),r}function yw(e,t){if(t){if(ni(t))return t;if(Qs(t))return e.getCachedReference(t)}}function V8(e,t){return _k("searchOne",e,t)}function ol(e,t){return _k("searchResources",e,t)}function _k(e,t,n){const r=se(),[o,i]=p.useState(),[a,l]=p.useState(!0),[c,u]=p.useState(),[d,f]=p.useState();return p.useEffect(()=>{const h=r.fhirSearchUrl(t,n).toString();h!==o&&(i(h),r[e](t,n).then(m=>{l(!1),u(m),f(z$)}).catch(m=>{l(!1),u(void 0),f(ht(m))}))},[r,e,t,n,o]),[c,a,d]}function W8(e){const t=e.value;return t?s.jsx(s.Fragment,{children:C6(t)}):null}const Dk=["meta","implicitRules","contained","extension","modifierExtension"],Ik=["language","text"],bt=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});bt.displayName="ElementsContext";const zx=["extension","modifierExtension"],H8=["id",...Dk].filter(e=>!zx.includes(e));function q8(e){return Object.entries(e).filter(([n,r])=>{var o;return!Bt(r.type)||r.max===0||r.path.toLowerCase().endsWith("extension.url")&&r.fixed||zx.includes(n)&&!Bt((o=r.slicing)==null?void 0:o.slices)||H8.includes(n)?!1:!(Ik.includes(n)&&r.path.split(".").length===2||n.includes("."))})}function xw(e,t){return e.line&&e.line.length>t?e.line[t]:""}function bw(e,t,n){const r=e.line||[];for(;r.length<=t;)r.push("");return r[t]=n,{...e,line:r}}function G8(e){const[t,n]=p.useState(e.defaultValue||{}),r=p.useRef();r.current=t;const{getExtendedProps:o}=p.useContext(bt),[i,a,l,c,u,d,f]=p.useMemo(()=>["use","type","line1","line2","city","state","postalCode"].map(x=>o(e.path+"."+x)),[o,e.path]);function h(x){n(x),e.onChange&&e.onChange(x)}function m(x){h({...r.current,use:x})}function g(x){h({...r.current,type:x})}function v(x){h(bw(r.current||{},0,x))}function S(x){h(bw(r.current||{},1,x))}function y(x){h({...r.current,city:x})}function w(x){h({...r.current,state:x})}function b(x){h({...r.current,postalCode:x})}return s.jsxs(te,{gap:"xs",wrap:"nowrap",grow:!0,children:[s.jsx(It,{disabled:e.disabled||(i==null?void 0:i.readonly),"data-testid":"address-use",defaultValue:t.use,onChange:x=>m(x.currentTarget.value),data:["","home","work","temp","old","billing"]}),s.jsx(It,{disabled:e.disabled||(a==null?void 0:a.readonly),"data-testid":"address-type",defaultValue:t.type,onChange:x=>g(x.currentTarget.value),data:["","postal","physical","both"]}),s.jsx(ve,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"Line 1",defaultValue:xw(t,0),onChange:x=>v(x.currentTarget.value)}),s.jsx(ve,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Line 2",defaultValue:xw(t,1),onChange:x=>S(x.currentTarget.value)}),s.jsx(ve,{disabled:e.disabled||(u==null?void 0:u.readonly),placeholder:"City",defaultValue:t.city,onChange:x=>y(x.currentTarget.value)}),s.jsx(ve,{disabled:e.disabled||(d==null?void 0:d.readonly),placeholder:"State",defaultValue:t.state,onChange:x=>w(x.currentTarget.value)}),s.jsx(ve,{disabled:e.disabled||(f==null?void 0:f.readonly),placeholder:"Postal Code",defaultValue:t.postalCode,onChange:x=>b(x.currentTarget.value)})]})}function Q8(e){const t=$h(),[n,r]=p.useState(e.defaultValue||{});function o(i){const a=i?{text:i,authorReference:t&&Et(t),time:new Date().toISOString()}:{};r(a),e.onChange&&e.onChange(a)}return s.jsx(ve,{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.12.0 - MIT
143
143
  *
144
144
  * This source code is licensed under the MIT license.
145
145
  * See the LICENSE file in the root directory of this source tree.
146
- */var Q8={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}};/**
146
+ */var K8={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}};/**
147
147
  * @license @tabler/icons-react v3.12.0 - MIT
148
148
  *
149
149
  * This source code is licensed under the MIT license.
150
150
  * See the LICENSE file in the root directory of this source tree.
151
- */const be=(e,t,n,r)=>{const o=p.forwardRef(({color:i="currentColor",size:a=24,stroke:l=2,title:c,className:u,children:d,...f},h)=>p.createElement("svg",{ref:h,...Q8[e],width:a,height:a,className:["tabler-icon",`tabler-icon-${t}`,u].join(" "),...e==="filled"?{fill:i}:{strokeWidth:l,stroke:i},...f},[c&&p.createElement("title",{key:"svg-title"},c),...r.map(([m,g])=>p.createElement(m,g)),...Array.isArray(d)?d:[d]]));return o.displayName=`${n}`,o};/**
151
+ */const be=(e,t,n,r)=>{const o=p.forwardRef(({color:i="currentColor",size:a=24,stroke:l=2,title:c,className:u,children:d,...f},h)=>p.createElement("svg",{ref:h,...K8[e],width:a,height:a,className:["tabler-icon",`tabler-icon-${t}`,u].join(" "),...e==="filled"?{fill:i}:{strokeWidth:l,stroke:i},...f},[c&&p.createElement("title",{key:"svg-title"},c),...r.map(([m,g])=>p.createElement(m,g)),...Array.isArray(d)?d:[d]]));return o.displayName=`${n}`,o};/**
152
152
  * @license @tabler/icons-react v3.12.0 - MIT
153
153
  *
154
154
  * This source code is licensed under the MIT license.
155
155
  * See the LICENSE file in the root directory of this source tree.
156
- */var K8=be("outline","adjustments-horizontal","IconAdjustmentsHorizontal",[["path",{d:"M14 6m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-0"}],["path",{d:"M4 6l8 0",key:"svg-1"}],["path",{d:"M16 6l4 0",key:"svg-2"}],["path",{d:"M8 12m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-3"}],["path",{d:"M4 12l2 0",key:"svg-4"}],["path",{d:"M10 12l10 0",key:"svg-5"}],["path",{d:"M17 18m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-6"}],["path",{d:"M4 18l11 0",key:"svg-7"}],["path",{d:"M19 18l1 0",key:"svg-8"}]]);/**
156
+ */var Y8=be("outline","adjustments-horizontal","IconAdjustmentsHorizontal",[["path",{d:"M14 6m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-0"}],["path",{d:"M4 6l8 0",key:"svg-1"}],["path",{d:"M16 6l4 0",key:"svg-2"}],["path",{d:"M8 12m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-3"}],["path",{d:"M4 12l2 0",key:"svg-4"}],["path",{d:"M10 12l10 0",key:"svg-5"}],["path",{d:"M17 18m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-6"}],["path",{d:"M4 18l11 0",key:"svg-7"}],["path",{d:"M19 18l1 0",key:"svg-8"}]]);/**
157
157
  * @license @tabler/icons-react v3.12.0 - MIT
158
158
  *
159
159
  * This source code is licensed under the MIT license.
@@ -163,52 +163,52 @@ Error generating stack: `+i.message+`
163
163
  *
164
164
  * This source code is licensed under the MIT license.
165
165
  * See the LICENSE file in the root directory of this source tree.
166
- */var Y8=be("outline","arrow-down","IconArrowDown",[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M18 13l-6 6",key:"svg-1"}],["path",{d:"M6 13l6 6",key:"svg-2"}]]);/**
166
+ */var X8=be("outline","arrow-down","IconArrowDown",[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M18 13l-6 6",key:"svg-1"}],["path",{d:"M6 13l6 6",key:"svg-2"}]]);/**
167
167
  * @license @tabler/icons-react v3.12.0 - MIT
168
168
  *
169
169
  * This source code is licensed under the MIT license.
170
170
  * See the LICENSE file in the root directory of this source tree.
171
- */var X8=be("outline","arrow-up","IconArrowUp",[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M18 11l-6 -6",key:"svg-1"}],["path",{d:"M6 11l6 -6",key:"svg-2"}]]);/**
171
+ */var J8=be("outline","arrow-up","IconArrowUp",[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M18 11l-6 -6",key:"svg-1"}],["path",{d:"M6 11l6 -6",key:"svg-2"}]]);/**
172
172
  * @license @tabler/icons-react v3.12.0 - MIT
173
173
  *
174
174
  * This source code is licensed under the MIT license.
175
175
  * See the LICENSE file in the root directory of this source tree.
176
- */var J8=be("outline","bleach-off","IconBleachOff",[["path",{d:"M5 19h14m1.986 -1.977a2 2 0 0 0 -.146 -.773l-7.1 -12.25a2 2 0 0 0 -3.5 0l-.815 1.405m-1.488 2.568l-4.797 8.277a2 2 0 0 0 1.75 2.75",key:"svg-0"}],["path",{d:"M3 3l18 18",key:"svg-1"}]]);/**
176
+ */var Z8=be("outline","bleach-off","IconBleachOff",[["path",{d:"M5 19h14m1.986 -1.977a2 2 0 0 0 -.146 -.773l-7.1 -12.25a2 2 0 0 0 -3.5 0l-.815 1.405m-1.488 2.568l-4.797 8.277a2 2 0 0 0 1.75 2.75",key:"svg-0"}],["path",{d:"M3 3l18 18",key:"svg-1"}]]);/**
177
177
  * @license @tabler/icons-react v3.12.0 - MIT
178
178
  *
179
179
  * This source code is licensed under the MIT license.
180
180
  * See the LICENSE file in the root directory of this source tree.
181
- */var Z8=be("outline","bleach","IconBleach",[["path",{d:"M5 19h14a2 2 0 0 0 1.84 -2.75l-7.1 -12.25a2 2 0 0 0 -3.5 0l-7.1 12.25a2 2 0 0 0 1.75 2.75",key:"svg-0"}]]);/**
181
+ */var ez=be("outline","bleach","IconBleach",[["path",{d:"M5 19h14a2 2 0 0 0 1.84 -2.75l-7.1 -12.25a2 2 0 0 0 -3.5 0l-7.1 12.25a2 2 0 0 0 1.75 2.75",key:"svg-0"}]]);/**
182
182
  * @license @tabler/icons-react v3.12.0 - MIT
183
183
  *
184
184
  * This source code is licensed under the MIT license.
185
185
  * See the LICENSE file in the root directory of this source tree.
186
- */var ez=be("outline","box-multiple","IconBoxMultiple",[["path",{d:"M7 3m0 2a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z",key:"svg-0"}],["path",{d:"M17 17v2a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-10a2 2 0 0 1 2 -2h2",key:"svg-1"}]]);/**
186
+ */var tz=be("outline","box-multiple","IconBoxMultiple",[["path",{d:"M7 3m0 2a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z",key:"svg-0"}],["path",{d:"M17 17v2a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-10a2 2 0 0 1 2 -2h2",key:"svg-1"}]]);/**
187
187
  * @license @tabler/icons-react v3.12.0 - MIT
188
188
  *
189
189
  * This source code is licensed under the MIT license.
190
190
  * See the LICENSE file in the root directory of this source tree.
191
- */var tz=be("outline","brackets-contain","IconBracketsContain",[["path",{d:"M7 4h-4v16h4",key:"svg-0"}],["path",{d:"M17 4h4v16h-4",key:"svg-1"}],["path",{d:"M8 16h.01",key:"svg-2"}],["path",{d:"M12 16h.01",key:"svg-3"}],["path",{d:"M16 16h.01",key:"svg-4"}]]);/**
191
+ */var nz=be("outline","brackets-contain","IconBracketsContain",[["path",{d:"M7 4h-4v16h4",key:"svg-0"}],["path",{d:"M17 4h4v16h-4",key:"svg-1"}],["path",{d:"M8 16h.01",key:"svg-2"}],["path",{d:"M12 16h.01",key:"svg-3"}],["path",{d:"M16 16h.01",key:"svg-4"}]]);/**
192
192
  * @license @tabler/icons-react v3.12.0 - MIT
193
193
  *
194
194
  * This source code is licensed under the MIT license.
195
195
  * See the LICENSE file in the root directory of this source tree.
196
- */var nz=be("outline","brand-asana","IconBrandAsana",[["path",{d:"M12 7m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",key:"svg-0"}],["path",{d:"M17 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",key:"svg-1"}],["path",{d:"M7 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",key:"svg-2"}]]);/**
196
+ */var rz=be("outline","brand-asana","IconBrandAsana",[["path",{d:"M12 7m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",key:"svg-0"}],["path",{d:"M17 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",key:"svg-1"}],["path",{d:"M7 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",key:"svg-2"}]]);/**
197
197
  * @license @tabler/icons-react v3.12.0 - MIT
198
198
  *
199
199
  * This source code is licensed under the MIT license.
200
200
  * See the LICENSE file in the root directory of this source tree.
201
- */var rz=be("outline","bucket-off","IconBucketOff",[["path",{d:"M5.029 5.036c-.655 .58 -1.029 1.25 -1.029 1.964c0 2.033 3.033 3.712 6.96 3.967m3.788 -.21c3.064 -.559 5.252 -2.029 5.252 -3.757c0 -2.21 -3.582 -4 -8 -4c-1.605 0 -3.1 .236 -4.352 .643",key:"svg-0"}],["path",{d:"M4 7c0 .664 .088 1.324 .263 1.965l2.737 10.035c.5 1.5 2.239 2 5 2s4.5 -.5 5 -2c.1 -.3 .252 -.812 .457 -1.535m.862 -3.146c.262 -.975 .735 -2.76 1.418 -5.354a7.45 7.45 0 0 0 .263 -1.965",key:"svg-1"}],["path",{d:"M3 3l18 18",key:"svg-2"}]]);/**
201
+ */var oz=be("outline","bucket-off","IconBucketOff",[["path",{d:"M5.029 5.036c-.655 .58 -1.029 1.25 -1.029 1.964c0 2.033 3.033 3.712 6.96 3.967m3.788 -.21c3.064 -.559 5.252 -2.029 5.252 -3.757c0 -2.21 -3.582 -4 -8 -4c-1.605 0 -3.1 .236 -4.352 .643",key:"svg-0"}],["path",{d:"M4 7c0 .664 .088 1.324 .263 1.965l2.737 10.035c.5 1.5 2.239 2 5 2s4.5 -.5 5 -2c.1 -.3 .252 -.812 .457 -1.535m.862 -3.146c.262 -.975 .735 -2.76 1.418 -5.354a7.45 7.45 0 0 0 .263 -1.965",key:"svg-1"}],["path",{d:"M3 3l18 18",key:"svg-2"}]]);/**
202
202
  * @license @tabler/icons-react v3.12.0 - MIT
203
203
  *
204
204
  * This source code is licensed under the MIT license.
205
205
  * See the LICENSE file in the root directory of this source tree.
206
- */var oz=be("outline","bucket","IconBucket",[["path",{d:"M12 7m-8 0a8 4 0 1 0 16 0a8 4 0 1 0 -16 0",key:"svg-0"}],["path",{d:"M4 7c0 .664 .088 1.324 .263 1.965l2.737 10.035c.5 1.5 2.239 2 5 2s4.5 -.5 5 -2c.333 -1 1.246 -4.345 2.737 -10.035a7.45 7.45 0 0 0 .263 -1.965",key:"svg-1"}]]);/**
206
+ */var iz=be("outline","bucket","IconBucket",[["path",{d:"M12 7m-8 0a8 4 0 1 0 16 0a8 4 0 1 0 -16 0",key:"svg-0"}],["path",{d:"M4 7c0 .664 .088 1.324 .263 1.965l2.737 10.035c.5 1.5 2.239 2 5 2s4.5 -.5 5 -2c.333 -1 1.246 -4.345 2.737 -10.035a7.45 7.45 0 0 0 .263 -1.965",key:"svg-1"}]]);/**
207
207
  * @license @tabler/icons-react v3.12.0 - MIT
208
208
  *
209
209
  * This source code is licensed under the MIT license.
210
210
  * See the LICENSE file in the root directory of this source tree.
211
- */var iz=be("outline","building","IconBuilding",[["path",{d:"M3 21l18 0",key:"svg-0"}],["path",{d:"M9 8l1 0",key:"svg-1"}],["path",{d:"M9 12l1 0",key:"svg-2"}],["path",{d:"M9 16l1 0",key:"svg-3"}],["path",{d:"M14 8l1 0",key:"svg-4"}],["path",{d:"M14 12l1 0",key:"svg-5"}],["path",{d:"M14 16l1 0",key:"svg-6"}],["path",{d:"M5 21v-16a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v16",key:"svg-7"}]]);/**
211
+ */var sz=be("outline","building","IconBuilding",[["path",{d:"M3 21l18 0",key:"svg-0"}],["path",{d:"M9 8l1 0",key:"svg-1"}],["path",{d:"M9 12l1 0",key:"svg-2"}],["path",{d:"M9 16l1 0",key:"svg-3"}],["path",{d:"M14 8l1 0",key:"svg-4"}],["path",{d:"M14 12l1 0",key:"svg-5"}],["path",{d:"M14 16l1 0",key:"svg-6"}],["path",{d:"M5 21v-16a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v16",key:"svg-7"}]]);/**
212
212
  * @license @tabler/icons-react v3.12.0 - MIT
213
213
  *
214
214
  * This source code is licensed under the MIT license.
@@ -223,7 +223,7 @@ Error generating stack: `+i.message+`
223
223
  *
224
224
  * This source code is licensed under the MIT license.
225
225
  * See the LICENSE file in the root directory of this source tree.
226
- */var sz=be("outline","checkbox","IconCheckbox",[["path",{d:"M9 11l3 3l8 -8",key:"svg-0"}],["path",{d:"M20 12v6a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h9",key:"svg-1"}]]);/**
226
+ */var az=be("outline","checkbox","IconCheckbox",[["path",{d:"M9 11l3 3l8 -8",key:"svg-0"}],["path",{d:"M20 12v6a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h9",key:"svg-1"}]]);/**
227
227
  * @license @tabler/icons-react v3.12.0 - MIT
228
228
  *
229
229
  * This source code is licensed under the MIT license.
@@ -248,7 +248,7 @@ Error generating stack: `+i.message+`
248
248
  *
249
249
  * This source code is licensed under the MIT license.
250
250
  * See the LICENSE file in the root directory of this source tree.
251
- */var az=be("outline","columns","IconColumns",[["path",{d:"M4 6l5.5 0",key:"svg-0"}],["path",{d:"M4 10l5.5 0",key:"svg-1"}],["path",{d:"M4 14l5.5 0",key:"svg-2"}],["path",{d:"M4 18l5.5 0",key:"svg-3"}],["path",{d:"M14.5 6l5.5 0",key:"svg-4"}],["path",{d:"M14.5 10l5.5 0",key:"svg-5"}],["path",{d:"M14.5 14l5.5 0",key:"svg-6"}],["path",{d:"M14.5 18l5.5 0",key:"svg-7"}]]);/**
251
+ */var lz=be("outline","columns","IconColumns",[["path",{d:"M4 6l5.5 0",key:"svg-0"}],["path",{d:"M4 10l5.5 0",key:"svg-1"}],["path",{d:"M4 14l5.5 0",key:"svg-2"}],["path",{d:"M4 18l5.5 0",key:"svg-3"}],["path",{d:"M14.5 6l5.5 0",key:"svg-4"}],["path",{d:"M14.5 10l5.5 0",key:"svg-5"}],["path",{d:"M14.5 14l5.5 0",key:"svg-6"}],["path",{d:"M14.5 18l5.5 0",key:"svg-7"}]]);/**
252
252
  * @license @tabler/icons-react v3.12.0 - MIT
253
253
  *
254
254
  * This source code is licensed under the MIT license.
@@ -258,17 +258,17 @@ Error generating stack: `+i.message+`
258
258
  *
259
259
  * This source code is licensed under the MIT license.
260
260
  * See the LICENSE file in the root directory of this source tree.
261
- */var lz=be("outline","currency-dollar","IconCurrencyDollar",[["path",{d:"M16.7 8a3 3 0 0 0 -2.7 -2h-4a3 3 0 0 0 0 6h4a3 3 0 0 1 0 6h-4a3 3 0 0 1 -2.7 -2",key:"svg-0"}],["path",{d:"M12 3v3m0 12v3",key:"svg-1"}]]);/**
261
+ */var cz=be("outline","currency-dollar","IconCurrencyDollar",[["path",{d:"M16.7 8a3 3 0 0 0 -2.7 -2h-4a3 3 0 0 0 0 6h4a3 3 0 0 1 0 6h-4a3 3 0 0 1 -2.7 -2",key:"svg-0"}],["path",{d:"M12 3v3m0 12v3",key:"svg-1"}]]);/**
262
262
  * @license @tabler/icons-react v3.12.0 - MIT
263
263
  *
264
264
  * This source code is licensed under the MIT license.
265
265
  * See the LICENSE file in the root directory of this source tree.
266
- */var cz=be("outline","device-floppy","IconDeviceFloppy",[["path",{d:"M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2",key:"svg-0"}],["path",{d:"M12 14m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-1"}],["path",{d:"M14 4l0 4l-6 0l0 -4",key:"svg-2"}]]);/**
266
+ */var uz=be("outline","device-floppy","IconDeviceFloppy",[["path",{d:"M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2",key:"svg-0"}],["path",{d:"M12 14m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-1"}],["path",{d:"M14 4l0 4l-6 0l0 -4",key:"svg-2"}]]);/**
267
267
  * @license @tabler/icons-react v3.12.0 - MIT
268
268
  *
269
269
  * This source code is licensed under the MIT license.
270
270
  * See the LICENSE file in the root directory of this source tree.
271
- */var uz=be("outline","dots","IconDots",[["path",{d:"M5 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0",key:"svg-0"}],["path",{d:"M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0",key:"svg-1"}],["path",{d:"M19 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0",key:"svg-2"}]]);/**
271
+ */var dz=be("outline","dots","IconDots",[["path",{d:"M5 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0",key:"svg-0"}],["path",{d:"M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0",key:"svg-1"}],["path",{d:"M19 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0",key:"svg-2"}]]);/**
272
272
  * @license @tabler/icons-react v3.12.0 - MIT
273
273
  *
274
274
  * This source code is licensed under the MIT license.
@@ -293,22 +293,22 @@ Error generating stack: `+i.message+`
293
293
  *
294
294
  * This source code is licensed under the MIT license.
295
295
  * See the LICENSE file in the root directory of this source tree.
296
- */var dz=be("outline","file-plus","IconFilePlus",[["path",{d:"M14 3v4a1 1 0 0 0 1 1h4",key:"svg-0"}],["path",{d:"M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z",key:"svg-1"}],["path",{d:"M12 11l0 6",key:"svg-2"}],["path",{d:"M9 14l6 0",key:"svg-3"}]]);/**
296
+ */var fz=be("outline","file-plus","IconFilePlus",[["path",{d:"M14 3v4a1 1 0 0 0 1 1h4",key:"svg-0"}],["path",{d:"M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z",key:"svg-1"}],["path",{d:"M12 11l0 6",key:"svg-2"}],["path",{d:"M9 14l6 0",key:"svg-3"}]]);/**
297
297
  * @license @tabler/icons-react v3.12.0 - MIT
298
298
  *
299
299
  * This source code is licensed under the MIT license.
300
300
  * See the LICENSE file in the root directory of this source tree.
301
- */var fz=be("outline","filter","IconFilter",[["path",{d:"M4 4h16v2.172a2 2 0 0 1 -.586 1.414l-4.414 4.414v7l-6 2v-8.5l-4.48 -4.928a2 2 0 0 1 -.52 -1.345v-2.227z",key:"svg-0"}]]);/**
301
+ */var hz=be("outline","filter","IconFilter",[["path",{d:"M4 4h16v2.172a2 2 0 0 1 -.586 1.414l-4.414 4.414v7l-6 2v-8.5l-4.48 -4.928a2 2 0 0 1 -.52 -1.345v-2.227z",key:"svg-0"}]]);/**
302
302
  * @license @tabler/icons-react v3.12.0 - MIT
303
303
  *
304
304
  * This source code is licensed under the MIT license.
305
305
  * See the LICENSE file in the root directory of this source tree.
306
- */var hz=be("outline","forms","IconForms",[["path",{d:"M12 3a3 3 0 0 0 -3 3v12a3 3 0 0 0 3 3",key:"svg-0"}],["path",{d:"M6 3a3 3 0 0 1 3 3v12a3 3 0 0 1 -3 3",key:"svg-1"}],["path",{d:"M13 7h7a1 1 0 0 1 1 1v8a1 1 0 0 1 -1 1h-7",key:"svg-2"}],["path",{d:"M5 7h-1a1 1 0 0 0 -1 1v8a1 1 0 0 0 1 1h1",key:"svg-3"}],["path",{d:"M17 12h.01",key:"svg-4"}],["path",{d:"M13 12h.01",key:"svg-5"}]]);/**
306
+ */var pz=be("outline","forms","IconForms",[["path",{d:"M12 3a3 3 0 0 0 -3 3v12a3 3 0 0 0 3 3",key:"svg-0"}],["path",{d:"M6 3a3 3 0 0 1 3 3v12a3 3 0 0 1 -3 3",key:"svg-1"}],["path",{d:"M13 7h7a1 1 0 0 1 1 1v8a1 1 0 0 1 -1 1h-7",key:"svg-2"}],["path",{d:"M5 7h-1a1 1 0 0 0 -1 1v8a1 1 0 0 0 1 1h1",key:"svg-3"}],["path",{d:"M17 12h.01",key:"svg-4"}],["path",{d:"M13 12h.01",key:"svg-5"}]]);/**
307
307
  * @license @tabler/icons-react v3.12.0 - MIT
308
308
  *
309
309
  * This source code is licensed under the MIT license.
310
310
  * See the LICENSE file in the root directory of this source tree.
311
- */var pz=be("outline","id","IconId",[["path",{d:"M3 4m0 3a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v10a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3z",key:"svg-0"}],["path",{d:"M9 10m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-1"}],["path",{d:"M15 8l2 0",key:"svg-2"}],["path",{d:"M15 12l2 0",key:"svg-3"}],["path",{d:"M7 16l10 0",key:"svg-4"}]]);/**
311
+ */var mz=be("outline","id","IconId",[["path",{d:"M3 4m0 3a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v10a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3z",key:"svg-0"}],["path",{d:"M9 10m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-1"}],["path",{d:"M15 8l2 0",key:"svg-2"}],["path",{d:"M15 12l2 0",key:"svg-3"}],["path",{d:"M7 16l10 0",key:"svg-4"}]]);/**
312
312
  * @license @tabler/icons-react v3.12.0 - MIT
313
313
  *
314
314
  * This source code is licensed under the MIT license.
@@ -318,17 +318,17 @@ Error generating stack: `+i.message+`
318
318
  *
319
319
  * This source code is licensed under the MIT license.
320
320
  * See the LICENSE file in the root directory of this source tree.
321
- */var mz=be("outline","lock-access","IconLockAccess",[["path",{d:"M4 8v-2a2 2 0 0 1 2 -2h2",key:"svg-0"}],["path",{d:"M4 16v2a2 2 0 0 0 2 2h2",key:"svg-1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v2",key:"svg-2"}],["path",{d:"M16 20h2a2 2 0 0 0 2 -2v-2",key:"svg-3"}],["path",{d:"M8 11m0 1a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1v3a1 1 0 0 1 -1 1h-6a1 1 0 0 1 -1 -1z",key:"svg-4"}],["path",{d:"M10 11v-2a2 2 0 1 1 4 0v2",key:"svg-5"}]]);/**
321
+ */var gz=be("outline","lock-access","IconLockAccess",[["path",{d:"M4 8v-2a2 2 0 0 1 2 -2h2",key:"svg-0"}],["path",{d:"M4 16v2a2 2 0 0 0 2 2h2",key:"svg-1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v2",key:"svg-2"}],["path",{d:"M16 20h2a2 2 0 0 0 2 -2v-2",key:"svg-3"}],["path",{d:"M8 11m0 1a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1v3a1 1 0 0 1 -1 1h-6a1 1 0 0 1 -1 -1z",key:"svg-4"}],["path",{d:"M10 11v-2a2 2 0 1 1 4 0v2",key:"svg-5"}]]);/**
322
322
  * @license @tabler/icons-react v3.12.0 - MIT
323
323
  *
324
324
  * This source code is licensed under the MIT license.
325
325
  * See the LICENSE file in the root directory of this source tree.
326
- */var gz=be("outline","lock","IconLock",[["path",{d:"M5 13a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v6a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-6z",key:"svg-0"}],["path",{d:"M11 16a1 1 0 1 0 2 0a1 1 0 0 0 -2 0",key:"svg-1"}],["path",{d:"M8 11v-4a4 4 0 1 1 8 0v4",key:"svg-2"}]]);/**
326
+ */var vz=be("outline","lock","IconLock",[["path",{d:"M5 13a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v6a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-6z",key:"svg-0"}],["path",{d:"M11 16a1 1 0 1 0 2 0a1 1 0 0 0 -2 0",key:"svg-1"}],["path",{d:"M8 11v-4a4 4 0 1 1 8 0v4",key:"svg-2"}]]);/**
327
327
  * @license @tabler/icons-react v3.12.0 - MIT
328
328
  *
329
329
  * This source code is licensed under the MIT license.
330
330
  * See the LICENSE file in the root directory of this source tree.
331
- */var vz=be("outline","logout","IconLogout",[["path",{d:"M14 8v-2a2 2 0 0 0 -2 -2h-7a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2 -2v-2",key:"svg-0"}],["path",{d:"M9 12h12l-3 -3",key:"svg-1"}],["path",{d:"M18 15l3 -3",key:"svg-2"}]]);/**
331
+ */var yz=be("outline","logout","IconLogout",[["path",{d:"M14 8v-2a2 2 0 0 0 -2 -2h-7a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2 -2v-2",key:"svg-0"}],["path",{d:"M9 12h12l-3 -3",key:"svg-1"}],["path",{d:"M18 15l3 -3",key:"svg-2"}]]);/**
332
332
  * @license @tabler/icons-react v3.12.0 - MIT
333
333
  *
334
334
  * This source code is licensed under the MIT license.
@@ -343,67 +343,67 @@ Error generating stack: `+i.message+`
343
343
  *
344
344
  * This source code is licensed under the MIT license.
345
345
  * See the LICENSE file in the root directory of this source tree.
346
- */var yz=be("outline","message","IconMessage",[["path",{d:"M8 9h8",key:"svg-0"}],["path",{d:"M8 13h6",key:"svg-1"}],["path",{d:"M18 4a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-5l-5 3v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12z",key:"svg-2"}]]);/**
346
+ */var xz=be("outline","message","IconMessage",[["path",{d:"M8 9h8",key:"svg-0"}],["path",{d:"M8 13h6",key:"svg-1"}],["path",{d:"M18 4a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-5l-5 3v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12z",key:"svg-2"}]]);/**
347
347
  * @license @tabler/icons-react v3.12.0 - MIT
348
348
  *
349
349
  * This source code is licensed under the MIT license.
350
350
  * See the LICENSE file in the root directory of this source tree.
351
- */var xz=be("outline","microscope","IconMicroscope",[["path",{d:"M5 21h14",key:"svg-0"}],["path",{d:"M6 18h2",key:"svg-1"}],["path",{d:"M7 18v3",key:"svg-2"}],["path",{d:"M9 11l3 3l6 -6l-3 -3z",key:"svg-3"}],["path",{d:"M10.5 12.5l-1.5 1.5",key:"svg-4"}],["path",{d:"M17 3l3 3",key:"svg-5"}],["path",{d:"M12 21a6 6 0 0 0 3.715 -10.712",key:"svg-6"}]]);/**
351
+ */var bz=be("outline","microscope","IconMicroscope",[["path",{d:"M5 21h14",key:"svg-0"}],["path",{d:"M6 18h2",key:"svg-1"}],["path",{d:"M7 18v3",key:"svg-2"}],["path",{d:"M9 11l3 3l6 -6l-3 -3z",key:"svg-3"}],["path",{d:"M10.5 12.5l-1.5 1.5",key:"svg-4"}],["path",{d:"M17 3l3 3",key:"svg-5"}],["path",{d:"M12 21a6 6 0 0 0 3.715 -10.712",key:"svg-6"}]]);/**
352
352
  * @license @tabler/icons-react v3.12.0 - MIT
353
353
  *
354
354
  * This source code is licensed under the MIT license.
355
355
  * See the LICENSE file in the root directory of this source tree.
356
- */var bz=be("outline","packages","IconPackages",[["path",{d:"M7 16.5l-5 -3l5 -3l5 3v5.5l-5 3z",key:"svg-0"}],["path",{d:"M2 13.5v5.5l5 3",key:"svg-1"}],["path",{d:"M7 16.545l5 -3.03",key:"svg-2"}],["path",{d:"M17 16.5l-5 -3l5 -3l5 3v5.5l-5 3z",key:"svg-3"}],["path",{d:"M12 19l5 3",key:"svg-4"}],["path",{d:"M17 16.5l5 -3",key:"svg-5"}],["path",{d:"M12 13.5v-5.5l-5 -3l5 -3l5 3v5.5",key:"svg-6"}],["path",{d:"M7 5.03v5.455",key:"svg-7"}],["path",{d:"M12 8l5 -3",key:"svg-8"}]]);/**
356
+ */var wz=be("outline","packages","IconPackages",[["path",{d:"M7 16.5l-5 -3l5 -3l5 3v5.5l-5 3z",key:"svg-0"}],["path",{d:"M2 13.5v5.5l5 3",key:"svg-1"}],["path",{d:"M7 16.545l5 -3.03",key:"svg-2"}],["path",{d:"M17 16.5l-5 -3l5 -3l5 3v5.5l-5 3z",key:"svg-3"}],["path",{d:"M12 19l5 3",key:"svg-4"}],["path",{d:"M17 16.5l5 -3",key:"svg-5"}],["path",{d:"M12 13.5v-5.5l-5 -3l5 -3l5 3v5.5",key:"svg-6"}],["path",{d:"M7 5.03v5.455",key:"svg-7"}],["path",{d:"M12 8l5 -3",key:"svg-8"}]]);/**
357
357
  * @license @tabler/icons-react v3.12.0 - MIT
358
358
  *
359
359
  * This source code is licensed under the MIT license.
360
360
  * See the LICENSE file in the root directory of this source tree.
361
- */var wz=be("outline","pin","IconPin",[["path",{d:"M15 4.5l-4 4l-4 1.5l-1.5 1.5l7 7l1.5 -1.5l1.5 -4l4 -4",key:"svg-0"}],["path",{d:"M9 15l-4.5 4.5",key:"svg-1"}],["path",{d:"M14.5 4l5.5 5.5",key:"svg-2"}]]);/**
361
+ */var Sz=be("outline","pin","IconPin",[["path",{d:"M15 4.5l-4 4l-4 1.5l-1.5 1.5l7 7l1.5 -1.5l1.5 -4l4 -4",key:"svg-0"}],["path",{d:"M9 15l-4.5 4.5",key:"svg-1"}],["path",{d:"M14.5 4l5.5 5.5",key:"svg-2"}]]);/**
362
362
  * @license @tabler/icons-react v3.12.0 - MIT
363
363
  *
364
364
  * This source code is licensed under the MIT license.
365
365
  * See the LICENSE file in the root directory of this source tree.
366
- */var Sz=be("outline","pinned-off","IconPinnedOff",[["path",{d:"M3 3l18 18",key:"svg-0"}],["path",{d:"M15 4.5l-3.249 3.249m-2.57 1.433l-2.181 .818l-1.5 1.5l7 7l1.5 -1.5l.82 -2.186m1.43 -2.563l3.25 -3.251",key:"svg-1"}],["path",{d:"M9 15l-4.5 4.5",key:"svg-2"}],["path",{d:"M14.5 4l5.5 5.5",key:"svg-3"}]]);/**
366
+ */var jz=be("outline","pinned-off","IconPinnedOff",[["path",{d:"M3 3l18 18",key:"svg-0"}],["path",{d:"M15 4.5l-3.249 3.249m-2.57 1.433l-2.181 .818l-1.5 1.5l7 7l1.5 -1.5l.82 -2.186m1.43 -2.563l3.25 -3.251",key:"svg-1"}],["path",{d:"M9 15l-4.5 4.5",key:"svg-2"}],["path",{d:"M14.5 4l5.5 5.5",key:"svg-3"}]]);/**
367
367
  * @license @tabler/icons-react v3.12.0 - MIT
368
368
  *
369
369
  * This source code is licensed under the MIT license.
370
370
  * See the LICENSE file in the root directory of this source tree.
371
- */var jz=be("outline","player-play","IconPlayerPlay",[["path",{d:"M7 4v16l13 -8z",key:"svg-0"}]]);/**
371
+ */var Cz=be("outline","player-play","IconPlayerPlay",[["path",{d:"M7 4v16l13 -8z",key:"svg-0"}]]);/**
372
372
  * @license @tabler/icons-react v3.12.0 - MIT
373
373
  *
374
374
  * This source code is licensed under the MIT license.
375
375
  * See the LICENSE file in the root directory of this source tree.
376
- */var Cz=be("outline","plus","IconPlus",[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M5 12l14 0",key:"svg-1"}]]);/**
376
+ */var Ez=be("outline","plus","IconPlus",[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M5 12l14 0",key:"svg-1"}]]);/**
377
377
  * @license @tabler/icons-react v3.12.0 - MIT
378
378
  *
379
379
  * This source code is licensed under the MIT license.
380
380
  * See the LICENSE file in the root directory of this source tree.
381
- */var Ez=be("outline","receipt","IconReceipt",[["path",{d:"M5 21v-16a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v16l-3 -2l-2 2l-2 -2l-2 2l-2 -2l-3 2m4 -14h6m-6 4h6m-2 4h2",key:"svg-0"}]]);/**
381
+ */var Tz=be("outline","receipt","IconReceipt",[["path",{d:"M5 21v-16a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v16l-3 -2l-2 2l-2 -2l-2 2l-2 -2l-3 2m4 -14h6m-6 4h6m-2 4h2",key:"svg-0"}]]);/**
382
382
  * @license @tabler/icons-react v3.12.0 - MIT
383
383
  *
384
384
  * This source code is licensed under the MIT license.
385
385
  * See the LICENSE file in the root directory of this source tree.
386
- */var Tz=be("outline","refresh","IconRefresh",[["path",{d:"M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4",key:"svg-0"}],["path",{d:"M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4",key:"svg-1"}]]);/**
386
+ */var Pz=be("outline","refresh","IconRefresh",[["path",{d:"M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4",key:"svg-0"}],["path",{d:"M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4",key:"svg-1"}]]);/**
387
387
  * @license @tabler/icons-react v3.12.0 - MIT
388
388
  *
389
389
  * This source code is licensed under the MIT license.
390
390
  * See the LICENSE file in the root directory of this source tree.
391
- */var Pz=be("outline","repeat","IconRepeat",[["path",{d:"M4 12v-3a3 3 0 0 1 3 -3h13m-3 -3l3 3l-3 3",key:"svg-0"}],["path",{d:"M20 12v3a3 3 0 0 1 -3 3h-13m3 3l-3 -3l3 -3",key:"svg-1"}]]);/**
391
+ */var kz=be("outline","repeat","IconRepeat",[["path",{d:"M4 12v-3a3 3 0 0 1 3 -3h13m-3 -3l3 3l-3 3",key:"svg-0"}],["path",{d:"M20 12v3a3 3 0 0 1 -3 3h-13m3 3l-3 -3l3 -3",key:"svg-1"}]]);/**
392
392
  * @license @tabler/icons-react v3.12.0 - MIT
393
393
  *
394
394
  * This source code is licensed under the MIT license.
395
395
  * See the LICENSE file in the root directory of this source tree.
396
- */var kz=be("outline","report-medical","IconReportMedical",[["path",{d:"M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2",key:"svg-0"}],["path",{d:"M9 3m0 2a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v0a2 2 0 0 1 -2 2h-2a2 2 0 0 1 -2 -2z",key:"svg-1"}],["path",{d:"M10 14l4 0",key:"svg-2"}],["path",{d:"M12 12l0 4",key:"svg-3"}]]);/**
396
+ */var Rz=be("outline","report-medical","IconReportMedical",[["path",{d:"M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2",key:"svg-0"}],["path",{d:"M9 3m0 2a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v0a2 2 0 0 1 -2 2h-2a2 2 0 0 1 -2 -2z",key:"svg-1"}],["path",{d:"M10 14l4 0",key:"svg-2"}],["path",{d:"M12 12l0 4",key:"svg-3"}]]);/**
397
397
  * @license @tabler/icons-react v3.12.0 - MIT
398
398
  *
399
399
  * This source code is licensed under the MIT license.
400
400
  * See the LICENSE file in the root directory of this source tree.
401
- */var Rz=be("outline","router","IconRouter",[["path",{d:"M3 13m0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v4a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z",key:"svg-0"}],["path",{d:"M17 17l0 .01",key:"svg-1"}],["path",{d:"M13 17l0 .01",key:"svg-2"}],["path",{d:"M15 13l0 -2",key:"svg-3"}],["path",{d:"M11.75 8.75a4 4 0 0 1 6.5 0",key:"svg-4"}],["path",{d:"M8.5 6.5a8 8 0 0 1 13 0",key:"svg-5"}]]);/**
401
+ */var _z=be("outline","router","IconRouter",[["path",{d:"M3 13m0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v4a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z",key:"svg-0"}],["path",{d:"M17 17l0 .01",key:"svg-1"}],["path",{d:"M13 17l0 .01",key:"svg-2"}],["path",{d:"M15 13l0 -2",key:"svg-3"}],["path",{d:"M11.75 8.75a4 4 0 0 1 6.5 0",key:"svg-4"}],["path",{d:"M8.5 6.5a8 8 0 0 1 13 0",key:"svg-5"}]]);/**
402
402
  * @license @tabler/icons-react v3.12.0 - MIT
403
403
  *
404
404
  * This source code is licensed under the MIT license.
405
405
  * See the LICENSE file in the root directory of this source tree.
406
- */var _z=be("outline","search","IconSearch",[["path",{d:"M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0",key:"svg-0"}],["path",{d:"M21 21l-6 -6",key:"svg-1"}]]);/**
406
+ */var Dz=be("outline","search","IconSearch",[["path",{d:"M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0",key:"svg-0"}],["path",{d:"M21 21l-6 -6",key:"svg-1"}]]);/**
407
407
  * @license @tabler/icons-react v3.12.0 - MIT
408
408
  *
409
409
  * This source code is licensed under the MIT license.
@@ -423,27 +423,27 @@ Error generating stack: `+i.message+`
423
423
  *
424
424
  * This source code is licensed under the MIT license.
425
425
  * See the LICENSE file in the root directory of this source tree.
426
- */var Dz=be("outline","square","IconSquare",[["path",{d:"M3 3m0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z",key:"svg-0"}]]);/**
426
+ */var Iz=be("outline","square","IconSquare",[["path",{d:"M3 3m0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z",key:"svg-0"}]]);/**
427
427
  * @license @tabler/icons-react v3.12.0 - MIT
428
428
  *
429
429
  * This source code is licensed under the MIT license.
430
430
  * See the LICENSE file in the root directory of this source tree.
431
- */var Iz=be("outline","star","IconStar",[["path",{d:"M12 17.75l-6.172 3.245l1.179 -6.873l-5 -4.867l6.9 -1l3.086 -6.253l3.086 6.253l6.9 1l-5 4.867l1.179 6.873z",key:"svg-0"}]]);/**
431
+ */var Az=be("outline","star","IconStar",[["path",{d:"M12 17.75l-6.172 3.245l1.179 -6.873l-5 -4.867l6.9 -1l3.086 -6.253l3.086 6.253l6.9 1l-5 4.867l1.179 6.873z",key:"svg-0"}]]);/**
432
432
  * @license @tabler/icons-react v3.12.0 - MIT
433
433
  *
434
434
  * This source code is licensed under the MIT license.
435
435
  * See the LICENSE file in the root directory of this source tree.
436
- */var Az=be("outline","switch-horizontal","IconSwitchHorizontal",[["path",{d:"M16 3l4 4l-4 4",key:"svg-0"}],["path",{d:"M10 7l10 0",key:"svg-1"}],["path",{d:"M8 13l-4 4l4 4",key:"svg-2"}],["path",{d:"M4 17l9 0",key:"svg-3"}]]);/**
436
+ */var Nz=be("outline","switch-horizontal","IconSwitchHorizontal",[["path",{d:"M16 3l4 4l-4 4",key:"svg-0"}],["path",{d:"M10 7l10 0",key:"svg-1"}],["path",{d:"M8 13l-4 4l4 4",key:"svg-2"}],["path",{d:"M4 17l9 0",key:"svg-3"}]]);/**
437
437
  * @license @tabler/icons-react v3.12.0 - MIT
438
438
  *
439
439
  * This source code is licensed under the MIT license.
440
440
  * See the LICENSE file in the root directory of this source tree.
441
- */var Nz=be("outline","table-export","IconTableExport",[["path",{d:"M12.5 21h-7.5a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v7.5",key:"svg-0"}],["path",{d:"M3 10h18",key:"svg-1"}],["path",{d:"M10 3v18",key:"svg-2"}],["path",{d:"M16 19h6",key:"svg-3"}],["path",{d:"M19 16l3 3l-3 3",key:"svg-4"}]]);/**
441
+ */var Mz=be("outline","table-export","IconTableExport",[["path",{d:"M12.5 21h-7.5a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v7.5",key:"svg-0"}],["path",{d:"M3 10h18",key:"svg-1"}],["path",{d:"M10 3v18",key:"svg-2"}],["path",{d:"M16 19h6",key:"svg-3"}],["path",{d:"M19 16l3 3l-3 3",key:"svg-4"}]]);/**
442
442
  * @license @tabler/icons-react v3.12.0 - MIT
443
443
  *
444
444
  * This source code is licensed under the MIT license.
445
445
  * See the LICENSE file in the root directory of this source tree.
446
- */var Mz=be("outline","text-recognition","IconTextRecognition",[["path",{d:"M4 8v-2a2 2 0 0 1 2 -2h2",key:"svg-0"}],["path",{d:"M4 16v2a2 2 0 0 0 2 2h2",key:"svg-1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v2",key:"svg-2"}],["path",{d:"M16 20h2a2 2 0 0 0 2 -2v-2",key:"svg-3"}],["path",{d:"M12 16v-7",key:"svg-4"}],["path",{d:"M9 9h6",key:"svg-5"}]]);/**
446
+ */var Oz=be("outline","text-recognition","IconTextRecognition",[["path",{d:"M4 8v-2a2 2 0 0 1 2 -2h2",key:"svg-0"}],["path",{d:"M4 16v2a2 2 0 0 0 2 2h2",key:"svg-1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v2",key:"svg-2"}],["path",{d:"M16 20h2a2 2 0 0 0 2 -2v-2",key:"svg-3"}],["path",{d:"M12 16v-7",key:"svg-4"}],["path",{d:"M9 9h6",key:"svg-5"}]]);/**
447
447
  * @license @tabler/icons-react v3.12.0 - MIT
448
448
  *
449
449
  * This source code is licensed under the MIT license.
@@ -458,7 +458,7 @@ Error generating stack: `+i.message+`
458
458
  *
459
459
  * This source code is licensed under the MIT license.
460
460
  * See the LICENSE file in the root directory of this source tree.
461
- */var Oz=be("outline","webhook","IconWebhook",[["path",{d:"M4.876 13.61a4 4 0 1 0 6.124 3.39h6",key:"svg-0"}],["path",{d:"M15.066 20.502a4 4 0 1 0 1.934 -7.502c-.706 0 -1.424 .179 -2 .5l-3 -5.5",key:"svg-1"}],["path",{d:"M16 8a4 4 0 1 0 -8 0c0 1.506 .77 2.818 2 3.5l-3 5.5",key:"svg-2"}]]);/**
461
+ */var Lz=be("outline","webhook","IconWebhook",[["path",{d:"M4.876 13.61a4 4 0 1 0 6.124 3.39h6",key:"svg-0"}],["path",{d:"M15.066 20.502a4 4 0 1 0 1.934 -7.502c-.706 0 -1.424 .179 -2 .5l-3 -5.5",key:"svg-1"}],["path",{d:"M16 8a4 4 0 1 0 -8 0c0 1.506 .77 2.818 2 3.5l-3 5.5",key:"svg-2"}]]);/**
462
462
  * @license @tabler/icons-react v3.12.0 - MIT
463
463
  *
464
464
  * This source code is licensed under the MIT license.
@@ -468,7 +468,7 @@ Error generating stack: `+i.message+`
468
468
  *
469
469
  * This source code is licensed under the MIT license.
470
470
  * See the LICENSE file in the root directory of this source tree.
471
- */var Lz=be("filled","circle-filled","IconCircleFilled",[["path",{d:"M7 3.34a10 10 0 1 1 -4.995 8.984l-.005 -.324l.005 -.324a10 10 0 0 1 4.995 -8.336z",key:"svg-0"}]]);class Lk extends p.Component{constructor(t){super(t),this.state={lastLocation:window.location.toString()}}static getDerivedStateFromError(t){return{error:t,lastLocation:window.location.toString()}}componentDidUpdate(t,n){window.location.toString()!==this.state.lastLocation&&this.setState({lastLocation:window.location.toString(),error:void 0})}shouldComponentUpdate(t,n){return!!(this.props.children!==t.children||n.error&&!this.state.error||this.state.lastLocation!==window.location.toString())}componentDidCatch(t,n){console.error("Uncaught error:",t,n)}render(){return this.state.error?s.jsx(Vi,{icon:s.jsx(Sl,{size:16}),title:"Something went wrong",color:"red",children:De(this.state.error)}):this.props.children}}function Jr(){return s.jsx(mn,{style:{width:"100%",height:"100vh"},children:s.jsx(Zn,{})})}const $z="_main_g2hyx_1",Fz={main:$z};function yt(e){e.preventDefault(),e.stopPropagation()}function $k(e){if(Cw(e))return!0;if(e instanceof HTMLTableCellElement){const t=e.children;if(t.length===1&&Cw(t[0]))return!0}return!1}function Cw(e){return e instanceof HTMLInputElement&&e.type==="checkbox"}function Ge(e){const t=Lh(),{to:n,suffix:r,label:o,onClick:i,children:a,...l}=e;let c=zz(n);return r&&(c+="/"+r),s.jsx(Ze,{href:c,"aria-label":o,onClick:u=>{yt(u),i?i(u):n&&t(c)},...l,children:a})}function zz(e){if(e){if(typeof e=="string")return Bz(e);if(ni(e))return Uz(e);if(Qs(e))return Vz(e)}return"#"}function Bz(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:"/"+e}function Uz(e){return`/${e.resourceType}/${e.id}`}function Vz(e){return`/${e.reference}`}function Wz(e){const t=e.split(" ").filter(Boolean);return t.length>1?t[0][0]+t[t.length-1][0]:t.length===1?t[0][0]:""}function Hi(e){const t=wt(e.value),n=t?Wo(t):e.alt??"",r=Wz(n),o=(t&&o6(t))??e.src,i=Rk(o??void 0),a=e.radius??"xl",l={...e,value:void 0,link:void 0};return e.link?s.jsx(Ge,{to:t,children:s.jsx(Ts,{src:i,alt:n,radius:a,...l,children:r})}):s.jsx(Ts,{src:i,alt:n,radius:a,...l,children:r})}const Hz="_logoButton_189g3_1",qz="_user_189g3_11",Gz="_userName_189g3_21",Qz="_userActive_189g3_31",sd={logoButton:Hz,user:qz,userName:Gz,userActive:Qz};function qx(e){const t=e.value;return t?s.jsx(s.Fragment,{children:fu(t,e.options)}):null}function Kz(e){var c,u,d;const t=Oh(),{medplum:n,profile:r,navigate:o}=t,i=n.getLogins(),{colorScheme:a,setColorScheme:l}=aI();return s.jsxs(s.Fragment,{children:[s.jsxs(Oe,{align:"center",p:"xl",children:[s.jsx(Hi,{size:"xl",radius:100,value:t.profile}),s.jsx(qx,{value:(u=(c=t.profile)==null?void 0:c.name)==null?void 0:u[0]}),s.jsx(fe,{c:"dimmed",size:"xs",children:(d=n.getActiveLogin())==null?void 0:d.project.display})]}),i.length>1&&s.jsx(J.Divider,{}),i.map(f=>f.profile.reference!==st(t.profile)&&s.jsx(J.Item,{onClick:()=>{n.setActiveLogin(f).then(()=>window.location.reload()).catch(console.log)},children:s.jsxs(te,{children:[s.jsx(Ts,{radius:"xl"}),s.jsxs("div",{style:{flex:1},children:[s.jsx(fe,{size:"sm",fw:500,children:f.profile.display}),s.jsx(fe,{c:"dimmed",size:"xs",children:f.project.display})]})]})},f.profile.reference)),s.jsx(J.Divider,{}),s.jsx(te,{justify:"center",children:s.jsx(cx,{size:"xs",value:a,onChange:f=>l(f),data:[{label:"Light",value:"light"},{label:"Dark",value:"dark"},{label:"Auto",value:"auto"}]})}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(Az,{size:14,stroke:1.5}),onClick:()=>o("/signin"),children:"Add another account"}),s.jsx(J.Item,{leftSection:s.jsx(Tg,{size:14,stroke:1.5}),onClick:()=>o(`/${st(r)}`),children:"Account settings"}),s.jsx(J.Item,{leftSection:s.jsx(vz,{size:14,stroke:1.5}),onClick:async()=>{await n.signOut(),o("/signin")},children:"Sign out"}),s.jsx(fe,{size:"xs",c:"dimmed",ta:"center",children:e.version})]})}const Yz={selectedItems:"selected-items"};function Gx(e){const t=nu({onDropdownClose:()=>t.resetSelectedOption(),onDropdownOpen:()=>t.updateSelectedOptionIndex("active")}),{name:n,label:r,description:o,error:i,defaultValue:a,toOption:l,loadOptions:c,itemComponent:u,onChange:d,onCreate:f,creatable:h,clearable:m,required:g,placeholder:v,leftSection:S,maxValues:y,optionsDropdownMaxHeight:w=320,...b}=e,x=b.disabled,C=Xz(a),[j,T]=p.useState(""),[E,_]=p.useState(),[k,A]=p.useState(),[O,U]=p.useState(),[N,F]=p.useState(C.map(l)),[D,R]=p.useState([]),P=u??Jz,$=p.useRef();$.current=j;const L=p.useRef(),V=p.useRef(),K=p.useRef();K.current=E;const ie=p.useRef();ie.current=k;const Re=p.useRef();Re.current=O;const ae=p.useRef();ae.current=D;const Ee=p.useCallback(()=>{if(_(void 0),$.current===V.current&&c===L.current)return;V.current=$.current,L.current=c;const Te=new AbortController;A(Te),c($.current??"",Te.signal).then(Pe=>{Te.signal.aborted||(R(Pe.map(l)),A(void 0),Re.current?(Pe.length>0&&d(Pe.slice(0,1)),U(!1)):Pe.length>0&&t.openDropdown())}).catch(Pe=>{Te.signal.aborted||Pe.message.includes("aborted")||he({color:"red",message:De(Pe)})})},[t,c,d,l]),Fe=p.useCallback(Te=>{(D&&D.length>0||h)&&t.openDropdown(),t.updateSelectedOptionIndex(),T(Te.currentTarget.value),ie.current&&(ie.current.abort(),A(void 0)),K.current!==void 0&&window.clearTimeout(K.current);const Pe=window.setTimeout(()=>Ee(),100);_(Pe)},[t,D,h,Ee]),me=p.useCallback(Te=>{const Pe=N.some(Z=>Z.value===Te),Xe=Pe?N.filter(Z=>Z.value!==Te):[...N];let Qe=D==null?void 0:D.find(Z=>Z.value===Te);if(!Qe&&h!==!1&&f){const Z=f(Te);Qe=l(Z)}if(Qe){if(y===0){d([Qe.resource]),N.length>0&&F([]);return}Pe||Xe.push(Qe)}if(y!==void 0)for(;Xe.length>y;)Xe.shift();d(Xe.map(Z=>Z.resource)),F(Xe)},[h,D,N,y,d,f,l]),Le=p.useMemo(()=>{if(!x)return Te=>{x||(y===1&&(T(""),R([]),t.closeDropdown()),V.current=void 0,me(Te==="$create"?j:Te))}},[me,t,x,y,j]),nt=p.useCallback(Te=>{const Pe=N.filter(Xe=>Xe.value!==Te.value);d(Pe.map(Xe=>Xe.resource)),F(Pe)},[N,d]),Tt=p.useCallback(Te=>{Te.key==="Enter"?(E||k)&&U(!0):Te.key==="Backspace"&&j.length===0&&(yt(Te),nt(N[N.length-1]))},[k,nt,j.length,N,E]);p.useEffect(()=>()=>{ie.current&&ie.current.abort()},[]);const Ve=!x&&m&&N.length>0&&s.jsx(Me.ClearButton,{title:"Clear all",size:16,onClear:()=>{T(""),F([]),d([]),t.closeDropdown()}});return s.jsxs(Me,{store:t,onOptionSubmit:Le,withinPortal:!0,shadow:"xl",...b,children:[s.jsx(Me.DropdownTarget,{children:s.jsx(el,{label:r,description:o,error:i,className:e.className,leftSection:S,rightSection:k?s.jsx(Zn,{size:16}):Ve,required:g,disabled:x,children:s.jsxs(Ps.Group,{"data-testid":Yz.selectedItems,children:[N.map(Te=>s.jsx(Ps,{withRemoveButton:!x,onRemove:()=>nt(Te),children:Te.label},Te.value)),!x&&(y===void 0||y===0||N.length<y)&&s.jsx(Me.EventsTarget,{children:s.jsx(el.Field,{role:"searchbox",name:n,value:j,placeholder:v,onFocus:Fe,onBlur:()=>{t.closeDropdown(),T("")},onKeyDown:Tt,onChange:Fe})})]})})}),s.jsx(Me.Dropdown,{children:s.jsx(Me.Options,{children:s.jsxs(eh,{type:"scroll",mah:w,children:[D.map(Te=>{const Pe=N.some(Xe=>Xe.value===Te.value);return s.jsx(Me.Option,{value:Te.value,active:Pe,children:s.jsx(P,{...Te,active:Pe})},Te.value)}),h&&j.trim().length>0&&s.jsxs(Me.Option,{value:"$create",children:["+ Create ",j]}),!h&&j.trim().length>0&&D.length===0&&s.jsx(Me.Empty,{children:"Nothing found"})]})})})]})}function Xz(e){return e?Array.isArray(e)?e:[e]:[]}function Jz(e){return s.jsxs(te,{gap:"xs",children:[e.active&&s.jsx(Ks,{size:12}),s.jsx("span",{children:e.label})]})}const Zz="_searchInput_dick8_1",eB={searchInput:Zz};function tB(e){return{value:e.id,label:Wo(e),resource:e}}function nB(e){const t=Lh(),n=se(),r=p.useCallback(async(i,a)=>{const l=oB(i),c={signal:a},u=await n.graphql(l,void 0,void 0,c);return iB(u,i)},[n]),o=p.useCallback(i=>{i.length>0&&t(`/${st(i[0])}`)},[t]);return s.jsx(Gx,{size:"sm",radius:"md",className:eB.searchInput,leftSection:s.jsx(_z,{size:16}),placeholder:"Search",itemComponent:rB,toOption:tB,onChange:o,loadOptions:r,maxValues:0,clearable:!1},`${e.pathname}?${e.searchParams}`)}const rB=p.forwardRef(({resource:e,active:t,...n},r)=>{var i;let o;return e.resourceType==="Patient"?o=e.birthDate:e.resourceType==="ServiceRequest"&&(o=(i=e.subject)==null?void 0:i.display),s.jsx("div",{ref:r,...n,children:s.jsxs(te,{wrap:"nowrap",children:[s.jsx(Hi,{value:e}),s.jsxs("div",{children:[s.jsx(fe,{children:Wo(e)}),s.jsx(fe,{size:"xs",c:"dimmed",children:o})]})]})})});function oB(e){const t=JSON.stringify(e);return nk(e)?`{
471
+ */var $z=be("filled","circle-filled","IconCircleFilled",[["path",{d:"M7 3.34a10 10 0 1 1 -4.995 8.984l-.005 -.324l.005 -.324a10 10 0 0 1 4.995 -8.336z",key:"svg-0"}]]);class Lk extends p.Component{constructor(t){super(t),this.state={lastLocation:window.location.toString()}}static getDerivedStateFromError(t){return{error:t,lastLocation:window.location.toString()}}componentDidUpdate(t,n){window.location.toString()!==this.state.lastLocation&&this.setState({lastLocation:window.location.toString(),error:void 0})}shouldComponentUpdate(t,n){return!!(this.props.children!==t.children||n.error&&!this.state.error||this.state.lastLocation!==window.location.toString())}componentDidCatch(t,n){console.error("Uncaught error:",t,n)}render(){return this.state.error?s.jsx(Vi,{icon:s.jsx(Sl,{size:16}),title:"Something went wrong",color:"red",children:De(this.state.error)}):this.props.children}}function Jr(){return s.jsx(mn,{style:{width:"100%",height:"100vh"},children:s.jsx(Zn,{})})}const Fz="_main_g2hyx_1",zz={main:Fz};function yt(e){e.preventDefault(),e.stopPropagation()}function $k(e){if(Cw(e))return!0;if(e instanceof HTMLTableCellElement){const t=e.children;if(t.length===1&&Cw(t[0]))return!0}return!1}function Cw(e){return e instanceof HTMLInputElement&&e.type==="checkbox"}function Ge(e){const t=Lh(),{to:n,suffix:r,label:o,onClick:i,children:a,...l}=e;let c=Bz(n);return r&&(c+="/"+r),s.jsx(Ze,{href:c,"aria-label":o,onClick:u=>{yt(u),i?i(u):n&&t(c)},...l,children:a})}function Bz(e){if(e){if(typeof e=="string")return Uz(e);if(ni(e))return Vz(e);if(Qs(e))return Wz(e)}return"#"}function Uz(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:"/"+e}function Vz(e){return`/${e.resourceType}/${e.id}`}function Wz(e){return`/${e.reference}`}function Hz(e){const t=e.split(" ").filter(Boolean);return t.length>1?t[0][0]+t[t.length-1][0]:t.length===1?t[0][0]:""}function Hi(e){const t=wt(e.value),n=t?Wo(t):e.alt??"",r=Hz(n),o=(t&&o6(t))??e.src,i=Rk(o??void 0),a=e.radius??"xl",l={...e,value:void 0,link:void 0};return e.link?s.jsx(Ge,{to:t,children:s.jsx(Ts,{src:i,alt:n,radius:a,...l,children:r})}):s.jsx(Ts,{src:i,alt:n,radius:a,...l,children:r})}const qz="_logoButton_189g3_1",Gz="_user_189g3_11",Qz="_userName_189g3_21",Kz="_userActive_189g3_31",sd={logoButton:qz,user:Gz,userName:Qz,userActive:Kz};function qx(e){const t=e.value;return t?s.jsx(s.Fragment,{children:fu(t,e.options)}):null}function Yz(e){var c,u,d;const t=Oh(),{medplum:n,profile:r,navigate:o}=t,i=n.getLogins(),{colorScheme:a,setColorScheme:l}=aI();return s.jsxs(s.Fragment,{children:[s.jsxs(Oe,{align:"center",p:"xl",children:[s.jsx(Hi,{size:"xl",radius:100,value:t.profile}),s.jsx(qx,{value:(u=(c=t.profile)==null?void 0:c.name)==null?void 0:u[0]}),s.jsx(fe,{c:"dimmed",size:"xs",children:(d=n.getActiveLogin())==null?void 0:d.project.display})]}),i.length>1&&s.jsx(J.Divider,{}),i.map(f=>f.profile.reference!==st(t.profile)&&s.jsx(J.Item,{onClick:()=>{n.setActiveLogin(f).then(()=>window.location.reload()).catch(console.log)},children:s.jsxs(te,{children:[s.jsx(Ts,{radius:"xl"}),s.jsxs("div",{style:{flex:1},children:[s.jsx(fe,{size:"sm",fw:500,children:f.profile.display}),s.jsx(fe,{c:"dimmed",size:"xs",children:f.project.display})]})]})},f.profile.reference)),s.jsx(J.Divider,{}),s.jsx(te,{justify:"center",children:s.jsx(cx,{size:"xs",value:a,onChange:f=>l(f),data:[{label:"Light",value:"light"},{label:"Dark",value:"dark"},{label:"Auto",value:"auto"}]})}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(Nz,{size:14,stroke:1.5}),onClick:()=>o("/signin"),children:"Add another account"}),s.jsx(J.Item,{leftSection:s.jsx(Tg,{size:14,stroke:1.5}),onClick:()=>o(`/${st(r)}`),children:"Account settings"}),s.jsx(J.Item,{leftSection:s.jsx(yz,{size:14,stroke:1.5}),onClick:async()=>{await n.signOut(),o("/signin")},children:"Sign out"}),s.jsx(fe,{size:"xs",c:"dimmed",ta:"center",children:e.version})]})}const Xz={selectedItems:"selected-items"};function Gx(e){const t=nu({onDropdownClose:()=>t.resetSelectedOption(),onDropdownOpen:()=>t.updateSelectedOptionIndex("active")}),{name:n,label:r,description:o,error:i,defaultValue:a,toOption:l,loadOptions:c,itemComponent:u,onChange:d,onCreate:f,creatable:h,clearable:m,required:g,placeholder:v,leftSection:S,maxValues:y,optionsDropdownMaxHeight:w=320,...b}=e,x=b.disabled,C=Jz(a),[j,T]=p.useState(""),[E,_]=p.useState(),[k,A]=p.useState(),[O,U]=p.useState(),[N,F]=p.useState(C.map(l)),[D,R]=p.useState([]),P=u??Zz,$=p.useRef();$.current=j;const L=p.useRef(),V=p.useRef(),K=p.useRef();K.current=E;const ie=p.useRef();ie.current=k;const Re=p.useRef();Re.current=O;const ae=p.useRef();ae.current=D;const Ee=p.useCallback(()=>{if(_(void 0),$.current===V.current&&c===L.current)return;V.current=$.current,L.current=c;const Te=new AbortController;A(Te),c($.current??"",Te.signal).then(Pe=>{Te.signal.aborted||(R(Pe.map(l)),A(void 0),Re.current?(Pe.length>0&&d(Pe.slice(0,1)),U(!1)):Pe.length>0&&t.openDropdown())}).catch(Pe=>{Te.signal.aborted||Pe.message.includes("aborted")||he({color:"red",message:De(Pe)})})},[t,c,d,l]),Fe=p.useCallback(Te=>{(D&&D.length>0||h)&&t.openDropdown(),t.updateSelectedOptionIndex(),T(Te.currentTarget.value),ie.current&&(ie.current.abort(),A(void 0)),K.current!==void 0&&window.clearTimeout(K.current);const Pe=window.setTimeout(()=>Ee(),100);_(Pe)},[t,D,h,Ee]),me=p.useCallback(Te=>{const Pe=N.some(Z=>Z.value===Te),Xe=Pe?N.filter(Z=>Z.value!==Te):[...N];let Qe=D==null?void 0:D.find(Z=>Z.value===Te);if(!Qe&&h!==!1&&f){const Z=f(Te);Qe=l(Z)}if(Qe){if(y===0){d([Qe.resource]),N.length>0&&F([]);return}Pe||Xe.push(Qe)}if(y!==void 0)for(;Xe.length>y;)Xe.shift();d(Xe.map(Z=>Z.resource)),F(Xe)},[h,D,N,y,d,f,l]),Le=p.useMemo(()=>{if(!x)return Te=>{x||(y===1&&(T(""),R([]),t.closeDropdown()),V.current=void 0,me(Te==="$create"?j:Te))}},[me,t,x,y,j]),nt=p.useCallback(Te=>{const Pe=N.filter(Xe=>Xe.value!==Te.value);d(Pe.map(Xe=>Xe.resource)),F(Pe)},[N,d]),Tt=p.useCallback(Te=>{Te.key==="Enter"?(E||k)&&U(!0):Te.key==="Backspace"&&j.length===0&&(yt(Te),nt(N[N.length-1]))},[k,nt,j.length,N,E]);p.useEffect(()=>()=>{ie.current&&ie.current.abort()},[]);const Ve=!x&&m&&N.length>0&&s.jsx(Me.ClearButton,{title:"Clear all",size:16,onClear:()=>{T(""),F([]),d([]),t.closeDropdown()}});return s.jsxs(Me,{store:t,onOptionSubmit:Le,withinPortal:!0,shadow:"xl",...b,children:[s.jsx(Me.DropdownTarget,{children:s.jsx(el,{label:r,description:o,error:i,className:e.className,leftSection:S,rightSection:k?s.jsx(Zn,{size:16}):Ve,required:g,disabled:x,children:s.jsxs(Ps.Group,{"data-testid":Xz.selectedItems,children:[N.map(Te=>s.jsx(Ps,{withRemoveButton:!x,onRemove:()=>nt(Te),children:Te.label},Te.value)),!x&&(y===void 0||y===0||N.length<y)&&s.jsx(Me.EventsTarget,{children:s.jsx(el.Field,{role:"searchbox",name:n,value:j,placeholder:v,onFocus:Fe,onBlur:()=>{t.closeDropdown(),T("")},onKeyDown:Tt,onChange:Fe})})]})})}),s.jsx(Me.Dropdown,{children:s.jsx(Me.Options,{children:s.jsxs(eh,{type:"scroll",mah:w,children:[D.map(Te=>{const Pe=N.some(Xe=>Xe.value===Te.value);return s.jsx(Me.Option,{value:Te.value,active:Pe,children:s.jsx(P,{...Te,active:Pe})},Te.value)}),h&&j.trim().length>0&&s.jsxs(Me.Option,{value:"$create",children:["+ Create ",j]}),!h&&j.trim().length>0&&D.length===0&&s.jsx(Me.Empty,{children:"Nothing found"})]})})})]})}function Jz(e){return e?Array.isArray(e)?e:[e]:[]}function Zz(e){return s.jsxs(te,{gap:"xs",children:[e.active&&s.jsx(Ks,{size:12}),s.jsx("span",{children:e.label})]})}const eB="_searchInput_dick8_1",tB={searchInput:eB};function nB(e){return{value:e.id,label:Wo(e),resource:e}}function rB(e){const t=Lh(),n=se(),r=p.useCallback(async(i,a)=>{const l=iB(i),c={signal:a},u=await n.graphql(l,void 0,void 0,c);return sB(u,i)},[n]),o=p.useCallback(i=>{i.length>0&&t(`/${st(i[0])}`)},[t]);return s.jsx(Gx,{size:"sm",radius:"md",className:tB.searchInput,leftSection:s.jsx(Dz,{size:16}),placeholder:"Search",itemComponent:oB,toOption:nB,onChange:o,loadOptions:r,maxValues:0,clearable:!1},`${e.pathname}?${e.searchParams}`)}const oB=p.forwardRef(({resource:e,active:t,...n},r)=>{var i;let o;return e.resourceType==="Patient"?o=e.birthDate:e.resourceType==="ServiceRequest"&&(o=(i=e.subject)==null?void 0:i.display),s.jsx("div",{ref:r,...n,children:s.jsxs(te,{wrap:"nowrap",children:[s.jsx(Hi,{value:e}),s.jsxs("div",{children:[s.jsx(fe,{children:Wo(e)}),s.jsx(fe,{size:"xs",c:"dimmed",children:o})]})]})})});function iB(e){const t=JSON.stringify(e);return nk(e)?`{
472
472
  Patients1: PatientList(_id: ${t}, _count: 1) {
473
473
  resourceType
474
474
  id
@@ -531,16 +531,16 @@ Error generating stack: `+i.message+`
531
531
  display
532
532
  }
533
533
  }
534
- }`.replace(/\s+/g," ")}function iB(e,t){const n=[];return e.data.Patients1&&n.push(...e.data.Patients1),e.data.Patients2&&n.push(...e.data.Patients2),e.data.ServiceRequestList&&n.push(...e.data.ServiceRequestList),aB(sB(n),t).slice(0,5)}function sB(e){const t=new Set,n=[];for(const r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function aB(e,t){return e.sort((n,r)=>Ew(r,t)-Ew(n,t))}function Ew(e,t){let n=0;if(e.identifier)for(const r of e.identifier)n=Math.max(n,Tw(r.value,t));if(e.resourceType==="Patient"&&e.name)for(const r of e.name)n=Math.max(n,Tw(fu(r),t));return n}function Tw(e,t){if(!e)return 0;const n=e.toLowerCase().indexOf(t.toLowerCase());return n<0?0:100-n}function lB(e){var o;const t=$h(),[n,r]=p.useState(!1);return s.jsx(Jn.Header,{p:8,style:{zIndex:101},children:s.jsxs(te,{justify:"space-between",children:[s.jsxs(te,{gap:"xs",children:[s.jsx(bn,{className:sd.logoButton,onClick:e.navbarToggle,children:e.logo}),!e.headerSearchDisabled&&s.jsx(nB,{pathname:e.pathname,searchParams:e.searchParams})]}),s.jsxs(te,{gap:"lg",pr:"sm",children:[e.notifications,s.jsxs(J,{width:260,shadow:"xl",position:"bottom-end",transitionProps:{transition:"pop-top-right"},opened:n,onClose:()=>r(!1),children:[s.jsx(J.Target,{children:s.jsx(bn,{className:rt(sd.user,{[sd.userActive]:n}),onClick:()=>r(i=>!i),children:s.jsxs(te,{gap:7,children:[s.jsx(Hi,{value:t,radius:"xl",size:24}),s.jsx(fe,{size:"sm",className:sd.userName,children:fu((o=t==null?void 0:t.name)==null?void 0:o[0])}),s.jsx(Bx,{size:12,stroke:1.5})]})})}),s.jsx(J.Dropdown,{children:s.jsx(Kz,{version:e.version})})]})]})]})})}function cB(e){const t={};for(const n of Array.from(e.elements))n instanceof HTMLInputElement?uB(t,n):n instanceof HTMLTextAreaElement?t[n.name]=n.value:n instanceof HTMLSelectElement&&dB(t,n);return t}function uB(e,t){t.disabled||(t.type==="checkbox"||t.type==="radio")&&!t.checked||(e[t.name]=t.value)}function dB(e,t){e[t.name]=t.value}function Ke(e){return s.jsx("form",{style:e.style,"data-testid":e.testid,onSubmit:t=>{t.preventDefault();const n=cB(t.target);e.onSubmit&&e.onSubmit(n)},children:e.children})}function fB(e){const t=se(),n=t.getUserConfiguration();function r(o){var d,f;const{menuname:i,bookmarkname:a}=o,l=`${e.pathname}?${e.searchParams.toString()}`,c=Xr(n),u=(d=c.menu)==null?void 0:d.find(({title:h})=>h===i);(f=u==null?void 0:u.link)==null||f.push({name:a,target:l}),t.updateResource(c).then(h=>{n.menu=h.menu,t.dispatchEvent({type:"change"}),he({color:"green",message:"Success"}),e.onOk()}).catch(h=>{he({color:"red",message:De(h)})})}return s.jsx(wn,{title:"Add Bookmark",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:e.onCancel,children:s.jsx(Ke,{onSubmit:r,children:s.jsxs(Oe,{children:[s.jsx(hB,{config:n}),s.jsx(ve,{label:"Bookmark Name",type:"text",name:"bookmarkname",placeholder:"Bookmark Name",withAsterisk:!0}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{mt:"sm",type:"submit",children:"OK"})})]})})})}function hB(e){function t(r){var o;return(o=r==null?void 0:r.menu)==null?void 0:o.map(i=>i.title)}const n=t(e.config);return s.jsx(It,{name:"menuname",defaultValue:n[0],label:"Select Menu Option",data:n,withAsterisk:!0})}function Fk(e){return typeof e.code=="string"?e.code:JSON.stringify(e)}function pB(e){return typeof e.display=="string"?e.display:Fk(e)}function mB(e){return{value:Fk(e),label:pB(e),resource:e}}function gB(e){return{code:e,display:e}}function Qx(e){const t=se(),{binding:n,creatable:r,clearable:o,expandParams:i,withHelpText:a,...l}=e,c=p.useCallback(async(u,d)=>{var g;if(!n)return[];const h=(g=(await t.valueSetExpand({...i,url:n,filter:u},{signal:d})).expansion)==null?void 0:g.contains,m=[];for(const v of h)v.code&&!m.some(S=>S.code===v.code)&&m.push(v);return m},[t,i,n]);return s.jsx(Gx,{...l,creatable:r??!0,clearable:o??!0,toOption:mB,loadOptions:c,onCreate:gB,itemComponent:a?vB:void 0})}const vB=p.forwardRef(({label:e,resource:t,active:n,...r},o)=>s.jsx("div",{ref:o,...r,children:s.jsxs(te,{wrap:"nowrap",gap:"xs",children:[n&&s.jsx(Ks,{size:12}),s.jsxs("div",{children:[s.jsx(fe,{children:e}),s.jsx(fe,{size:"xs",c:"dimmed",children:`${t.system}#${t.code}`})]})]})}));function zk(e){const{defaultValue:t,onChange:n,withHelpText:r,...o}=e,[i,a]=p.useState(t);function l(c){const u=c[0],d=xB(u);a(d),n&&n(d)}return s.jsx(Qx,{defaultValue:yB(i),onChange:l,withHelpText:r??!0,...o})}function yB(e){return e?{code:e}:void 0}function xB(e){return e==null?void 0:e.code}function Kx(e){const[t,n]=p.useState(e.defaultValue),r=e.onChange,o=p.useCallback(i=>{n(i),r&&r(i)},[r]);return s.jsx(zk,{disabled:e.disabled,"data-autofocus":e.autoFocus,"data-testid":e.testId,defaultValue:t,onChange:o,name:e.name,placeholder:e.placeholder,binding:"https://medplum.com/fhir/ValueSet/resource-types",creatable:!1,maxValues:e.maxValues??1,clearable:!1,withHelpText:!1})}const bB="_menuTitle_9g6l5_1",wB="_link_9g6l5_9",SB="_linkActive_9g6l5_38",Pg={menuTitle:bB,link:wB,linkActive:SB};function jB(e){var l;const t=Lh(),n=TB(e.pathname,e.searchParams,e.menus),[r,o]=p.useState(!1);function i(c,u){c.stopPropagation(),c.preventDefault(),t(u),window.innerWidth<768&&e.closeNavbar()}function a(c){c&&t(`/${c}`)}return s.jsxs(s.Fragment,{children:[s.jsx(Jn.Navbar,{children:s.jsxs(Ir,{p:"xs",children:[!e.resourceTypeSearchDisabled&&s.jsx(Jn.Section,{mb:"sm",children:s.jsx(Kx,{name:"resourceType",placeholder:"Resource Type",maxValues:0,onChange:c=>a(c)},window.location.pathname)}),s.jsxs(Jn.Section,{grow:!0,children:[(l=e.menus)==null?void 0:l.map(c=>{var u;return s.jsxs(p.Fragment,{children:[s.jsx(fe,{className:Pg.menuTitle,children:c.title}),(u=c.links)==null?void 0:u.map(d=>s.jsxs(CB,{to:d.href,active:d.href===(n==null?void 0:n.href),onClick:f=>i(f,d.href),children:[s.jsx(EB,{to:d.href,icon:d.icon}),s.jsx("span",{children:d.label})]},d.href))]},`menu-${c.title}`)}),e.displayAddBookmark&&s.jsx(oe,{variant:"subtle",size:"xs",mt:"xl",leftSection:s.jsx(Cz,{size:"0.75rem"}),onClick:()=>o(!0),children:"Add Bookmark"})]})]})}),e.pathname&&e.searchParams&&s.jsx(fB,{pathname:e.pathname,searchParams:e.searchParams,visible:r,onOk:()=>o(!1),onCancel:()=>o(!1)})]})}function CB(e){return s.jsx(Ge,{onClick:e.onClick,to:e.to,className:rt(Pg.link,{[Pg.linkActive]:e.active}),children:e.children})}function EB(e){return e.icon?e.icon:s.jsx(Rh,{w:30})}function TB(e,t,n){if(!e||!t||!n)return;let r,o=0;for(const i of n)if(i.links)for(const a of i.links){const l=PB(e,t,a.href);l>o&&(o=l,r=a)}return r}function PB(e,t,n){const r=new URL(n,"https://example.com");if(e!==r.pathname)return 0;const o=["_count","_offset"];for(const[a,l]of r.searchParams.entries())if(!o.includes(a)&&t.get(a)!==l)return 0;let i=1;for(const[a,l]of t.entries())o.includes(a)||r.searchParams.get(a)===l&&i++;return i}function kB(e){const[t,n]=p.useState(localStorage.navbarOpen==="true"),r=se(),o=$h();p.useEffect(()=>{function c(){he({color:"red",message:"No connection to server",autoClose:!1})}return r.addEventListener("offline",c),()=>r.removeEventListener("offline",c)},[r]);function i(c){localStorage.navbarOpen=c.toString(),n(c)}function a(){i(!1)}function l(){i(!t)}return r.isLoading()?s.jsx(Jr,{}):s.jsxs(Jn,{header:{height:60},navbar:{width:250,breakpoint:"sm",collapsed:{desktop:!o||!t,mobile:!o||!t}},padding:0,children:[o&&s.jsx(lB,{pathname:e.pathname,searchParams:e.searchParams,headerSearchDisabled:e.headerSearchDisabled,logo:e.logo,version:e.version,navbarToggle:l,notifications:e.notifications}),o&&t?s.jsx(jB,{pathname:e.pathname,searchParams:e.searchParams,menus:e.menus,closeNavbar:a,displayAddBookmark:e.displayAddBookmark,resourceTypeSearchDisabled:e.resourceTypeSearchDisabled}):void 0,s.jsx(Jn.Main,{className:Fz.main,children:s.jsx(Lk,{children:s.jsx(p.Suspense,{fallback:s.jsx(Jr,{}),children:e.children})})})]})}function mu(e){const{contentType:t,url:n,title:r}=e.value??{},o=Rk(n);return o?s.jsxs("div",{"data-testid":"attachment-display",children:[(t==null?void 0:t.startsWith("image/"))&&s.jsx("img",{"data-testid":"attachment-image",style:{maxWidth:e.maxWidth},src:o,alt:r}),(t==null?void 0:t.startsWith("video/"))&&s.jsx("video",{"data-testid":"attachment-video",style:{maxWidth:e.maxWidth},controls:!0,children:s.jsx("source",{type:t,src:o})}),((t==null?void 0:t.startsWith("text/"))||t==="application/json"||t==="application/pdf")&&s.jsx("div",{"data-testid":"attachment-iframe",style:{maxWidth:e.maxWidth,minHeight:400},children:s.jsx("iframe",{width:"100%",height:"400",src:o+"#navpanes=0",allowFullScreen:!0,frameBorder:0,seamless:!0})}),s.jsx("div",{"data-testid":"download-link",style:{padding:"2px 16px 16px 16px"},children:s.jsx(Ze,{href:n,"data-testid":"attachment-details",target:"_blank",rel:"noopener noreferrer",download:RB(r),children:r||"Download"})})]}):null}function RB(e){return e!=null&&e.includes(".")?e:void 0}const _B="_root_17n8t_1",DB="_compact_17n8t_25",Pw={root:_B,compact:DB};function Yx(e){const{children:t,compact:n}=e;return s.jsx("dl",{className:rt(Pw.root,{[Pw.compact]:n}),children:t})}function No(e){return s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:e.term}),s.jsx("dd",{children:e.children})]})}function IB(e){var r;const t=(r=e.values)==null?void 0:r.map((o,i)=>s.jsx("div",{children:s.jsx(mu,{value:o,maxWidth:e.maxWidth})},"attatchment-"+i));let n;if(e.includeDescriptionListEntry){if(e.property===void 0)throw new Error("props.property is required when includeDescriptionListEntry is true");if(!Bt(e.path))throw new Error("props.path is required when includeDescriptionListEntry is true");const o=e.path.split(".").pop();n=s.jsx(No,{term:Rs(o),children:t})}else n=s.jsx(s.Fragment,{children:t});return n}function Xx(e){const t=se(),n=p.useRef(null);function r(a){var l;yt(a),(l=n.current)==null||l.click()}function o(a){yt(a);const l=a.target.files;l&&Array.from(l).forEach(i)}function i(a){!a||!a.name||(e.onUploadStart&&e.onUploadStart(),t.createAttachment({data:a,contentType:a.type||"application/octet-stream",filename:a.name,securityContext:e.securityContext,onProgress:e.onUploadProgress}).then(c=>e.onUpload(c)).catch(c=>{e.onUploadError&&e.onUploadError(ht(c))}))}return s.jsxs(s.Fragment,{children:[s.jsx("input",{disabled:e.disabled,type:"file","data-testid":"upload-file-input",style:{display:"none"},ref:n,onChange:a=>o(a)}),e.children({onClick:r,disabled:e.disabled})]})}function AB(e){const[t,n]=p.useState(e.defaultValue??[]),r=p.useRef();r.current=t;function o(i){n(i),e.onChange&&e.onChange(i)}return s.jsxs("table",{style:{width:"100%"},children:[s.jsxs("colgroup",{children:[s.jsx("col",{width:"97%"}),s.jsx("col",{width:"3%"})]}),s.jsxs("tbody",{children:[t.map((i,a)=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(mu,{value:i,maxWidth:200})}),s.jsx("td",{children:s.jsx(tn,{disabled:e.disabled,title:"Remove",variant:"subtle",size:"sm",color:"gray",onClick:l=>{yt(l);const c=t.slice();c.splice(a,1),o(c)},children:s.jsx(vf,{})})})]},`${a}-${t.length}`)),s.jsxs("tr",{children:[s.jsx("td",{}),s.jsx("td",{children:s.jsx(Xx,{disabled:e.disabled,onUpload:i=>{o([...r.current,i])},children:i=>s.jsx(tn,{...i,title:"Add",variant:"subtle",size:"sm",color:i.disabled?"gray":"green",children:s.jsx(Ux,{})})})})]})]})]})}function Bk(e){const[t,n]=p.useState(e.defaultValue);function r(o){n(o),e.onChange&&e.onChange(o)}return t?s.jsxs(s.Fragment,{children:[s.jsx(mu,{value:t,maxWidth:200}),s.jsx(oe,{disabled:e.disabled,onClick:o=>{yt(o),r(void 0)},children:"Remove"})]}):s.jsx(Xx,{disabled:e.disabled,securityContext:e.securityContext,onUpload:r,children:o=>s.jsx(oe,{...o,children:"Upload..."})})}function yo(e){return s.jsx(s.Fragment,{children:Oi(e.value)})}function NB(e){return s.jsx(s.Fragment,{children:qs(e.value)})}function Uk(e){const t=e.value;if(!t)return null;const n=[];return t.value&&n.push(t.value),(t.use||t.system)&&(n.push(" ["),t.use&&n.push(t.use),t.use&&t.system&&n.push(" "),t.system&&n.push(t.system),n.push("]")),s.jsx(s.Fragment,{children:n.join("").trim()})}function MB(e){var n;const t=e.value;return t?s.jsxs(s.Fragment,{children:[t.name,t.name&&": ",(n=t.telecom)==null?void 0:n.map(r=>s.jsx(Uk,{value:r},`telecom-${t.name}-${r.value}`))]}):null}function OB(e){var t,n;return s.jsxs("div",{children:[(t=e.value)==null?void 0:t.system,": ",(n=e.value)==null?void 0:n.value]})}function LB(e){return s.jsx(s.Fragment,{children:D6(e.value)})}function $c(e){return s.jsx(s.Fragment,{children:fi(e.value)})}function Jx(e){return s.jsx(s.Fragment,{children:Mc(e.value)})}function $B(e){const t=e.value;return t?s.jsxs(s.Fragment,{children:[s.jsx($c,{value:t.numerator})," / ",s.jsx($c,{value:t.denominator})]}):null}function bf(e){if(!e.value)return null;const t=e.value.display||e.value.reference||pr(e.value);return e.link!==!1&&e.value.reference?s.jsx(Ge,{to:e.value,children:t}):s.jsx(s.Fragment,{children:t})}function Vk(e,t,n,r){if(!Bt(n==null?void 0:n.slices))return[e];const o=new Array(t.length+1);for(let i=0;i<o.length;i++)o[i]=[];for(const i of e){const a=Tk(i,t,n.discriminator,r);let l=a?t.findIndex(c=>c.name===a):-1;l===-1&&(l=t.length),o[l].push(i)}return o}async function Wk({medplum:e,property:t}){return new Promise((n,r)=>{var l,c;if(!t.slicing){n([]);return}const o=[],i=[],a=[];for(const u of t.slicing.slices){if(!Ek(u)){console.debug("Unsupported slice definition",u);continue}let d;Bt(u.elements)||(d=(c=(l=u.type[0])==null?void 0:l.profile)==null?void 0:c[0]),o.push(u),i.push(d),d&&a.push(e.requestProfileSchema(d))}Promise.all(a).then(()=>{for(let u=0;u<o.length;u++){const d=o[u],f=i[u];if(f){const h=yl(f);d.typeSchema=h}}n(o)}).catch(r)})}function Fh(e,t,n){return t!==void 0?s.jsx(e,{value:t,children:n}):n}function FB(e){var a,l;const{slice:t,property:n}=e,r=((a=t.typeSchema)==null?void 0:a.elements)??t.elements,o=p.useContext(bt),i=p.useMemo(()=>{var c;if(Bt(r))return rl({parentContext:o,elements:r,path:e.path,profileUrl:(c=t.typeSchema)==null?void 0:c.url})},[o,e.path,(l=t.typeSchema)==null?void 0:l.url,r]);return Fh(bt.Provider,i,s.jsx(s.Fragment,{children:e.value.map((c,u)=>s.jsx("div",{children:s.jsx(Zr,{property:n,path:e.path,arrayElement:!0,elementDefinitionType:t.type[0],propertyType:t.type[0].code,value:c,ignoreMissingValues:e.ignoreMissingValues,link:e.link})},`${u}-${e.value.length}`))}))}function zB(e){var g;const{property:t,propertyType:n}=e,r=se(),o=p.useMemo(()=>Array.isArray(e.values)?e.values:[],[e.values]),[i,a]=p.useState(!0),[l,c]=p.useState([]),[u,d]=p.useState(()=>[o]),f=p.useContext(bt);if(p.useEffect(()=>{Wk({medplum:r,property:t}).then(v=>{c(v);const S=Vk(o,v,t.slicing,f.profileUrl);d(S),a(!1)}).catch(v=>{console.error(v),a(!1)})},[r,t,f.profileUrl,d,o]),i)return s.jsx("div",{children:"Loading..."});let h;if(((g=t.type[0])==null?void 0:g.code)!=="Extension"){const v=u[l.length],S=v.map((y,w)=>s.jsx("div",{children:s.jsx(Zr,{path:e.path,arrayElement:!0,property:t,propertyType:n,value:y,ignoreMissingValues:e.ignoreMissingValues,link:e.link})},`${w}-${v.length}`));if(e.includeDescriptionListEntry){if(!Bt(e.path))throw new Error("props.path is required when includeDescriptionListEntry is true");const y=e.path.split(".").pop();h=s.jsx(No,{term:Rs(y),children:S})}else h=s.jsx(s.Fragment,{children:S})}return s.jsxs(s.Fragment,{children:[l.map((v,S)=>{if(!e.path)throw Error(`Displaying a resource property with slices of type ${e.propertyType} requires path`);let y=s.jsx(FB,{path:e.path,slice:v,property:t,value:u[S],ignoreMissingValues:e.ignoreMissingValues,link:e.link},v.name);return e.includeDescriptionListEntry&&(y=s.jsx(No,{term:Rs(v.name),children:y},v.name)),y}),h]})}function gu(e,t,n){const r=vn(e,t,{profileUrl:n});return r?Array.isArray(r)?[r.map(o=>o.value),r[0].type]:[r.value,r.type]:[void 0,"undefined"]}function BB(e,t,n){const r=YP(e,t,n);return r?Array.isArray(r)?[r.map(o=>o.value),r[0].type]:[r.value,r.type]:[void 0,"undefined"]}function UB(e){const{elementDefinitionType:t}=e,n=se(),r=p.useContext(bt),[o,i]=p.useState(QP("Extension")),a=p.useMemo(()=>{if(Bt(t==null?void 0:t.profile))return t.profile[0]},[t]),[l,c]=p.useState(a!==void 0);if(p.useEffect(()=>{a&&(c(!0),n.requestProfileSchema(a).then(()=>{const f=yl(a);c(!1),f&&i(f)}).catch(f=>{c(!1),console.warn(f)}))},[n,a]),a&&(l||!jx(a)))return s.jsx("div",{children:"Loading..."});const u=o.elements["value[x]"];if((u==null?void 0:u.max)!==0){const[f,h]=gu({type:"Extension",value:e.value},"value[x]",a??r.profileUrl);return s.jsx(Zr,{propertyType:h,value:f})}return s.jsx(wf,{path:e.path,value:{type:o.type,value:e.value},compact:e.compact,ignoreMissingValues:e.ignoreMissingValues,link:e.link,profileUrl:a})}function Zr(e){var i;const{property:t,propertyType:n,value:r}=e;if((i=t==null?void 0:t.path)==null?void 0:i.endsWith(".id"))return s.jsxs(q,{component:"div",style:{display:"flex",gap:3,alignItems:"center"},children:[r,!Gt(r)&&s.jsx(qT,{value:r,timeout:2e3,children:({copied:a,copy:l})=>s.jsx(Vs,{label:a?"Copied":"Copy",withArrow:!0,position:"right",children:s.jsx(tn,{variant:"subtle",color:a?"teal":"gray",onClick:l,children:a?s.jsx(Ks,{size:"1rem"}):s.jsx(Ak,{size:"1rem"})})})})]});if(t&&(t.isArray||t.max>1)&&!e.arrayElement)return n===H.Attachment?s.jsx(IB,{values:r,maxWidth:e.maxWidth,includeDescriptionListEntry:e.includeArrayDescriptionListEntry,property:t,path:e.path}):s.jsx(zB,{path:e.path,property:t,propertyType:n,values:r,includeDescriptionListEntry:e.includeArrayDescriptionListEntry,ignoreMissingValues:e.ignoreMissingValues,link:e.link});switch(n){case H.boolean:return s.jsx(s.Fragment,{children:r===void 0?"":(!!r).toString()});case H.SystemString:case H.string:return s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:r});case H.code:case H.date:case H.decimal:case H.id:case H.integer:case H.positiveInt:case H.unsignedInt:case H.uri:case H.url:return s.jsx(s.Fragment,{children:r});case H.canonical:return s.jsx(bf,{value:{reference:r},link:e.link});case H.dateTime:case H.instant:return s.jsx(s.Fragment,{children:Fn(r)});case H.markdown:return s.jsx("pre",{children:r});case H.Address:return s.jsx(V8,{value:r});case H.Annotation:return s.jsx(s.Fragment,{children:r==null?void 0:r.text});case H.Attachment:return s.jsx(mu,{value:r,maxWidth:e.maxWidth});case H.CodeableConcept:return s.jsx(yo,{value:r});case H.Coding:return s.jsx(NB,{value:r});case H.ContactDetail:return s.jsx(MB,{value:r});case H.ContactPoint:return s.jsx(Uk,{value:r});case H.HumanName:return s.jsx(qx,{value:r});case H.Identifier:return s.jsx(OB,{value:r});case H.Money:return s.jsx(LB,{value:r});case H.Period:return s.jsx(s.Fragment,{children:T6(r)});case H.Quantity:case H.Duration:return s.jsx($c,{value:r});case H.Range:return s.jsx(Jx,{value:r});case H.Ratio:return s.jsx($B,{value:r});case H.Reference:return s.jsx(bf,{value:r,link:e.link});case H.Timing:return s.jsx(s.Fragment,{children:sk(r)});case H.Dosage:case H.UsageContext:if(!e.path)throw Error(`Displaying property of type ${e.propertyType} requires path`);return s.jsx(wf,{path:e.path,value:{type:n,value:r},compact:!0,ignoreMissingValues:e.ignoreMissingValues});case H.Extension:if(!e.path)throw Error(`Displaying property of type ${e.propertyType} requires path`);return s.jsx(UB,{path:e.path,value:r,compact:!0,ignoreMissingValues:e.ignoreMissingValues,elementDefinitionType:e.elementDefinitionType});default:if(!t)throw Error(`Displaying property of type ${e.propertyType} requires element schema`);if(!e.path)throw Error(`Displaying property of type ${e.propertyType} requires path`);return s.jsx(wf,{path:e.path,value:{type:t.type[0].code,value:r},compact:!0,ignoreMissingValues:e.ignoreMissingValues})}}const Hk=["extension","modifierExtension"],VB=Dk.filter(e=>!Hk.includes(e));function wf(e){const t=e.value,{value:n,type:r}=t,o=p.useContext(bt),i=e.profileUrl??(o==null?void 0:o.profileUrl),a=p.useMemo(()=>Dh(r,i),[i,r]),l=p.useMemo(()=>{if(a)return rl({parentContext:o,elements:a.elements,path:e.path,profileUrl:a.url,accessPolicyResource:e.accessPolicyResource})},[a,o,e.path,e.accessPolicyResource]);if(Gt(n))return null;if(!a)return s.jsxs("div",{children:[r," not implemented"]});if(typeof n=="object"&&"name"in n&&Object.keys(n).length===1&&typeof n.name=="string")return s.jsx("div",{children:n.name});const c=l??o;return Fh(bt.Provider,l,s.jsx(Yx,{compact:e.compact,children:Object.entries(c.elements).map(([u,d])=>{var v;if(Hk.includes(u)&&Gt((v=d.slicing)==null?void 0:v.slices))return null;if(VB.includes(u))return null;if(Ik.includes(u)&&d.path.split(".").length===2||u.includes("."))return null;const[f,h]=gu(t,u,c.profileUrl);if((e.ignoreMissingValues||d.max===0)&&Gt(f)||e.path.endsWith(".extension")&&(u==="url"||u==="id"))return null;const m=d.max>1||d.isArray,g=s.jsx(Zr,{property:d,propertyType:h,path:e.path+"."+u,value:f,ignoreMissingValues:e.ignoreMissingValues,includeArrayDescriptionListEntry:m,link:e.link},u);return m?g:s.jsx(No,{term:Rs(u),children:g},u)})}))}const qk="Read Only";function Gk(e,t){return e?s.jsx(Vs.Floating,{label:e,children:t}):t}const WB="_dimmed_1pxw4_1",Qk={dimmed:WB};function Kk(e){const{debugMode:t}=p.useContext(bt);let n;return t&&e.fhirPath?n=`${e.title} - ${e.fhirPath}`:n=e.title,Gk(e!=null&&e.readonly?qk:void 0,s.jsxs(te,{wrap:"nowrap","data-testid":e.testId,children:[s.jsx("div",{children:e.children}),s.jsx("div",{children:s.jsx(Lt.Wrapper,{id:e.htmlFor,label:n,classNames:{label:e!=null&&e.readonly?Qk.dimmed:void 0},description:e.description,withAsterisk:e.withAsterisk,children:null})})]}))}function Je(e,t){var n,r,o;return(o=(r=(n=e==null?void 0:e.issue)==null?void 0:n.filter(i=>{var a;return Yk((a=i.expression)==null?void 0:a[0],t)}))==null?void 0:r.map(i=>{var a;return(a=i.details)==null?void 0:a.text}))==null?void 0:o.join(`
535
- `)}function vu(e,t){var n;return(n=e==null?void 0:e.issue)==null?void 0:n.filter(r=>{var o;return Yk((o=r.expression)==null?void 0:o[0],t)})}const ad=/\[\d+\]/;function Yk(e,t){const n=typeof e=="string"&&ad.test(e),r=typeof t=="string"&&ad.test(t);if(n!==r&&(e=e==null?void 0:e.replace(ad,""),t=t==null?void 0:t.replace(ad,"")),e===t)return!0;if(!e||!t)return!1;const o=e.indexOf(".");if(o>=0&&e.substring(o+1)===t)return!0;const i=t.indexOf(".");return i>=0&&t.substring(i+1)===e}function vt(e){const{debugMode:t}=p.useContext(bt);let n;return t&&e.fhirPath?n=`${e.title} - ${e.fhirPath}`:n=e.title,Gk(e!=null&&e.readonly?qk:void 0,s.jsx(Lt.Wrapper,{id:e.htmlFor,label:n,classNames:{label:e!=null&&e.readonly?Qk.dimmed:void 0},description:e.description,withAsterisk:e.withAsterisk,error:Je(e.outcome,e.errorExpression??e.htmlFor),"data-testid":e.testId,children:e.children}))}function Xk(e,t,n,r,o){const i=r.type;if(i.length>1)for(const a of i){const l=t.replace("[x]",nn(a.code));l in e&&delete e[l]}return e[n]=o,e}function HB(e){return!!e&&!Gt(e.url)&&!Gt(e.name)}function qB(e){const{defaultValue:t,onChange:n,withHelpText:r,outcome:o,path:i,valuePath:a,...l}=e,[c,u]=p.useState(t);function d(f){const h=QB(f);u(h),n&&n(h)}return s.jsx(Qx,{defaultValue:c&&GB(c),onChange:d,withHelpText:r??!0,...l})}function GB(e){var t;return(t=e.coding)==null?void 0:t.map(n=>({system:n.system,code:n.code,display:n.display}))}function QB(e){if(e.length!==0)return{coding:e.map(t=>({system:t.system,code:t.code,display:t.display}))}}function Jk(e){const{defaultValue:t,onChange:n,withHelpText:r,...o}=e,[i,a]=p.useState(t);function l(c){const u=c[0],d=u&&YB(u);a(d),n&&n(d)}return s.jsx(Qx,{defaultValue:i&&KB(i),maxValues:1,onChange:l,withHelpText:r??!0,...o})}function KB(e){return{system:e.system,code:e.code,display:e.display}}function YB(e){return{system:e.system,code:e.code,display:e.display}}function Zk(e){const{path:t,outcome:n}=e,{elementsByPath:r,getExtendedProps:o}=p.useContext(bt),[i,a]=p.useState(e.defaultValue),l=p.useRef();l.current=i;const[c,u,d]=p.useMemo(()=>["system","use","value"].map(b=>r[t+"."+b]),[r,t]),[f,h,m]=p.useMemo(()=>["system","use","value"].map(b=>o(t+"."+b)),[o,t]);function g(b){b&&Object.keys(b).length===0&&(b=void 0),a(b),e.onChange&&e.onChange(b)}function v(b){const x={...l.current,system:b};b||delete x.system,g(x)}function S(b){const x={...l.current,use:b};b||delete x.use,g(x)}function y(b){const x={...l.current,value:b};b||delete x.value,g(x)}const w=e.valuePath??t;return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[s.jsx(It,{disabled:e.disabled||(f==null?void 0:f.readonly),"data-testid":"system",defaultValue:i==null?void 0:i.system,required:((c==null?void 0:c.min)??0)>0,onChange:b=>v(b.currentTarget.value),data:["","email","phone","fax","pager","sms","other"],error:Je(n,w+".system")}),s.jsx(It,{disabled:e.disabled||(h==null?void 0:h.readonly),"data-testid":"use",defaultValue:i==null?void 0:i.use,required:((u==null?void 0:u.min)??0)>0,onChange:b=>S(b.currentTarget.value),data:["","home","work","temp","old","mobile"],error:Je(n,w+".use")}),s.jsx(ve,{disabled:e.disabled||(m==null?void 0:m.readonly),placeholder:"Value",defaultValue:i==null?void 0:i.value,required:((d==null?void 0:d.min)??0)>0,onChange:b=>y(b.currentTarget.value),error:Je(n,w+".value")})]})}function XB(e){var d;const[t,n]=p.useState(e.defaultValue),r=p.useRef();r.current=t;const{getExtendedProps:o}=p.useContext(bt),[i,a]=p.useMemo(()=>["name","telecom"].map(f=>o(e.path+"."+f)),[o,e.path]);function l(f){n(f),e.onChange&&e.onChange(f)}function c(f){const h={...r.current,name:f};f||delete h.name,l(h)}function u(f){const h={...r.current,telecom:f&&[f]};f||delete h.telecom,l(h)}return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(ve,{disabled:e.disabled||(i==null?void 0:i.readonly),"data-testid":e.name+"-name",name:e.name+"-name",placeholder:"Name",style:{width:180},defaultValue:t==null?void 0:t.name,onChange:f=>c(f.currentTarget.value)}),s.jsx(Zk,{disabled:e.disabled||(a==null?void 0:a.readonly),name:e.name+"-telecom",path:e.path+".telecom",defaultValue:(d=t==null?void 0:t.telecom)==null?void 0:d[0],onChange:u,outcome:e.outcome})]})}function JB(e){if(!e)return"";const t=new Date(e);return Ih(t)?t.toLocaleDateString("sv")+"T"+t.toLocaleTimeString("sv"):""}function eR(e){if(!e)return"";const t=new Date(e);return Ih(t)?t.toISOString():""}function _s(e){return s.jsx(ve,{id:e.name,name:e.name,label:e.label,"data-autofocus":e.autoFocus,"data-testid":e["data-testid"]??e.name,placeholder:e.placeholder,required:e.required,disabled:e.disabled,type:ZB(),defaultValue:JB(e.defaultValue),autoFocus:e.autoFocus,error:Je(e.outcome,e.name),onChange:t=>{if(e.onChange){const n=t.currentTarget.value;e.onChange(eR(n))}}})}function ZB(){return"datetime-local"}function eU(e){const{propertyType:t}=e,n=se(),r=p.useMemo(()=>{if(Bt(t.profile))return t.profile[0]},[t]),[o,i]=p.useState(r!==void 0);return p.useEffect(()=>{r&&(i(!0),n.requestProfileSchema(r).then(()=>i(!1)).catch(a=>{i(!1),console.warn(a)}))},[n,r]),r&&(o||!jx(r))?s.jsx("div",{children:"Loading..."}):s.jsx(t0,{profileUrl:r,path:e.path,typeName:"Extension",defaultValue:e.defaultValue,onChange:e.onChange})}function tU(e){var w,b,x;const{outcome:t,path:n}=e,[r,o]=p.useState(e.defaultValue),{getExtendedProps:i}=p.useContext(bt),[a,l,c,u,d]=p.useMemo(()=>["use","prefix","given","family","suffix"].map(C=>i(e.path+"."+C)),[i,e.path]);function f(C){o(C),e.onChange&&e.onChange(C)}function h(C){f({...r,use:C||void 0})}function m(C){f({...r,prefix:C?C.split(" "):void 0})}function g(C){f({...r,given:C?C.split(" "):void 0})}function v(C){f({...r,family:C||void 0})}function S(C){f({...r,suffix:C?C.split(" "):void 0})}const y=e.valuePath??n;return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(It,{disabled:e.disabled||(a==null?void 0:a.readonly),defaultValue:r==null?void 0:r.use,name:e.name+"-use","data-testid":"use",onChange:C=>h(C.currentTarget.value),data:["","temp","old","usual","official","nickname","anonymous","maiden"],error:Je(t,y+".use")}),s.jsx(ve,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"Prefix",name:e.name+"-prefix",defaultValue:(w=r==null?void 0:r.prefix)==null?void 0:w.join(" "),onChange:C=>m(C.currentTarget.value),error:Je(t,y+".prefix")}),s.jsx(ve,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Given",name:e.name+"-given",defaultValue:(b=r==null?void 0:r.given)==null?void 0:b.join(" "),onChange:C=>g(C.currentTarget.value),error:Je(t,y+".given")}),s.jsx(ve,{disabled:e.disabled||(u==null?void 0:u.readonly),name:e.name+"-family",placeholder:"Family",defaultValue:r==null?void 0:r.family,onChange:C=>v(C.currentTarget.value),error:Je(t,y+".family")}),s.jsx(ve,{disabled:e.disabled||(d==null?void 0:d.readonly),placeholder:"Suffix",name:e.name+"-suffix",defaultValue:(x=r==null?void 0:r.suffix)==null?void 0:x.join(" "),onChange:C=>S(C.currentTarget.value),error:Je(t,y+".suffix")})]})}function nU(e){const[t,n]=p.useState(e.defaultValue),{elementsByPath:r,getExtendedProps:o}=p.useContext(bt),[i,a]=p.useMemo(()=>["system","value"].map(f=>r[e.path+"."+f]),[r,e.path]),[l,c]=p.useMemo(()=>["system","value"].map(f=>o(e.path+"."+f)),[o,e.path]);function u(f){n(f),e.onChange&&e.onChange(f)}const d=e.valuePath??e.path;return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[s.jsx(ve,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"System",required:((i==null?void 0:i.min)??0)>0,defaultValue:t==null?void 0:t.system,onChange:f=>u({...t,system:f.currentTarget.value}),error:Je(e.outcome,d+".system")}),s.jsx(ve,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Value",required:((a==null?void 0:a.min)??0)>0,defaultValue:t==null?void 0:t.value,onChange:f=>u({...t,value:f.currentTarget.value}),error:Je(e.outcome,d+".value")})]})}const rU=["USD","EUR","CAD","GBP","AUD"];function oU(e){var f;const{onChange:t}=e,[n,r]=p.useState(e.defaultValue),{getExtendedProps:o}=p.useContext(bt),[i,a]=p.useMemo(()=>["currency","value"].map(h=>o(e.path+"."+h)),[o,e.path]),l=p.useCallback(h=>{r(h),t&&t(h)},[t]),c=p.useCallback(h=>{l({...n,currency:h.currentTarget.value})},[n,l]),u=p.useCallback(h=>{l({...n,value:h.currentTarget.valueAsNumber})},[n,l]),d=s.jsx(It,{disabled:e.disabled||(i==null?void 0:i.readonly),defaultValue:n==null?void 0:n.currency,data:rU,styles:{input:{fontWeight:500,borderTopLeftRadius:0,borderBottomLeftRadius:0,width:92}},onChange:c});return s.jsx(ve,{disabled:e.disabled||(a==null?void 0:a.readonly),type:"number",name:e.name,label:e.label,placeholder:e.placeholder??"Value",defaultValue:((f=n==null?void 0:n.value)==null?void 0:f.toString())??"USD",leftSection:s.jsx(lz,{size:14}),rightSection:d,rightSectionWidth:92,onChange:u})}function iU(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(bt),[o,i]=p.useMemo(()=>["start","end"].map(l=>r(e.path+"."+l)),[r,e.path]);function a(l){n(l),e.onChange&&e.onChange(l)}return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(_s,{disabled:e.disabled||(o==null?void 0:o.readonly),name:e.name+".start",placeholder:"Start",defaultValue:t==null?void 0:t.start,onChange:l=>a({...t,start:l})}),s.jsx(_s,{disabled:e.disabled||(i==null?void 0:i.readonly),name:e.name+".end",placeholder:"End",defaultValue:t==null?void 0:t.end,onChange:l=>a({...t,end:l})})]})}function Ds(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(bt),[o,i,a]=p.useMemo(()=>["comparator","value","unit"].map(c=>r(e.path+"."+c)),[r,e.path]);function l(c){n(c),e.onChange&&e.onChange(c)}return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(It,{disabled:e.disabled||(o==null?void 0:o.readonly),style:{width:80},"data-testid":e.name+"-comparator",defaultValue:t==null?void 0:t.comparator,data:["","<","<=",">=",">"],onChange:c=>l({...t,comparator:c.currentTarget.value})}),s.jsx(ve,{disabled:e.disabled||(i==null?void 0:i.readonly),id:e.name,name:e.name,required:e.required,"data-autofocus":e.autoFocus,"data-testid":e.name+"-value",type:"number",placeholder:"Value",defaultValue:t==null?void 0:t.value,autoFocus:e.autoFocus,step:"any",onWheel:c=>{e.disableWheel&&c.currentTarget.blur()},onChange:c=>{l({...t,value:sU(c.currentTarget.value)})}}),s.jsx(ve,{disabled:e.disabled||(a==null?void 0:a.readonly),placeholder:"Unit","data-testid":e.name+"-unit",defaultValue:t==null?void 0:t.unit,onChange:c=>l({...t,unit:c.currentTarget.value})})]})}function sU(e){if(e)return parseFloat(e)}function Zx(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(bt),[o,i]=p.useMemo(()=>["low","high"].map(l=>r(e.path+"."+l)),[r,e.path]);function a(l){n(l),e.onChange&&e.onChange(l)}return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(Ds,{path:e.path+".low",disabled:e.disabled||(o==null?void 0:o.readonly),name:e.name+"-low",defaultValue:t==null?void 0:t.low,onChange:l=>a({...t,low:l})}),s.jsx(Ds,{path:e.path+".high",disabled:e.disabled||(i==null?void 0:i.readonly),name:e.name+"-high",defaultValue:t==null?void 0:t.high,onChange:l=>a({...t,high:l})})]})}function aU(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(bt),[o,i]=p.useMemo(()=>["numerator","denominator"].map(l=>r(e.path+"."+l)),[r,e.path]);function a(l){n(l),e.onChange&&e.onChange(l)}return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(Ds,{path:e.path+".numerator",disabled:e.disabled||(o==null?void 0:o.readonly),name:e.name+"-numerator",defaultValue:t==null?void 0:t.numerator,onChange:l=>a({...t,numerator:l})}),s.jsx(Ds,{path:e.path+".denominator",disabled:e.disabled||(i==null?void 0:i.readonly),name:e.name+"-denominator",defaultValue:t==null?void 0:t.denominator,onChange:l=>a({...t,denominator:l})})]})}const lU={Device:"device-name",Observation:"code",Subscription:"criteria",User:"email:contains"},cU=["AccessPolicy","Account","ActivityDefinition","Bot","CapabilityStatement","CareTeam","ClientApplication","CodeSystem","CompartmentDefinition","ConceptMap","EffectEvidenceSynthesis","Endpoint","EventDefinition","Evidence","EvidenceVariable","ExampleScenario","GraphDefinition","Group","HealthcareService","ImplementationGuide","InsurancePlan","Library","Location","Measure","MedicinalProduct","MessageDefinition","NamingSystem","OperationDefinition","Organization","Patient","Person","PlanDefinition","Practitioner","Project","Questionnaire","RelatedPerson","ResearchDefinition","ResearchElementDefinition","RiskEvidenceSynthesis","SearchParameter","StructureDefinition","StructureMap","TerminologyCapabilities","TestScript","UserConfiguration","ValueSet"];function uU(e){return{value:st(e),label:Wo(e),resource:e}}function Ys(e){const t=se(),{resourceType:n,searchCriteria:r}=e,[o,i]=p.useState(),a=wt(e.defaultValue,i),l=e.itemComponent??dU,c=e.onChange,u=p.useCallback(async(f,h)=>{const m=fU(n),g=new URLSearchParams({[m]:f??"",_count:"10",...r});return await t.searchResources(n,g,{signal:h})},[t,n,r]),d=p.useCallback(f=>{c&&c(f[0])},[c]);return Bt(e.defaultValue)&&!o&&!a?null:s.jsx(Gx,{disabled:e.disabled,name:e.name,required:e.required,itemComponent:l,defaultValue:a,placeholder:e.placeholder,maxValues:1,toOption:uU,loadOptions:u,onChange:d,clearable:!0})}const dU=p.forwardRef(({label:e,resource:t,active:n,...r},o)=>s.jsx("div",{ref:o,...r,children:s.jsxs(te,{wrap:"nowrap",children:[s.jsx(Hi,{value:t}),s.jsxs("div",{children:[s.jsx(fe,{children:e}),s.jsx(fe,{size:"xs",c:"dimmed",children:t.birthDate||t.id})]})]})}));function fU(e){return lU[e]??(cU.includes(e)?"name":"_id")}function zh(e){const{onChange:t}=e,n=se(),[r,o]=p.useState(e.defaultValue),[i,a]=p.useState(()=>hU(e.targetTypes)),[l,c]=p.useState(()=>pU(e.defaultValue,i)),u=p.useRef(new wk),d=p.useMemo(()=>(l==null?void 0:l.type)==="profile"?{...e.searchCriteria,_profile:l.value}:e.searchCriteria,[e.searchCriteria,l]);p.useEffect(()=>{let m=!1;const g=i==null?void 0:i.map(v=>{if(!gU(v))return Promise.resolve(v);m=!0;const S=v.value,y=u.current.get(S);if(y)return y;const w=mU(n,v.value).then(x=>{const C={...v};return x?Bt(x.type)?(C.resourceType=x.type,C.name=x.name,C.title=x.title):(console.error(`StructureDefinition.type missing for ${v.value}`),C.error="StructureDefinition.type missing"):(console.error(`StructureDefinition not found for ${v.value}`),C.error="StructureDefinition not found"),C}).catch(x=>(console.error(x),{...v,error:x})),b=new Fr(w);return u.current.set(S,b),b});!g||!m||Promise.all(g).then(v=>{if(a(v),!l)return;const S=v.findIndex(y=>y.value===l.value||y.resourceType===l.resourceType);if(S===-1){console.debug(`defaultValue had unexpected resourceType: ${l.resourceType}`);return}c(v[S])}).catch(console.error)},[n,l,i]);const f=p.useCallback(m=>{const g=m?Et(m):void 0;o(g),t&&t(g)},[t]),h=p.useMemo(()=>i?i.map(m=>({value:m.value,label:m.type==="profile"?m.title??m.name??m.resourceType??m.value:m.value})):[],[i]);return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[i&&i.length>1&&s.jsx(It,{disabled:e.disabled,"data-autofocus":e.autoFocus,"data-testid":"reference-input-resource-type-select",defaultValue:l==null?void 0:l.resourceType,autoFocus:e.autoFocus,onChange:m=>{const g=m.currentTarget.value,v=i.find(S=>S.value===g);c(v)},data:h}),!i&&s.jsx(Kx,{disabled:e.disabled,autoFocus:e.autoFocus,testId:"reference-input-resource-type-input",defaultValue:l==null?void 0:l.resourceType,onChange:m=>{c(m?{type:"resourceType",value:m,resourceType:m}:void 0)},name:e.name+"-resourceType",placeholder:"Resource Type"}),s.jsx(Ys,{resourceType:l==null?void 0:l.resourceType,name:e.name+"-id",required:e.required,placeholder:e.placeholder,defaultValue:r,searchCriteria:d,onChange:f,disabled:e.disabled})]})}function hU(e){if(!e||e.length===0||e.length===1&&e[0]==="Resource")return;const t=[];for(const n of e)n.includes("/")?t.push({type:"profile",value:n}):t.push({type:"resourceType",value:n,resourceType:n});return t}function pU(e,t){var r;const n=(r=e==null?void 0:e.reference)==null?void 0:r.split("/")[0];if(n){const o=t==null?void 0:t.find(i=>i.resourceType===n);return o||{type:"resourceType",value:n,resourceType:n}}if(t&&t.length>0)return t[0]}async function mU(e,t){const n=yl(t);if(n)return{type:n.type,name:n.name,title:n.title};const r=`{
534
+ }`.replace(/\s+/g," ")}function sB(e,t){const n=[];return e.data.Patients1&&n.push(...e.data.Patients1),e.data.Patients2&&n.push(...e.data.Patients2),e.data.ServiceRequestList&&n.push(...e.data.ServiceRequestList),lB(aB(n),t).slice(0,5)}function aB(e){const t=new Set,n=[];for(const r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function lB(e,t){return e.sort((n,r)=>Ew(r,t)-Ew(n,t))}function Ew(e,t){let n=0;if(e.identifier)for(const r of e.identifier)n=Math.max(n,Tw(r.value,t));if(e.resourceType==="Patient"&&e.name)for(const r of e.name)n=Math.max(n,Tw(fu(r),t));return n}function Tw(e,t){if(!e)return 0;const n=e.toLowerCase().indexOf(t.toLowerCase());return n<0?0:100-n}function cB(e){var o;const t=$h(),[n,r]=p.useState(!1);return s.jsx(Jn.Header,{p:8,style:{zIndex:101},children:s.jsxs(te,{justify:"space-between",children:[s.jsxs(te,{gap:"xs",children:[s.jsx(bn,{className:sd.logoButton,onClick:e.navbarToggle,children:e.logo}),!e.headerSearchDisabled&&s.jsx(rB,{pathname:e.pathname,searchParams:e.searchParams})]}),s.jsxs(te,{gap:"lg",pr:"sm",children:[e.notifications,s.jsxs(J,{width:260,shadow:"xl",position:"bottom-end",transitionProps:{transition:"pop-top-right"},opened:n,onClose:()=>r(!1),children:[s.jsx(J.Target,{children:s.jsx(bn,{className:rt(sd.user,{[sd.userActive]:n}),onClick:()=>r(i=>!i),children:s.jsxs(te,{gap:7,children:[s.jsx(Hi,{value:t,radius:"xl",size:24}),s.jsx(fe,{size:"sm",className:sd.userName,children:fu((o=t==null?void 0:t.name)==null?void 0:o[0])}),s.jsx(Bx,{size:12,stroke:1.5})]})})}),s.jsx(J.Dropdown,{children:s.jsx(Yz,{version:e.version})})]})]})]})})}function uB(e){const t={};for(const n of Array.from(e.elements))n instanceof HTMLInputElement?dB(t,n):n instanceof HTMLTextAreaElement?t[n.name]=n.value:n instanceof HTMLSelectElement&&fB(t,n);return t}function dB(e,t){t.disabled||(t.type==="checkbox"||t.type==="radio")&&!t.checked||(e[t.name]=t.value)}function fB(e,t){e[t.name]=t.value}function Ke(e){return s.jsx("form",{style:e.style,"data-testid":e.testid,onSubmit:t=>{t.preventDefault();const n=uB(t.target);e.onSubmit&&e.onSubmit(n)},children:e.children})}function hB(e){const t=se(),n=t.getUserConfiguration();function r(o){var d,f;const{menuname:i,bookmarkname:a}=o,l=`${e.pathname}?${e.searchParams.toString()}`,c=Xr(n),u=(d=c.menu)==null?void 0:d.find(({title:h})=>h===i);(f=u==null?void 0:u.link)==null||f.push({name:a,target:l}),t.updateResource(c).then(h=>{n.menu=h.menu,t.dispatchEvent({type:"change"}),he({color:"green",message:"Success"}),e.onOk()}).catch(h=>{he({color:"red",message:De(h)})})}return s.jsx(wn,{title:"Add Bookmark",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:e.onCancel,children:s.jsx(Ke,{onSubmit:r,children:s.jsxs(Oe,{children:[s.jsx(pB,{config:n}),s.jsx(ve,{label:"Bookmark Name",type:"text",name:"bookmarkname",placeholder:"Bookmark Name",withAsterisk:!0}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{mt:"sm",type:"submit",children:"OK"})})]})})})}function pB(e){function t(r){var o;return(o=r==null?void 0:r.menu)==null?void 0:o.map(i=>i.title)}const n=t(e.config);return s.jsx(It,{name:"menuname",defaultValue:n[0],label:"Select Menu Option",data:n,withAsterisk:!0})}function Fk(e){return typeof e.code=="string"?e.code:JSON.stringify(e)}function mB(e){return typeof e.display=="string"?e.display:Fk(e)}function gB(e){return{value:Fk(e),label:mB(e),resource:e}}function vB(e){return{code:e,display:e}}function Qx(e){const t=se(),{binding:n,creatable:r,clearable:o,expandParams:i,withHelpText:a,...l}=e,c=p.useCallback(async(u,d)=>{var g;if(!n)return[];const h=(g=(await t.valueSetExpand({...i,url:n,filter:u},{signal:d})).expansion)==null?void 0:g.contains,m=[];for(const v of h)v.code&&!m.some(S=>S.code===v.code)&&m.push(v);return m},[t,i,n]);return s.jsx(Gx,{...l,creatable:r??!0,clearable:o??!0,toOption:gB,loadOptions:c,onCreate:vB,itemComponent:a?yB:void 0})}const yB=p.forwardRef(({label:e,resource:t,active:n,...r},o)=>s.jsx("div",{ref:o,...r,children:s.jsxs(te,{wrap:"nowrap",gap:"xs",children:[n&&s.jsx(Ks,{size:12}),s.jsxs("div",{children:[s.jsx(fe,{children:e}),s.jsx(fe,{size:"xs",c:"dimmed",children:`${t.system}#${t.code}`})]})]})}));function zk(e){const{defaultValue:t,onChange:n,withHelpText:r,...o}=e,[i,a]=p.useState(t);function l(c){const u=c[0],d=bB(u);a(d),n&&n(d)}return s.jsx(Qx,{defaultValue:xB(i),onChange:l,withHelpText:r??!0,...o})}function xB(e){return e?{code:e}:void 0}function bB(e){return e==null?void 0:e.code}function Kx(e){const[t,n]=p.useState(e.defaultValue),r=e.onChange,o=p.useCallback(i=>{n(i),r&&r(i)},[r]);return s.jsx(zk,{disabled:e.disabled,"data-autofocus":e.autoFocus,"data-testid":e.testId,defaultValue:t,onChange:o,name:e.name,placeholder:e.placeholder,binding:"https://medplum.com/fhir/ValueSet/resource-types",creatable:!1,maxValues:e.maxValues??1,clearable:!1,withHelpText:!1})}const wB="_menuTitle_9g6l5_1",SB="_link_9g6l5_9",jB="_linkActive_9g6l5_38",Pg={menuTitle:wB,link:SB,linkActive:jB};function CB(e){var l;const t=Lh(),n=PB(e.pathname,e.searchParams,e.menus),[r,o]=p.useState(!1);function i(c,u){c.stopPropagation(),c.preventDefault(),t(u),window.innerWidth<768&&e.closeNavbar()}function a(c){c&&t(`/${c}`)}return s.jsxs(s.Fragment,{children:[s.jsx(Jn.Navbar,{children:s.jsxs(Ir,{p:"xs",children:[!e.resourceTypeSearchDisabled&&s.jsx(Jn.Section,{mb:"sm",children:s.jsx(Kx,{name:"resourceType",placeholder:"Resource Type",maxValues:0,onChange:c=>a(c)},window.location.pathname)}),s.jsxs(Jn.Section,{grow:!0,children:[(l=e.menus)==null?void 0:l.map(c=>{var u;return s.jsxs(p.Fragment,{children:[s.jsx(fe,{className:Pg.menuTitle,children:c.title}),(u=c.links)==null?void 0:u.map(d=>s.jsxs(EB,{to:d.href,active:d.href===(n==null?void 0:n.href),onClick:f=>i(f,d.href),children:[s.jsx(TB,{to:d.href,icon:d.icon}),s.jsx("span",{children:d.label})]},d.href))]},`menu-${c.title}`)}),e.displayAddBookmark&&s.jsx(oe,{variant:"subtle",size:"xs",mt:"xl",leftSection:s.jsx(Ez,{size:"0.75rem"}),onClick:()=>o(!0),children:"Add Bookmark"})]})]})}),e.pathname&&e.searchParams&&s.jsx(hB,{pathname:e.pathname,searchParams:e.searchParams,visible:r,onOk:()=>o(!1),onCancel:()=>o(!1)})]})}function EB(e){return s.jsx(Ge,{onClick:e.onClick,to:e.to,className:rt(Pg.link,{[Pg.linkActive]:e.active}),children:e.children})}function TB(e){return e.icon?e.icon:s.jsx(Rh,{w:30})}function PB(e,t,n){if(!e||!t||!n)return;let r,o=0;for(const i of n)if(i.links)for(const a of i.links){const l=kB(e,t,a.href);l>o&&(o=l,r=a)}return r}function kB(e,t,n){const r=new URL(n,"https://example.com");if(e!==r.pathname)return 0;const o=["_count","_offset"];for(const[a,l]of r.searchParams.entries())if(!o.includes(a)&&t.get(a)!==l)return 0;let i=1;for(const[a,l]of t.entries())o.includes(a)||r.searchParams.get(a)===l&&i++;return i}function RB(e){const[t,n]=p.useState(localStorage.navbarOpen==="true"),r=se(),o=$h();p.useEffect(()=>{function c(){he({color:"red",message:"No connection to server",autoClose:!1})}return r.addEventListener("offline",c),()=>r.removeEventListener("offline",c)},[r]);function i(c){localStorage.navbarOpen=c.toString(),n(c)}function a(){i(!1)}function l(){i(!t)}return r.isLoading()?s.jsx(Jr,{}):s.jsxs(Jn,{header:{height:60},navbar:{width:250,breakpoint:"sm",collapsed:{desktop:!o||!t,mobile:!o||!t}},padding:0,children:[o&&s.jsx(cB,{pathname:e.pathname,searchParams:e.searchParams,headerSearchDisabled:e.headerSearchDisabled,logo:e.logo,version:e.version,navbarToggle:l,notifications:e.notifications}),o&&t?s.jsx(CB,{pathname:e.pathname,searchParams:e.searchParams,menus:e.menus,closeNavbar:a,displayAddBookmark:e.displayAddBookmark,resourceTypeSearchDisabled:e.resourceTypeSearchDisabled}):void 0,s.jsx(Jn.Main,{className:zz.main,children:s.jsx(Lk,{children:s.jsx(p.Suspense,{fallback:s.jsx(Jr,{}),children:e.children})})})]})}function mu(e){const{contentType:t,url:n,title:r}=e.value??{},o=Rk(n);return o?s.jsxs("div",{"data-testid":"attachment-display",children:[(t==null?void 0:t.startsWith("image/"))&&s.jsx("img",{"data-testid":"attachment-image",style:{maxWidth:e.maxWidth},src:o,alt:r}),(t==null?void 0:t.startsWith("video/"))&&s.jsx("video",{"data-testid":"attachment-video",style:{maxWidth:e.maxWidth},controls:!0,children:s.jsx("source",{type:t,src:o})}),((t==null?void 0:t.startsWith("text/"))||t==="application/json"||t==="application/pdf")&&s.jsx("div",{"data-testid":"attachment-iframe",style:{maxWidth:e.maxWidth,minHeight:400},children:s.jsx("iframe",{width:"100%",height:"400",src:o+"#navpanes=0",allowFullScreen:!0,frameBorder:0,seamless:!0})}),s.jsx("div",{"data-testid":"download-link",style:{padding:"2px 16px 16px 16px"},children:s.jsx(Ze,{href:n,"data-testid":"attachment-details",target:"_blank",rel:"noopener noreferrer",download:_B(r),children:r||"Download"})})]}):null}function _B(e){return e!=null&&e.includes(".")?e:void 0}const DB="_root_17n8t_1",IB="_compact_17n8t_25",Pw={root:DB,compact:IB};function Yx(e){const{children:t,compact:n}=e;return s.jsx("dl",{className:rt(Pw.root,{[Pw.compact]:n}),children:t})}function No(e){return s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:e.term}),s.jsx("dd",{children:e.children})]})}function AB(e){var r;const t=(r=e.values)==null?void 0:r.map((o,i)=>s.jsx("div",{children:s.jsx(mu,{value:o,maxWidth:e.maxWidth})},"attatchment-"+i));let n;if(e.includeDescriptionListEntry){if(e.property===void 0)throw new Error("props.property is required when includeDescriptionListEntry is true");if(!Bt(e.path))throw new Error("props.path is required when includeDescriptionListEntry is true");const o=e.path.split(".").pop();n=s.jsx(No,{term:Rs(o),children:t})}else n=s.jsx(s.Fragment,{children:t});return n}function Xx(e){const t=se(),n=p.useRef(null);function r(a){var l;yt(a),(l=n.current)==null||l.click()}function o(a){yt(a);const l=a.target.files;l&&Array.from(l).forEach(i)}function i(a){!a||!a.name||(e.onUploadStart&&e.onUploadStart(),t.createAttachment({data:a,contentType:a.type||"application/octet-stream",filename:a.name,securityContext:e.securityContext,onProgress:e.onUploadProgress}).then(c=>e.onUpload(c)).catch(c=>{e.onUploadError&&e.onUploadError(ht(c))}))}return s.jsxs(s.Fragment,{children:[s.jsx("input",{disabled:e.disabled,type:"file","data-testid":"upload-file-input",style:{display:"none"},ref:n,onChange:a=>o(a)}),e.children({onClick:r,disabled:e.disabled})]})}function NB(e){const[t,n]=p.useState(e.defaultValue??[]),r=p.useRef();r.current=t;function o(i){n(i),e.onChange&&e.onChange(i)}return s.jsxs("table",{style:{width:"100%"},children:[s.jsxs("colgroup",{children:[s.jsx("col",{width:"97%"}),s.jsx("col",{width:"3%"})]}),s.jsxs("tbody",{children:[t.map((i,a)=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(mu,{value:i,maxWidth:200})}),s.jsx("td",{children:s.jsx(tn,{disabled:e.disabled,title:"Remove",variant:"subtle",size:"sm",color:"gray",onClick:l=>{yt(l);const c=t.slice();c.splice(a,1),o(c)},children:s.jsx(vf,{})})})]},`${a}-${t.length}`)),s.jsxs("tr",{children:[s.jsx("td",{}),s.jsx("td",{children:s.jsx(Xx,{disabled:e.disabled,onUpload:i=>{o([...r.current,i])},children:i=>s.jsx(tn,{...i,title:"Add",variant:"subtle",size:"sm",color:i.disabled?"gray":"green",children:s.jsx(Ux,{})})})})]})]})]})}function Bk(e){const[t,n]=p.useState(e.defaultValue);function r(o){n(o),e.onChange&&e.onChange(o)}return t?s.jsxs(s.Fragment,{children:[s.jsx(mu,{value:t,maxWidth:200}),s.jsx(oe,{disabled:e.disabled,onClick:o=>{yt(o),r(void 0)},children:"Remove"})]}):s.jsx(Xx,{disabled:e.disabled,securityContext:e.securityContext,onUpload:r,children:o=>s.jsx(oe,{...o,children:"Upload..."})})}function yo(e){return s.jsx(s.Fragment,{children:Oi(e.value)})}function MB(e){return s.jsx(s.Fragment,{children:qs(e.value)})}function Uk(e){const t=e.value;if(!t)return null;const n=[];return t.value&&n.push(t.value),(t.use||t.system)&&(n.push(" ["),t.use&&n.push(t.use),t.use&&t.system&&n.push(" "),t.system&&n.push(t.system),n.push("]")),s.jsx(s.Fragment,{children:n.join("").trim()})}function OB(e){var n;const t=e.value;return t?s.jsxs(s.Fragment,{children:[t.name,t.name&&": ",(n=t.telecom)==null?void 0:n.map(r=>s.jsx(Uk,{value:r},`telecom-${t.name}-${r.value}`))]}):null}function LB(e){var t,n;return s.jsxs("div",{children:[(t=e.value)==null?void 0:t.system,": ",(n=e.value)==null?void 0:n.value]})}function $B(e){return s.jsx(s.Fragment,{children:D6(e.value)})}function $c(e){return s.jsx(s.Fragment,{children:fi(e.value)})}function Jx(e){return s.jsx(s.Fragment,{children:Mc(e.value)})}function FB(e){const t=e.value;return t?s.jsxs(s.Fragment,{children:[s.jsx($c,{value:t.numerator})," / ",s.jsx($c,{value:t.denominator})]}):null}function bf(e){if(!e.value)return null;const t=e.value.display||e.value.reference||pr(e.value);return e.link!==!1&&e.value.reference?s.jsx(Ge,{to:e.value,children:t}):s.jsx(s.Fragment,{children:t})}function Vk(e,t,n,r){if(!Bt(n==null?void 0:n.slices))return[e];const o=new Array(t.length+1);for(let i=0;i<o.length;i++)o[i]=[];for(const i of e){const a=Tk(i,t,n.discriminator,r);let l=a?t.findIndex(c=>c.name===a):-1;l===-1&&(l=t.length),o[l].push(i)}return o}async function Wk({medplum:e,property:t}){return new Promise((n,r)=>{var l,c;if(!t.slicing){n([]);return}const o=[],i=[],a=[];for(const u of t.slicing.slices){if(!Ek(u)){console.debug("Unsupported slice definition",u);continue}let d;Bt(u.elements)||(d=(c=(l=u.type[0])==null?void 0:l.profile)==null?void 0:c[0]),o.push(u),i.push(d),d&&a.push(e.requestProfileSchema(d))}Promise.all(a).then(()=>{for(let u=0;u<o.length;u++){const d=o[u],f=i[u];if(f){const h=yl(f);d.typeSchema=h}}n(o)}).catch(r)})}function Fh(e,t,n){return t!==void 0?s.jsx(e,{value:t,children:n}):n}function zB(e){var a,l;const{slice:t,property:n}=e,r=((a=t.typeSchema)==null?void 0:a.elements)??t.elements,o=p.useContext(bt),i=p.useMemo(()=>{var c;if(Bt(r))return rl({parentContext:o,elements:r,path:e.path,profileUrl:(c=t.typeSchema)==null?void 0:c.url})},[o,e.path,(l=t.typeSchema)==null?void 0:l.url,r]);return Fh(bt.Provider,i,s.jsx(s.Fragment,{children:e.value.map((c,u)=>s.jsx("div",{children:s.jsx(Zr,{property:n,path:e.path,arrayElement:!0,elementDefinitionType:t.type[0],propertyType:t.type[0].code,value:c,ignoreMissingValues:e.ignoreMissingValues,link:e.link})},`${u}-${e.value.length}`))}))}function BB(e){var g;const{property:t,propertyType:n}=e,r=se(),o=p.useMemo(()=>Array.isArray(e.values)?e.values:[],[e.values]),[i,a]=p.useState(!0),[l,c]=p.useState([]),[u,d]=p.useState(()=>[o]),f=p.useContext(bt);if(p.useEffect(()=>{Wk({medplum:r,property:t}).then(v=>{c(v);const S=Vk(o,v,t.slicing,f.profileUrl);d(S),a(!1)}).catch(v=>{console.error(v),a(!1)})},[r,t,f.profileUrl,d,o]),i)return s.jsx("div",{children:"Loading..."});let h;if(((g=t.type[0])==null?void 0:g.code)!=="Extension"){const v=u[l.length],S=v.map((y,w)=>s.jsx("div",{children:s.jsx(Zr,{path:e.path,arrayElement:!0,property:t,propertyType:n,value:y,ignoreMissingValues:e.ignoreMissingValues,link:e.link})},`${w}-${v.length}`));if(e.includeDescriptionListEntry){if(!Bt(e.path))throw new Error("props.path is required when includeDescriptionListEntry is true");const y=e.path.split(".").pop();h=s.jsx(No,{term:Rs(y),children:S})}else h=s.jsx(s.Fragment,{children:S})}return s.jsxs(s.Fragment,{children:[l.map((v,S)=>{if(!e.path)throw Error(`Displaying a resource property with slices of type ${e.propertyType} requires path`);let y=s.jsx(zB,{path:e.path,slice:v,property:t,value:u[S],ignoreMissingValues:e.ignoreMissingValues,link:e.link},v.name);return e.includeDescriptionListEntry&&(y=s.jsx(No,{term:Rs(v.name),children:y},v.name)),y}),h]})}function gu(e,t,n){const r=vn(e,t,{profileUrl:n});return r?Array.isArray(r)?[r.map(o=>o.value),r[0].type]:[r.value,r.type]:[void 0,"undefined"]}function UB(e,t,n){const r=YP(e,t,n);return r?Array.isArray(r)?[r.map(o=>o.value),r[0].type]:[r.value,r.type]:[void 0,"undefined"]}function VB(e){const{elementDefinitionType:t}=e,n=se(),r=p.useContext(bt),[o,i]=p.useState(QP("Extension")),a=p.useMemo(()=>{if(Bt(t==null?void 0:t.profile))return t.profile[0]},[t]),[l,c]=p.useState(a!==void 0);if(p.useEffect(()=>{a&&(c(!0),n.requestProfileSchema(a).then(()=>{const f=yl(a);c(!1),f&&i(f)}).catch(f=>{c(!1),console.warn(f)}))},[n,a]),a&&(l||!jx(a)))return s.jsx("div",{children:"Loading..."});const u=o.elements["value[x]"];if((u==null?void 0:u.max)!==0){const[f,h]=gu({type:"Extension",value:e.value},"value[x]",a??r.profileUrl);return s.jsx(Zr,{propertyType:h,value:f})}return s.jsx(wf,{path:e.path,value:{type:o.type,value:e.value},compact:e.compact,ignoreMissingValues:e.ignoreMissingValues,link:e.link,profileUrl:a})}function Zr(e){var i;const{property:t,propertyType:n,value:r}=e;if((i=t==null?void 0:t.path)==null?void 0:i.endsWith(".id"))return s.jsxs(q,{component:"div",style:{display:"flex",gap:3,alignItems:"center"},children:[r,!Gt(r)&&s.jsx(qT,{value:r,timeout:2e3,children:({copied:a,copy:l})=>s.jsx(Vs,{label:a?"Copied":"Copy",withArrow:!0,position:"right",children:s.jsx(tn,{variant:"subtle",color:a?"teal":"gray",onClick:l,children:a?s.jsx(Ks,{size:"1rem"}):s.jsx(Ak,{size:"1rem"})})})})]});if(t&&(t.isArray||t.max>1)&&!e.arrayElement)return n===H.Attachment?s.jsx(AB,{values:r,maxWidth:e.maxWidth,includeDescriptionListEntry:e.includeArrayDescriptionListEntry,property:t,path:e.path}):s.jsx(BB,{path:e.path,property:t,propertyType:n,values:r,includeDescriptionListEntry:e.includeArrayDescriptionListEntry,ignoreMissingValues:e.ignoreMissingValues,link:e.link});switch(n){case H.boolean:return s.jsx(s.Fragment,{children:r===void 0?"":(!!r).toString()});case H.SystemString:case H.string:return s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:r});case H.code:case H.date:case H.decimal:case H.id:case H.integer:case H.positiveInt:case H.unsignedInt:case H.uri:case H.url:return s.jsx(s.Fragment,{children:r});case H.canonical:return s.jsx(bf,{value:{reference:r},link:e.link});case H.dateTime:case H.instant:return s.jsx(s.Fragment,{children:Fn(r)});case H.markdown:return s.jsx("pre",{children:r});case H.Address:return s.jsx(W8,{value:r});case H.Annotation:return s.jsx(s.Fragment,{children:r==null?void 0:r.text});case H.Attachment:return s.jsx(mu,{value:r,maxWidth:e.maxWidth});case H.CodeableConcept:return s.jsx(yo,{value:r});case H.Coding:return s.jsx(MB,{value:r});case H.ContactDetail:return s.jsx(OB,{value:r});case H.ContactPoint:return s.jsx(Uk,{value:r});case H.HumanName:return s.jsx(qx,{value:r});case H.Identifier:return s.jsx(LB,{value:r});case H.Money:return s.jsx($B,{value:r});case H.Period:return s.jsx(s.Fragment,{children:T6(r)});case H.Quantity:case H.Duration:return s.jsx($c,{value:r});case H.Range:return s.jsx(Jx,{value:r});case H.Ratio:return s.jsx(FB,{value:r});case H.Reference:return s.jsx(bf,{value:r,link:e.link});case H.Timing:return s.jsx(s.Fragment,{children:sk(r)});case H.Dosage:case H.UsageContext:if(!e.path)throw Error(`Displaying property of type ${e.propertyType} requires path`);return s.jsx(wf,{path:e.path,value:{type:n,value:r},compact:!0,ignoreMissingValues:e.ignoreMissingValues});case H.Extension:if(!e.path)throw Error(`Displaying property of type ${e.propertyType} requires path`);return s.jsx(VB,{path:e.path,value:r,compact:!0,ignoreMissingValues:e.ignoreMissingValues,elementDefinitionType:e.elementDefinitionType});default:if(!t)throw Error(`Displaying property of type ${e.propertyType} requires element schema`);if(!e.path)throw Error(`Displaying property of type ${e.propertyType} requires path`);return s.jsx(wf,{path:e.path,value:{type:t.type[0].code,value:r},compact:!0,ignoreMissingValues:e.ignoreMissingValues})}}const Hk=["extension","modifierExtension"],WB=Dk.filter(e=>!Hk.includes(e));function wf(e){const t=e.value,{value:n,type:r}=t,o=p.useContext(bt),i=e.profileUrl??(o==null?void 0:o.profileUrl),a=p.useMemo(()=>Dh(r,i),[i,r]),l=p.useMemo(()=>{if(a)return rl({parentContext:o,elements:a.elements,path:e.path,profileUrl:a.url,accessPolicyResource:e.accessPolicyResource})},[a,o,e.path,e.accessPolicyResource]);if(Gt(n))return null;if(!a)return s.jsxs("div",{children:[r," not implemented"]});if(typeof n=="object"&&"name"in n&&Object.keys(n).length===1&&typeof n.name=="string")return s.jsx("div",{children:n.name});const c=l??o;return Fh(bt.Provider,l,s.jsx(Yx,{compact:e.compact,children:Object.entries(c.elements).map(([u,d])=>{var v;if(Hk.includes(u)&&Gt((v=d.slicing)==null?void 0:v.slices))return null;if(WB.includes(u))return null;if(Ik.includes(u)&&d.path.split(".").length===2||u.includes("."))return null;const[f,h]=gu(t,u,c.profileUrl);if((e.ignoreMissingValues||d.max===0)&&Gt(f)||e.path.endsWith(".extension")&&(u==="url"||u==="id"))return null;const m=d.max>1||d.isArray,g=s.jsx(Zr,{property:d,propertyType:h,path:e.path+"."+u,value:f,ignoreMissingValues:e.ignoreMissingValues,includeArrayDescriptionListEntry:m,link:e.link},u);return m?g:s.jsx(No,{term:Rs(u),children:g},u)})}))}const qk="Read Only";function Gk(e,t){return e?s.jsx(Vs.Floating,{label:e,children:t}):t}const HB="_dimmed_1pxw4_1",Qk={dimmed:HB};function Kk(e){const{debugMode:t}=p.useContext(bt);let n;return t&&e.fhirPath?n=`${e.title} - ${e.fhirPath}`:n=e.title,Gk(e!=null&&e.readonly?qk:void 0,s.jsxs(te,{wrap:"nowrap","data-testid":e.testId,children:[s.jsx("div",{children:e.children}),s.jsx("div",{children:s.jsx(Lt.Wrapper,{id:e.htmlFor,label:n,classNames:{label:e!=null&&e.readonly?Qk.dimmed:void 0},description:e.description,withAsterisk:e.withAsterisk,children:null})})]}))}function Je(e,t){var n,r,o;return(o=(r=(n=e==null?void 0:e.issue)==null?void 0:n.filter(i=>{var a;return Yk((a=i.expression)==null?void 0:a[0],t)}))==null?void 0:r.map(i=>{var a;return(a=i.details)==null?void 0:a.text}))==null?void 0:o.join(`
535
+ `)}function vu(e,t){var n;return(n=e==null?void 0:e.issue)==null?void 0:n.filter(r=>{var o;return Yk((o=r.expression)==null?void 0:o[0],t)})}const ad=/\[\d+\]/;function Yk(e,t){const n=typeof e=="string"&&ad.test(e),r=typeof t=="string"&&ad.test(t);if(n!==r&&(e=e==null?void 0:e.replace(ad,""),t=t==null?void 0:t.replace(ad,"")),e===t)return!0;if(!e||!t)return!1;const o=e.indexOf(".");if(o>=0&&e.substring(o+1)===t)return!0;const i=t.indexOf(".");return i>=0&&t.substring(i+1)===e}function vt(e){const{debugMode:t}=p.useContext(bt);let n;return t&&e.fhirPath?n=`${e.title} - ${e.fhirPath}`:n=e.title,Gk(e!=null&&e.readonly?qk:void 0,s.jsx(Lt.Wrapper,{id:e.htmlFor,label:n,classNames:{label:e!=null&&e.readonly?Qk.dimmed:void 0},description:e.description,withAsterisk:e.withAsterisk,error:Je(e.outcome,e.errorExpression??e.htmlFor),"data-testid":e.testId,children:e.children}))}function Xk(e,t,n,r,o){const i=r.type;if(i.length>1)for(const a of i){const l=t.replace("[x]",nn(a.code));l in e&&delete e[l]}return e[n]=o,e}function qB(e){return!!e&&!Gt(e.url)&&!Gt(e.name)}function GB(e){const{defaultValue:t,onChange:n,withHelpText:r,outcome:o,path:i,valuePath:a,...l}=e,[c,u]=p.useState(t);function d(f){const h=KB(f);u(h),n&&n(h)}return s.jsx(Qx,{defaultValue:c&&QB(c),onChange:d,withHelpText:r??!0,...l})}function QB(e){var t;return(t=e.coding)==null?void 0:t.map(n=>({system:n.system,code:n.code,display:n.display}))}function KB(e){if(e.length!==0)return{coding:e.map(t=>({system:t.system,code:t.code,display:t.display}))}}function Jk(e){const{defaultValue:t,onChange:n,withHelpText:r,...o}=e,[i,a]=p.useState(t);function l(c){const u=c[0],d=u&&XB(u);a(d),n&&n(d)}return s.jsx(Qx,{defaultValue:i&&YB(i),maxValues:1,onChange:l,withHelpText:r??!0,...o})}function YB(e){return{system:e.system,code:e.code,display:e.display}}function XB(e){return{system:e.system,code:e.code,display:e.display}}function Zk(e){const{path:t,outcome:n}=e,{elementsByPath:r,getExtendedProps:o}=p.useContext(bt),[i,a]=p.useState(e.defaultValue),l=p.useRef();l.current=i;const[c,u,d]=p.useMemo(()=>["system","use","value"].map(b=>r[t+"."+b]),[r,t]),[f,h,m]=p.useMemo(()=>["system","use","value"].map(b=>o(t+"."+b)),[o,t]);function g(b){b&&Object.keys(b).length===0&&(b=void 0),a(b),e.onChange&&e.onChange(b)}function v(b){const x={...l.current,system:b};b||delete x.system,g(x)}function S(b){const x={...l.current,use:b};b||delete x.use,g(x)}function y(b){const x={...l.current,value:b};b||delete x.value,g(x)}const w=e.valuePath??t;return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[s.jsx(It,{disabled:e.disabled||(f==null?void 0:f.readonly),"data-testid":"system",defaultValue:i==null?void 0:i.system,required:((c==null?void 0:c.min)??0)>0,onChange:b=>v(b.currentTarget.value),data:["","email","phone","fax","pager","sms","other"],error:Je(n,w+".system")}),s.jsx(It,{disabled:e.disabled||(h==null?void 0:h.readonly),"data-testid":"use",defaultValue:i==null?void 0:i.use,required:((u==null?void 0:u.min)??0)>0,onChange:b=>S(b.currentTarget.value),data:["","home","work","temp","old","mobile"],error:Je(n,w+".use")}),s.jsx(ve,{disabled:e.disabled||(m==null?void 0:m.readonly),placeholder:"Value",defaultValue:i==null?void 0:i.value,required:((d==null?void 0:d.min)??0)>0,onChange:b=>y(b.currentTarget.value),error:Je(n,w+".value")})]})}function JB(e){var d;const[t,n]=p.useState(e.defaultValue),r=p.useRef();r.current=t;const{getExtendedProps:o}=p.useContext(bt),[i,a]=p.useMemo(()=>["name","telecom"].map(f=>o(e.path+"."+f)),[o,e.path]);function l(f){n(f),e.onChange&&e.onChange(f)}function c(f){const h={...r.current,name:f};f||delete h.name,l(h)}function u(f){const h={...r.current,telecom:f&&[f]};f||delete h.telecom,l(h)}return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(ve,{disabled:e.disabled||(i==null?void 0:i.readonly),"data-testid":e.name+"-name",name:e.name+"-name",placeholder:"Name",style:{width:180},defaultValue:t==null?void 0:t.name,onChange:f=>c(f.currentTarget.value)}),s.jsx(Zk,{disabled:e.disabled||(a==null?void 0:a.readonly),name:e.name+"-telecom",path:e.path+".telecom",defaultValue:(d=t==null?void 0:t.telecom)==null?void 0:d[0],onChange:u,outcome:e.outcome})]})}function ZB(e){if(!e)return"";const t=new Date(e);return Ih(t)?t.toLocaleDateString("sv")+"T"+t.toLocaleTimeString("sv"):""}function eR(e){if(!e)return"";const t=new Date(e);return Ih(t)?t.toISOString():""}function _s(e){return s.jsx(ve,{id:e.name,name:e.name,label:e.label,"data-autofocus":e.autoFocus,"data-testid":e["data-testid"]??e.name,placeholder:e.placeholder,required:e.required,disabled:e.disabled,type:eU(),defaultValue:ZB(e.defaultValue),autoFocus:e.autoFocus,error:Je(e.outcome,e.name),onChange:t=>{if(e.onChange){const n=t.currentTarget.value;e.onChange(eR(n))}}})}function eU(){return"datetime-local"}function tU(e){const{propertyType:t}=e,n=se(),r=p.useMemo(()=>{if(Bt(t.profile))return t.profile[0]},[t]),[o,i]=p.useState(r!==void 0);return p.useEffect(()=>{r&&(i(!0),n.requestProfileSchema(r).then(()=>i(!1)).catch(a=>{i(!1),console.warn(a)}))},[n,r]),r&&(o||!jx(r))?s.jsx("div",{children:"Loading..."}):s.jsx(t0,{profileUrl:r,path:e.path,typeName:"Extension",defaultValue:e.defaultValue,onChange:e.onChange})}function nU(e){var w,b,x;const{outcome:t,path:n}=e,[r,o]=p.useState(e.defaultValue),{getExtendedProps:i}=p.useContext(bt),[a,l,c,u,d]=p.useMemo(()=>["use","prefix","given","family","suffix"].map(C=>i(e.path+"."+C)),[i,e.path]);function f(C){o(C),e.onChange&&e.onChange(C)}function h(C){f({...r,use:C||void 0})}function m(C){f({...r,prefix:C?C.split(" "):void 0})}function g(C){f({...r,given:C?C.split(" "):void 0})}function v(C){f({...r,family:C||void 0})}function S(C){f({...r,suffix:C?C.split(" "):void 0})}const y=e.valuePath??n;return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(It,{disabled:e.disabled||(a==null?void 0:a.readonly),defaultValue:r==null?void 0:r.use,name:e.name+"-use","data-testid":"use",onChange:C=>h(C.currentTarget.value),data:["","temp","old","usual","official","nickname","anonymous","maiden"],error:Je(t,y+".use")}),s.jsx(ve,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"Prefix",name:e.name+"-prefix",defaultValue:(w=r==null?void 0:r.prefix)==null?void 0:w.join(" "),onChange:C=>m(C.currentTarget.value),error:Je(t,y+".prefix")}),s.jsx(ve,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Given",name:e.name+"-given",defaultValue:(b=r==null?void 0:r.given)==null?void 0:b.join(" "),onChange:C=>g(C.currentTarget.value),error:Je(t,y+".given")}),s.jsx(ve,{disabled:e.disabled||(u==null?void 0:u.readonly),name:e.name+"-family",placeholder:"Family",defaultValue:r==null?void 0:r.family,onChange:C=>v(C.currentTarget.value),error:Je(t,y+".family")}),s.jsx(ve,{disabled:e.disabled||(d==null?void 0:d.readonly),placeholder:"Suffix",name:e.name+"-suffix",defaultValue:(x=r==null?void 0:r.suffix)==null?void 0:x.join(" "),onChange:C=>S(C.currentTarget.value),error:Je(t,y+".suffix")})]})}function rU(e){const[t,n]=p.useState(e.defaultValue),{elementsByPath:r,getExtendedProps:o}=p.useContext(bt),[i,a]=p.useMemo(()=>["system","value"].map(f=>r[e.path+"."+f]),[r,e.path]),[l,c]=p.useMemo(()=>["system","value"].map(f=>o(e.path+"."+f)),[o,e.path]);function u(f){n(f),e.onChange&&e.onChange(f)}const d=e.valuePath??e.path;return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[s.jsx(ve,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"System",required:((i==null?void 0:i.min)??0)>0,defaultValue:t==null?void 0:t.system,onChange:f=>u({...t,system:f.currentTarget.value}),error:Je(e.outcome,d+".system")}),s.jsx(ve,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Value",required:((a==null?void 0:a.min)??0)>0,defaultValue:t==null?void 0:t.value,onChange:f=>u({...t,value:f.currentTarget.value}),error:Je(e.outcome,d+".value")})]})}const oU=["USD","EUR","CAD","GBP","AUD"];function iU(e){var f;const{onChange:t}=e,[n,r]=p.useState(e.defaultValue),{getExtendedProps:o}=p.useContext(bt),[i,a]=p.useMemo(()=>["currency","value"].map(h=>o(e.path+"."+h)),[o,e.path]),l=p.useCallback(h=>{r(h),t&&t(h)},[t]),c=p.useCallback(h=>{l({...n,currency:h.currentTarget.value})},[n,l]),u=p.useCallback(h=>{l({...n,value:h.currentTarget.valueAsNumber})},[n,l]),d=s.jsx(It,{disabled:e.disabled||(i==null?void 0:i.readonly),defaultValue:n==null?void 0:n.currency,data:oU,styles:{input:{fontWeight:500,borderTopLeftRadius:0,borderBottomLeftRadius:0,width:92}},onChange:c});return s.jsx(ve,{disabled:e.disabled||(a==null?void 0:a.readonly),type:"number",name:e.name,label:e.label,placeholder:e.placeholder??"Value",defaultValue:((f=n==null?void 0:n.value)==null?void 0:f.toString())??"USD",leftSection:s.jsx(cz,{size:14}),rightSection:d,rightSectionWidth:92,onChange:u})}function sU(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(bt),[o,i]=p.useMemo(()=>["start","end"].map(l=>r(e.path+"."+l)),[r,e.path]);function a(l){n(l),e.onChange&&e.onChange(l)}return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(_s,{disabled:e.disabled||(o==null?void 0:o.readonly),name:e.name+".start",placeholder:"Start",defaultValue:t==null?void 0:t.start,onChange:l=>a({...t,start:l})}),s.jsx(_s,{disabled:e.disabled||(i==null?void 0:i.readonly),name:e.name+".end",placeholder:"End",defaultValue:t==null?void 0:t.end,onChange:l=>a({...t,end:l})})]})}function Ds(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(bt),[o,i,a]=p.useMemo(()=>["comparator","value","unit"].map(c=>r(e.path+"."+c)),[r,e.path]);function l(c){n(c),e.onChange&&e.onChange(c)}return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(It,{disabled:e.disabled||(o==null?void 0:o.readonly),style:{width:80},"data-testid":e.name+"-comparator",defaultValue:t==null?void 0:t.comparator,data:["","<","<=",">=",">"],onChange:c=>l({...t,comparator:c.currentTarget.value})}),s.jsx(ve,{disabled:e.disabled||(i==null?void 0:i.readonly),id:e.name,name:e.name,required:e.required,"data-autofocus":e.autoFocus,"data-testid":e.name+"-value",type:"number",placeholder:"Value",defaultValue:t==null?void 0:t.value,autoFocus:e.autoFocus,step:"any",onWheel:c=>{e.disableWheel&&c.currentTarget.blur()},onChange:c=>{l({...t,value:aU(c.currentTarget.value)})}}),s.jsx(ve,{disabled:e.disabled||(a==null?void 0:a.readonly),placeholder:"Unit","data-testid":e.name+"-unit",defaultValue:t==null?void 0:t.unit,onChange:c=>l({...t,unit:c.currentTarget.value})})]})}function aU(e){if(e)return parseFloat(e)}function Zx(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(bt),[o,i]=p.useMemo(()=>["low","high"].map(l=>r(e.path+"."+l)),[r,e.path]);function a(l){n(l),e.onChange&&e.onChange(l)}return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(Ds,{path:e.path+".low",disabled:e.disabled||(o==null?void 0:o.readonly),name:e.name+"-low",defaultValue:t==null?void 0:t.low,onChange:l=>a({...t,low:l})}),s.jsx(Ds,{path:e.path+".high",disabled:e.disabled||(i==null?void 0:i.readonly),name:e.name+"-high",defaultValue:t==null?void 0:t.high,onChange:l=>a({...t,high:l})})]})}function lU(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(bt),[o,i]=p.useMemo(()=>["numerator","denominator"].map(l=>r(e.path+"."+l)),[r,e.path]);function a(l){n(l),e.onChange&&e.onChange(l)}return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(Ds,{path:e.path+".numerator",disabled:e.disabled||(o==null?void 0:o.readonly),name:e.name+"-numerator",defaultValue:t==null?void 0:t.numerator,onChange:l=>a({...t,numerator:l})}),s.jsx(Ds,{path:e.path+".denominator",disabled:e.disabled||(i==null?void 0:i.readonly),name:e.name+"-denominator",defaultValue:t==null?void 0:t.denominator,onChange:l=>a({...t,denominator:l})})]})}const cU={Device:"device-name",Observation:"code",Subscription:"criteria",User:"email:contains"},uU=["AccessPolicy","Account","ActivityDefinition","Bot","CapabilityStatement","CareTeam","ClientApplication","CodeSystem","CompartmentDefinition","ConceptMap","EffectEvidenceSynthesis","Endpoint","EventDefinition","Evidence","EvidenceVariable","ExampleScenario","GraphDefinition","Group","HealthcareService","ImplementationGuide","InsurancePlan","Library","Location","Measure","MedicinalProduct","MessageDefinition","NamingSystem","OperationDefinition","Organization","Patient","Person","PlanDefinition","Practitioner","Project","Questionnaire","RelatedPerson","ResearchDefinition","ResearchElementDefinition","RiskEvidenceSynthesis","SearchParameter","StructureDefinition","StructureMap","TerminologyCapabilities","TestScript","UserConfiguration","ValueSet"];function dU(e){return{value:st(e),label:Wo(e),resource:e}}function Ys(e){const t=se(),{resourceType:n,searchCriteria:r}=e,[o,i]=p.useState(),a=wt(e.defaultValue,i),l=e.itemComponent??fU,c=e.onChange,u=p.useCallback(async(f,h)=>{const m=hU(n),g=new URLSearchParams({[m]:f??"",_count:"10",...r});return await t.searchResources(n,g,{signal:h})},[t,n,r]),d=p.useCallback(f=>{c&&c(f[0])},[c]);return Bt(e.defaultValue)&&!o&&!a?null:s.jsx(Gx,{disabled:e.disabled,name:e.name,required:e.required,itemComponent:l,defaultValue:a,placeholder:e.placeholder,maxValues:1,toOption:dU,loadOptions:u,onChange:d,clearable:!0})}const fU=p.forwardRef(({label:e,resource:t,active:n,...r},o)=>s.jsx("div",{ref:o,...r,children:s.jsxs(te,{wrap:"nowrap",children:[s.jsx(Hi,{value:t}),s.jsxs("div",{children:[s.jsx(fe,{children:e}),s.jsx(fe,{size:"xs",c:"dimmed",children:t.birthDate||t.id})]})]})}));function hU(e){return cU[e]??(uU.includes(e)?"name":"_id")}function zh(e){const{onChange:t}=e,n=se(),[r,o]=p.useState(e.defaultValue),[i,a]=p.useState(()=>pU(e.targetTypes)),[l,c]=p.useState(()=>mU(e.defaultValue,i)),u=p.useRef(new wk),d=p.useMemo(()=>(l==null?void 0:l.type)==="profile"?{...e.searchCriteria,_profile:l.value}:e.searchCriteria,[e.searchCriteria,l]);p.useEffect(()=>{let m=!1;const g=i==null?void 0:i.map(v=>{if(!vU(v))return Promise.resolve(v);m=!0;const S=v.value,y=u.current.get(S);if(y)return y;const w=gU(n,v.value).then(x=>{const C={...v};return x?Bt(x.type)?(C.resourceType=x.type,C.name=x.name,C.title=x.title):(console.error(`StructureDefinition.type missing for ${v.value}`),C.error="StructureDefinition.type missing"):(console.error(`StructureDefinition not found for ${v.value}`),C.error="StructureDefinition not found"),C}).catch(x=>(console.error(x),{...v,error:x})),b=new Fr(w);return u.current.set(S,b),b});!g||!m||Promise.all(g).then(v=>{if(a(v),!l)return;const S=v.findIndex(y=>y.value===l.value||y.resourceType===l.resourceType);if(S===-1){console.debug(`defaultValue had unexpected resourceType: ${l.resourceType}`);return}c(v[S])}).catch(console.error)},[n,l,i]);const f=p.useCallback(m=>{const g=m?Et(m):void 0;o(g),t&&t(g)},[t]),h=p.useMemo(()=>i?i.map(m=>({value:m.value,label:m.type==="profile"?m.title??m.name??m.resourceType??m.value:m.value})):[],[i]);return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[i&&i.length>1&&s.jsx(It,{disabled:e.disabled,"data-autofocus":e.autoFocus,"data-testid":"reference-input-resource-type-select",defaultValue:l==null?void 0:l.resourceType,autoFocus:e.autoFocus,onChange:m=>{const g=m.currentTarget.value,v=i.find(S=>S.value===g);c(v)},data:h}),!i&&s.jsx(Kx,{disabled:e.disabled,autoFocus:e.autoFocus,testId:"reference-input-resource-type-input",defaultValue:l==null?void 0:l.resourceType,onChange:m=>{c(m?{type:"resourceType",value:m,resourceType:m}:void 0)},name:e.name+"-resourceType",placeholder:"Resource Type"}),s.jsx(Ys,{resourceType:l==null?void 0:l.resourceType,name:e.name+"-id",required:e.required,placeholder:e.placeholder,defaultValue:r,searchCriteria:d,onChange:f,disabled:e.disabled})]})}function pU(e){if(!e||e.length===0||e.length===1&&e[0]==="Resource")return;const t=[];for(const n of e)n.includes("/")?t.push({type:"profile",value:n}):t.push({type:"resourceType",value:n,resourceType:n});return t}function mU(e,t){var r;const n=(r=e==null?void 0:e.reference)==null?void 0:r.split("/")[0];if(n){const o=t==null?void 0:t.find(i=>i.resourceType===n);return o||{type:"resourceType",value:n,resourceType:n}}if(t&&t.length>0)return t[0]}async function gU(e,t){const n=yl(t);if(n)return{type:n.type,name:n.name,title:n.title};const r=`{
536
536
  StructureDefinitionList(url: "${t}", _sort: "_lastUpdated", _count: 1) {
537
537
  type,
538
538
  name,
539
539
  title,
540
540
  }
541
- }`.replace(/\s+/g," ");return(await e.graphql(r)).data.StructureDefinitionList[0]}function gU(e){return e.type==="profile"&&!(e!=null&&e.error)&&Gt(e.resourceType)}const vU="_indented_ldk1d_1",tR={indented:vU};function nR({propertyDisplayName:e,onClick:t,testId:n}){const r=e?`Add ${e}`:"Add";return e?s.jsx(oe,{title:r,size:"sm",color:"green.6",variant:"subtle","data-testid":n,leftSection:s.jsx(yf,{size:"1.25rem"}),onClick:t,children:r}):s.jsx(tn,{title:r,color:"green.6","data-testid":n,onClick:t,children:s.jsx(yf,{size:"1.25rem"})})}function rR({propertyDisplayName:e,onClick:t,testId:n}){return s.jsx(tn,{title:e?`Remove ${e}`:"Remove",color:"red.5","data-testid":n,variant:"subtle",onClick:t,children:s.jsx(vf,{size:"1.25rem"})})}function yU(e){var m,g;const{slice:t,property:n}=e,[r,o]=p.useState(e.defaultValue),i=((m=t.typeSchema)==null?void 0:m.elements)??t.elements,a=p.useContext(bt),l=p.useMemo(()=>{var v;if(Bt(i))return rl({parentContext:a,elements:i,path:e.path,profileUrl:(v=t.typeSchema)==null?void 0:v.url})},[a,e.path,(g=t.typeSchema)==null?void 0:g.url,i]);function c(v){o(v),e.onChange&&e.onChange(v)}const u=t.min>0,d=Gt(t.elements),f=ck(t.name),h=e.property.readonly&&r.length===0;return Fh(bt.Provider,l,s.jsx(vt,{title:f,description:t.definition,withAsterisk:u,fhirPath:`${n.path}:${t.name}`,testId:e.testId,readonly:e.property.readonly,children:h?s.jsx(fe,{c:"dimmed",children:"(empty)"}):s.jsxs(Oe,{className:d?tR.indented:void 0,children:[r.map((v,S)=>s.jsxs(te,{wrap:"nowrap",children:[s.jsx("div",{style:{flexGrow:1},"data-testid":e.testId&&`${e.testId}-elements-${S}`,children:s.jsx(e0,{elementDefinitionType:t.type[0],name:t.name,defaultValue:v,onChange:y=>{const w=[...r];w[S]=y,c(w)},outcome:e.outcome,min:t.min,max:t.max,binding:t.binding,path:e.path,valuePath:void 0,readOnly:e.property.readonly})}),!e.property.readonly&&r.length>t.min&&s.jsx(rR,{propertyDisplayName:f,testId:e.testId&&`${e.testId}-remove-${S}`,onClick:y=>{yt(y);const w=[...r];w.splice(S,1),c(w)}})]},`${S}-${r.length}`)),!e.property.readonly&&r.length<t.max&&s.jsx(te,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:s.jsx(nR,{propertyDisplayName:f,onClick:v=>{yt(v);const S=[...r,void 0];c(S)},testId:e.testId&&`${e.testId}-add`})})]})}))}function xU(e,t,n){return t===void 0?e:n===void 0?t:`${t}[${n}]`}function bU(e){var w;const{property:t}=e,n=se(),[r,o]=p.useState(!0),[i,a]=p.useState([]),[l]=p.useState(()=>Array.isArray(e.defaultValue)?e.defaultValue:[]),[c,u]=p.useState(()=>[l]),d=p.useContext(bt),f=(w=t.type[0])==null?void 0:w.code;p.useEffect(()=>{Wk({medplum:n,property:t}).then(b=>{a(b);const x=Vk(l,b,t.slicing,d.profileUrl);wU(x,b),u(x),o(!1)}).catch(b=>{console.error(b),o(!1)})},[n,t,l,d.profileUrl,u]);function h(b,x){const C=[...c];if(C[x]=b,u(C),e.onChange){const j=C.flat().filter(T=>T!==void 0);e.onChange(j)}}if(r)return s.jsx("div",{children:"Loading..."});const m=i.length,g=c[m],v=!(e.hideNonSliceValues??(f==="Extension"&&i.length>0)),S=Rs(t.path),y=e.property.readonly&&i.length===0&&l.length===0;return s.jsxs(Oe,{className:e.indent?tR.indented:void 0,children:[y&&s.jsx(fe,{c:"dimmed",children:"(empty)"}),i.map((b,x)=>s.jsx(yU,{slice:b,path:e.path,valuePath:e.valuePath,property:t,defaultValue:c[x],onChange:C=>{h(C,x)},testId:`slice-${b.name}`},b.name)),v&&g.map((b,x)=>s.jsxs(te,{wrap:"nowrap",style:{flexGrow:1},children:[s.jsx("div",{style:{flexGrow:1},children:s.jsx(jl,{arrayElement:!0,property:e.property,name:e.name+"."+x,path:e.path,valuePath:xU(e.path,e.valuePath,x),defaultValue:b,onChange:C=>{const j=[...g];j[x]=C,h(j,m)},defaultPropertyType:void 0,outcome:e.outcome})}),!e.property.readonly&&s.jsx(rR,{propertyDisplayName:S,testId:`nonsliced-remove-${x}`,onClick:C=>{yt(C);const j=[...g];j.splice(x,1),h(j,m)}})]},`${x}-${g.length}`)),!e.property.readonly&&v&&c.flat().length<t.max&&s.jsx(te,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:s.jsx(nR,{propertyDisplayName:S,onClick:b=>{yt(b);const x=[...g];x.push(void 0),h(x,m)},testId:"nonsliced-add"})})]})}function wU(e,t){for(let n=0;n<t.length;n++){const r=t[n],o=e[n];for(;o.length<r.min;)o.push(void 0)}}function SU(e){const[t,n]=p.useState(!1),r=ZS(),o=p.useRef(null),i={...e.styles};return t||(i.input||(i.input={}),i.input.WebkitTextSecurity="disc"),s.jsxs(Es,{gap:"xs",children:[s.jsx(Us,{...e,styles:{...i,root:{...i.root??{},flexGrow:1}},ref:o,autosize:!0,minRows:1,onFocus:()=>n(!0),onBlur:()=>n(!1)}),s.jsx(tn,{title:"Copy secret",onClick:()=>{var a;r.copy((a=o.current)==null?void 0:a.value),he({color:"green",message:"Copied"})},children:s.jsx(Ak,{})})]})}const jU=["sun","mon","tue","wed","thu","fri","sat"];function CU(e){const[t,n]=p.useState(e.defaultValue),[r,o]=p.useState(!e.disabled&&(e.defaultModalOpen??!1)),i=p.useRef();return i.current=t,s.jsxs(s.Fragment,{children:[s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx("span",{children:sk(i.current)||"No repeat"}),s.jsx(oe,{disabled:e.disabled,onClick:()=>o(!0),children:"Edit"})]}),!e.disabled&&s.jsx(EU,{path:e.path,visible:r,defaultValue:i.current,onOk:a=>{e.onChange&&e.onChange(a),n(a),o(!1)},onCancel:()=>o(!1)})]})}const kw={repeat:{period:1,periodUnit:"d"}};function EU(e){const[t,n]=p.useState(e.defaultValue||kw),{getExtendedProps:r}=p.useContext(bt),[o,i,a,l,c]=p.useMemo(()=>["event","repeat","repeat.period","repeat.periodUnit","repeat.dayOfWeek"].map(v=>r(e.path+"."+v)),[r,e.path]),u=p.useRef();u.current=t;function d(v){n({...u.current,event:[v]})}function f(v){n({...u.current,repeat:v})}function h(v){var S;f({...(S=u.current)==null?void 0:S.repeat,period:v})}function m(v){var S;f({...(S=u.current)==null?void 0:S.repeat,periodUnit:v})}function g(v){var S;f({...(S=u.current)==null?void 0:S.repeat,dayOfWeek:v})}return s.jsx(wn,{title:"Timing",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:()=>e.onCancel(),children:s.jsxs(Oe,{children:[s.jsx(vt,{title:"Starts on",htmlFor:"timing-dialog-start",children:s.jsx(_s,{disabled:o==null?void 0:o.readonly,name:"timing-dialog-start",onChange:v=>d(v)})}),s.jsx(lu,{disabled:i==null?void 0:i.readonly,label:"Repeat",checked:!!t.repeat,onChange:v=>f(v.currentTarget.checked?kw.repeat:void 0)}),t.repeat&&s.jsxs(s.Fragment,{children:[s.jsx(vt,{title:"Repeat every",htmlFor:"timing-dialog-period",children:s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(ve,{disabled:a==null?void 0:a.readonly,type:"number",step:1,id:"timing-dialog-period",name:"timing-dialog-period",defaultValue:t.repeat.period||1,onChange:v=>h(parseInt(v.currentTarget.value,10)||1)}),s.jsx(It,{disabled:l==null?void 0:l.readonly,id:"timing-dialog-periodUnit",name:"timing-dialog-periodUnit",defaultValue:t.repeat.periodUnit,onChange:v=>m(v.currentTarget.value),data:[{label:"second",value:"s"},{label:"minute",value:"min"},{label:"hour",value:"h"},{label:"day",value:"d"},{label:"week",value:"wk"},{label:"month",value:"mo"},{label:"year",value:"a"}]})]})}),t.repeat.periodUnit==="wk"&&s.jsx(vt,{title:"Repeat on",children:s.jsx(_c.Group,{multiple:!0,onChange:g,children:s.jsx(te,{justify:"space-between",mt:"md",gap:"xs",children:jU.map(v=>s.jsx(_c,{value:v,size:"xs",radius:"xl",disabled:c==null?void 0:c.readonly,children:v.charAt(0).toUpperCase()},v))})})})]}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{onClick:()=>e.onOk(t),children:"OK"})})]})})}function jl(e){var l;const{property:t,name:n,onChange:r,defaultValue:o}=e,i=e.defaultPropertyType&&e.defaultPropertyType!=="undefined"?e.defaultPropertyType:t.type[0].code,a=t.type;if((t.isArray||t.max>1)&&!e.arrayElement){if(i===H.Attachment)return s.jsx(AB,{name:n,defaultValue:o,onChange:r,disabled:t.readonly});const c=((l=a[0])==null?void 0:l.code)!==H.Extension;return s.jsx(bU,{property:t,name:n,path:e.path,valuePath:e.valuePath,defaultValue:o,indent:c,onChange:r,outcome:e.outcome})}else return a.length>1?s.jsx(TU,{elementDefinitionTypes:a,...e}):s.jsx(e0,{name:n,defaultValue:o,onChange:c=>{if(e.onChange){const u=e.name.replace("[x]",nn(a[0].code));e.onChange(c,u)}},outcome:e.outcome,elementDefinitionType:a[0],min:t.min,max:t.min,binding:t.binding,path:e.path,valuePath:e.valuePath,readOnly:t.readonly})}function TU(e){const t=e.elementDefinitionTypes;let n;e.defaultPropertyType&&(n=t.find(i=>i.code===e.defaultPropertyType)),n||(n=t[0]);const[r,o]=p.useState(n);return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[s.jsx(It,{disabled:e.property.readonly,style:{width:"200px"},defaultValue:r.code,"data-testid":e.name&&e.name+"-selector",onChange:i=>{o(t.find(a=>a.code===i.currentTarget.value))},data:t.map(i=>({value:i.code,label:i.code}))}),s.jsx(e0,{name:e.name,defaultValue:e.defaultValue,outcome:e.outcome,elementDefinitionType:r,onChange:i=>{e.onChange&&e.onChange(i,e.name.replace("[x]",nn(r.code)))},min:e.property.min,max:e.property.max,binding:e.property.binding,path:e.property.path,valuePath:e.valuePath,readOnly:e.property.readonly})]})}function e0(e){const{name:t,onChange:n,outcome:r,binding:o,path:i,valuePath:a,readOnly:l}=e,c=e.min!==void 0&&e.min>0,u=e.elementDefinitionType.code,d=p.useContext(bt),f=p.useMemo(()=>{if(!Px(u)||!Gt(e.defaultValue))return e.defaultValue;const g=Object.create(null);if(d.path===e.path)mw(g,d.elements);else{const v=Ac(d.path,e.path);if(v===void 0)return e.defaultValue;mw(g,d.elements,v)}return Bt(g)?g:e.defaultValue},[u,d.path,d.elements,e.path,e.defaultValue]);if(!u)return s.jsx("div",{children:"Property type not specified "});function h(){return{name:t,defaultValue:f,onChange:n,outcome:r,path:i,valuePath:a,disabled:l}}function m(){const g=Je(e.outcome,a??i);return{id:t,name:t,"data-testid":t,defaultValue:f,required:c,error:g,disabled:l}}switch(u){case H.SystemString:case H.canonical:case H.string:case H.time:case H.uri:case H.url:return e.path==="Project.secret.value[x]"?s.jsx(SU,{...m(),onChange:g=>{e.onChange&&e.onChange(g.currentTarget.value)}}):s.jsx(ve,{...m(),onChange:g=>{n&&n(g.currentTarget.value)}});case H.date:return s.jsx(ve,{...m(),type:"date",onChange:g=>{n&&n(g.currentTarget.value)}});case H.dateTime:case H.instant:return s.jsx(_s,{...m(),onChange:n,outcome:r});case H.decimal:case H.integer:case H.positiveInt:case H.unsignedInt:return s.jsx(ve,{...m(),type:"number",step:u===H.decimal?"any":"1",onChange:g=>{if(n){const v=g.currentTarget.valueAsNumber;n(Number.isNaN(v)?void 0:v)}}});case H.code:return s.jsx(zk,{...m(),error:void 0,onChange:n,binding:o==null?void 0:o.valueSet});case H.boolean:return s.jsx(_n,{...m(),defaultChecked:!!f,onChange:g=>{n&&n(g.currentTarget.checked)}});case H.base64Binary:case H.markdown:return s.jsx(Us,{...m(),spellCheck:u!==H.base64Binary,onChange:g=>{n&&n(g.currentTarget.value)}});case H.Address:return s.jsx(q8,{...h()});case H.Annotation:return s.jsx(G8,{...h()});case H.Attachment:return s.jsx(Bk,{...h()});case H.CodeableConcept:return s.jsx(qB,{binding:o==null?void 0:o.valueSet,...h()});case H.Coding:return s.jsx(Jk,{binding:o==null?void 0:o.valueSet,...h()});case H.ContactDetail:return s.jsx(XB,{...h()});case H.ContactPoint:return s.jsx(Zk,{...h()});case H.Extension:return s.jsx(eU,{...h(),propertyType:e.elementDefinitionType});case H.HumanName:return s.jsx(tU,{...h()});case H.Identifier:return s.jsx(nU,{...h()});case H.Money:return s.jsx(oU,{...h()});case H.Period:return s.jsx(iU,{...h()});case H.Duration:case H.Quantity:return s.jsx(Ds,{...h()});case H.Range:return s.jsx(Zx,{...h()});case H.Ratio:return s.jsx(aU,{...h()});case H.Reference:return s.jsx(zh,{...h(),targetTypes:kU(e.elementDefinitionType)});case H.Timing:return s.jsx(CU,{...h()});case H.Dosage:case H.UsageContext:default:return s.jsx(t0,{...h(),typeName:u})}}const PU=[`${A$}/fhir/StructureDefinition/`,"https://medplum.com/fhir/StructureDefinition/"];function kU(e){var t;return(t=e==null?void 0:e.targetProfile)==null?void 0:t.map(n=>{const r=PU.find(o=>n.startsWith(o));return r?n.slice(r.length):n})}function RU(e){const[t,n]=p.useState(e.defaultValue??{}),r=p.useContext(bt),o=p.useMemo(()=>H8(r.elements),[r.elements]);function i(l){n(l),e.onChange&&e.onChange(l)}const a={type:e.type,value:t};return s.jsx(Oe,{style:{flexGrow:1},"data-testid":e.testId,children:o.map(([l,c])=>{const[u,d]=BB(a,l,c),f=c.min!==void 0&&c.min>0,h=e.valuePath?e.valuePath+"."+l:void 0,m=s.jsx(jl,{property:c,name:l,path:e.path+"."+l,valuePath:h,defaultValue:u,defaultPropertyType:d,onChange:(g,v)=>{i(Xk({...t},l,v??l,c,g))},outcome:e.outcome},l);return e.type==="Extension"||zx.includes(l)?m:c.type.length===1&&c.type[0].code==="boolean"?s.jsx(Kk,{title:Rs(l),description:c.description,htmlFor:l,fhirPath:c.path,withAsterisk:f,readonly:c.readonly,children:m},l):s.jsx(vt,{title:Rs(l),description:c.description,withAsterisk:f,htmlFor:l,outcome:e.outcome,fhirPath:c.path,errorExpression:h,readonly:c.readonly,children:m},l)})})}function t0(e){const[t]=p.useState(()=>e.defaultValue??{}),n=p.useContext(bt),r=e.profileUrl??(n==null?void 0:n.profileUrl),o=p.useMemo(()=>Dh(e.typeName,r),[e.typeName,r]),i=(o==null?void 0:o.type)??e.typeName,a=p.useMemo(()=>{if(o)return rl({parentContext:n,elements:o.elements,path:e.path,profileUrl:o.url,accessPolicyResource:e.accessPolicyResource})},[o,n,e.path,e.accessPolicyResource]);return o?Fh(bt.Provider,a,s.jsx(RU,{path:e.path,valuePath:e.valuePath,type:i,defaultValue:t,onChange:e.onChange,outcome:e.outcome})):s.jsxs("div",{children:[i," not implemented"]})}const _U="_root_1vii2_1",DU={root:_U};function yu(e){const{children:t,...n}=e;return s.jsx(zy,{className:DU.root,...n,children:t})}const IU="_noteBody_10swh_1",AU="_noteCite_10swh_5",NU="_noteRoot_10swh_10",Rw={noteBody:IU,noteCite:AU,noteRoot:NU};function oR({value:e}){return e?s.jsx(Oe,{justify:"flex-start",gap:"xs",children:e.map(t=>{var n;return t.text&&s.jsx(Ly,{classNames:{cite:Rw.noteCite,root:Rw.noteRoot},cite:((n=t.authorReference)==null?void 0:n.display)||t.authorString,icon:null,children:t.text},`note-${t.text}`)})}):null}function Cl(e){const{value:t,link:n,...r}=e,[o,i]=p.useState(),a=wt(t,i);let l;if(o&&!UP(o))l=`[${De(o)}]`;else if(a)l=Wo(a);else return null;return n?s.jsx(Ge,{to:t,...r,children:l}):s.jsx(fe,{component:"span",...r,children:l})}function Ua(e){return s.jsxs(te,{gap:"xs",children:[s.jsx(Hi,{size:24,radius:12,value:e.value,link:e.link}),s.jsx(Cl,{value:e.value,link:e.link})]})}const MU={draft:"blue",active:"blue","on-hold":"yellow",revoked:"red",completed:"green","entered-in-error":"red",unknown:"gray",retired:"gray",registered:"blue",preliminary:"blue",final:"green",amended:"yellow",corrected:"yellow",cancelled:"red",requested:"blue",received:"blue",accepted:"blue",rejected:"red",ready:"blue","in-progress":"blue",failed:"red",proposed:"blue",pending:"blue",booked:"blue",arrived:"blue",fulfilled:"green",noshow:"red","checked-in":"blue",waitlist:"gray",routine:"gray",urgent:"red",asap:"red",stat:"red","not-done":"red",connected:"green",disconnected:"red"};function n0(e){return s.jsx(ru,{color:MU[e.status],children:e.status})}const OU="_table_pe9td_1",LU="_criticalRow_pe9td_12",$U="_noteBody_pe9td_23",FU="_noteCite_pe9td_27",zU="_noteRoot_pe9td_32",iR={table:OU,criticalRow:LU,noteBody:$U,noteCite:FU,noteRoot:zU};r0.defaultProps={hideObservationNotes:!1,hideSpecimenInfo:!1};function r0(e){var a;const t=se(),n=wt(e.value),[r,o]=p.useState();if(p.useEffect(()=>{n!=null&&n.specimen&&Promise.allSettled(n.specimen.map(l=>t.readReference(l))).then(l=>l.filter(c=>c.status==="fulfilled").map(c=>c.value)).then(o).catch(console.error)},[t,n]),!n)return null;const i=(r==null?void 0:r.flatMap(l=>l.note||[]))||[];if(n.presentedForm&&n.presentedForm.length>0){const l=n.presentedForm[0];(a=l.contentType)!=null&&a.startsWith("text/plain")&&l.data&&i.push({text:window.atob(l.data)})}return s.jsxs(Oe,{children:[s.jsx(ge,{children:"Diagnostic Report"}),s.jsx(BU,{value:n}),r&&!e.hideSpecimenInfo&&UU(r),n.result&&s.jsx(VU,{hideObservationNotes:e.hideObservationNotes,value:n.result}),i.length>0&&s.jsx(oR,{value:i})]})}function BU({value:e}){var t,n;return s.jsxs(te,{mt:"md",gap:30,children:[e.subject&&s.jsxs("div",{children:[s.jsx(fe,{size:"xs",tt:"uppercase",c:"dimmed",children:"Subject"}),s.jsx(Ua,{value:e.subject,link:!0})]}),(t=e.resultsInterpreter)==null?void 0:t.map(r=>s.jsxs("div",{children:[s.jsx(fe,{size:"xs",tt:"uppercase",c:"dimmed",children:"Interpreter"}),s.jsx(Ua,{value:r,link:!0})]},r.reference)),(n=e.performer)==null?void 0:n.map(r=>s.jsxs("div",{children:[s.jsx(fe,{size:"xs",tt:"uppercase",c:"dimmed",children:"Performer"}),s.jsx(Ua,{value:r,link:!0})]},r.reference)),e.issued&&s.jsxs("div",{children:[s.jsx(fe,{size:"xs",tt:"uppercase",c:"dimmed",children:"Issued"}),s.jsx(fe,{children:Fn(e.issued)})]}),e.status&&s.jsxs("div",{children:[s.jsx(fe,{size:"xs",tt:"uppercase",c:"dimmed",children:"Status"}),s.jsx(fe,{children:nn(e.status)})]})]})}function UU(e){return s.jsxs(Oe,{gap:"xs",children:[s.jsx(ge,{order:2,size:"h6",children:"Specimens"}),s.jsx(Ln,{type:"ordered",children:e==null?void 0:e.map(t=>{var n;return s.jsx(Ln.Item,{ml:"sm",children:s.jsxs(te,{gap:20,children:[s.jsxs(te,{gap:5,children:[s.jsx(fe,{fw:500,children:"Collected:"})," ",Fn((n=t.collection)==null?void 0:n.collectedDateTime)]}),s.jsxs(te,{gap:5,children:[s.jsx(fe,{fw:500,children:"Received:"})," ",Fn(t.receivedTime)]})]})},`specimen-${t.id}`)})})]})}function VU(e){return s.jsxs("table",{className:iR.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Test"}),s.jsx("th",{children:"Value"}),s.jsx("th",{children:"Reference Range"}),s.jsx("th",{children:"Interpretation"}),s.jsx("th",{children:"Category"}),s.jsx("th",{children:"Performer"}),s.jsx("th",{children:"Status"})]})}),s.jsx("tbody",{children:s.jsx(sR,{value:e.value,ancestorIds:e.ancestorIds,hideObservationNotes:e.hideObservationNotes})})]})}function sR(e){var t;return s.jsx(s.Fragment,{children:(t=e.value)==null?void 0:t.map(n=>s.jsx(WU,{value:n,ancestorIds:e.ancestorIds,hideObservationNotes:e.hideObservationNotes},`obs-${Qs(n)?n.reference:n.id}`))})}function WU(e){var o,i;const t=wt(e.value);if(!t||(o=e.ancestorIds)!=null&&o.includes(t.id))return null;const n=!e.hideObservationNotes&&t.note,r=GU(t);return s.jsxs(s.Fragment,{children:[s.jsxs("tr",{className:rt({[iR.criticalRow]:r}),children:[s.jsx("td",{rowSpan:n?2:1,children:s.jsx(Ge,{to:t,children:s.jsx(yo,{value:t.code})})}),s.jsx("td",{children:s.jsx(HU,{value:t})}),s.jsx("td",{children:s.jsx(qU,{value:t.referenceRange})}),s.jsx("td",{children:t.interpretation&&t.interpretation.length>0&&s.jsx(yo,{value:t.interpretation[0]})}),s.jsx("td",{children:t.category&&t.category.length>0&&s.jsx(s.Fragment,{children:t.category.map(a=>s.jsx("div",{children:s.jsx(yo,{value:a})},`category-${Oi(a)}`))})}),s.jsx("td",{children:(i=t.performer)==null?void 0:i.map(a=>s.jsx(bf,{value:a},a.reference))}),s.jsx("td",{children:t.status&&s.jsx(n0,{status:t.status})})]}),t.hasMember&&s.jsx(sR,{value:t.hasMember,ancestorIds:e.ancestorIds?[...e.ancestorIds,t.id]:[t.id],hideObservationNotes:e.hideObservationNotes}),n&&s.jsx("tr",{children:s.jsx("td",{colSpan:6,children:s.jsx(oR,{value:t.note})})})]})}function HU(e){const t=e.value;return s.jsx(s.Fragment,{children:ak(t)})}function qU(e){const t=e.value&&e.value.length>0&&e.value[0];return t?t.text?s.jsx(s.Fragment,{children:t.text}):s.jsx(Jx,{value:t}):null}function GU(e){var n,r,o,i;const t=(i=(o=(r=(n=e.interpretation)==null?void 0:n[0])==null?void 0:r.coding)==null?void 0:o[0])==null?void 0:i.code;return t==="AA"||t==="LL"||t==="HH"||t==="A"}const QU="_paper_1igaj_1",KU="_fill_1igaj_20",_w={paper:QU,fill:KU};function o0(e){const{width:t,fill:n,className:r,children:o,...i}=e,a=t?{maxWidth:t}:void 0;return s.jsx(Yn,{className:rt(_w.paper,n&&_w.fill,r),style:a,shadow:"sm",radius:"sm",withBorder:!0,...i,children:o})}var i0={},xu={};Object.defineProperty(xu,"__esModule",{value:!0});xu.Pointer=void 0;function YU(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function XU(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var JU=function(){function e(t){t===void 0&&(t=[""]),this.tokens=t}return e.fromJSON=function(t){var n=t.split("/").map(YU);if(n[0]!=="")throw new Error("Invalid JSON Pointer: ".concat(t));return new e(n)},e.prototype.toString=function(){return this.tokens.map(XU).join("/")},e.prototype.evaluate=function(t){for(var n=null,r="",o=t,i=1,a=this.tokens.length;i<a;i++)n=o,r=this.tokens[i],!(r=="__proto__"||r=="constructor"||r=="prototype")&&(o=(n||{})[r]);return{parent:n,key:r,value:o}},e.prototype.get=function(t){return this.evaluate(t).value},e.prototype.set=function(t,n){var r=this.evaluate(t);r.parent&&(r.parent[r.key]=n)},e.prototype.push=function(t){this.tokens.push(t)},e.prototype.add=function(t){var n=this.tokens.concat(String(t));return new e(n)},e}();xu.Pointer=JU;var Ht={},s0={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.clone=e.objectType=e.hasOwnProperty=void 0,e.hasOwnProperty=Object.prototype.hasOwnProperty;function t(o){return o===void 0?"undefined":o===null?"null":Array.isArray(o)?"array":typeof o}e.objectType=t;function n(o){return o!=null&&typeof o=="object"}function r(o){if(!n(o))return o;if(o.constructor==Array){for(var i=o.length,a=new Array(i),l=0;l<i;l++)a[l]=r(o[l]);return a}if(o.constructor==Date){var c=new Date(+o);return c}var u={};for(var d in o)e.hasOwnProperty.call(o,d)&&(u[d]=r(o[d]));return u}e.clone=r})(s0);var On={};Object.defineProperty(On,"__esModule",{value:!0});On.diffAny=On.diffObjects=On.diffArrays=On.intersection=On.subtract=On.isDestructive=void 0;var Fc=s0;function ZU(e){var t=e.op;return t==="remove"||t==="replace"||t==="copy"||t==="move"}On.isDestructive=ZU;function kg(e,t){var n={};for(var r in e)Fc.hasOwnProperty.call(e,r)&&e[r]!==void 0&&(n[r]=1);for(var o in t)Fc.hasOwnProperty.call(t,o)&&t[o]!==void 0&&delete n[o];return Object.keys(n)}On.subtract=kg;function aR(e){for(var t=e.length,n={},r=0;r<t;r++){var o=e[r];for(var i in o)Fc.hasOwnProperty.call(o,i)&&o[i]!==void 0&&(n[i]=(n[i]||0)+1)}for(var i in n)n[i]<t&&delete n[i];return Object.keys(n)}On.intersection=aR;function eV(e){return e.op==="add"}function tV(e){return e.op==="remove"}function Qp(e,t){return{operations:e.operations.concat(t),cost:e.cost+1}}function lR(e,t,n,r){r===void 0&&(r=Bh);var o={"0,0":{operations:[],cost:0}};function i(d,f){var h="".concat(d,",").concat(f),m=o[h];if(m===void 0){if(d>0&&f>0&&!r(e[d-1],t[f-1],n.add(String(d-1))).length)m=i(d-1,f-1);else{var g=[];if(d>0){var v=i(d-1,f),S={op:"remove",index:d-1};g.push(Qp(v,S))}if(f>0){var y=i(d,f-1),w={op:"add",index:d-1,value:t[f-1]};g.push(Qp(y,w))}if(d>0&&f>0){var b=i(d-1,f-1),x={op:"replace",index:d-1,original:e[d-1],value:t[f-1]};g.push(Qp(b,x))}var C=g.sort(function(j,T){return j.cost-T.cost})[0];m=C}o[h]=m}return m}var a=isNaN(e.length)||e.length<=0?0:e.length,l=isNaN(t.length)||t.length<=0?0:t.length,c=i(a,l).operations,u=c.reduce(function(d,f){var h=d[0],m=d[1];if(eV(f)){var g=f.index+1+m,v=g<a+m?String(g):"-",S={op:f.op,path:n.add(v).toString(),value:f.value};return[h.concat(S),m+1]}else if(tV(f)){var S={op:f.op,path:n.add(String(f.index+m)).toString()};return[h.concat(S),m-1]}else{var y=n.add(String(f.index+m)),w=r(f.original,f.value,y);return[h.concat.apply(h,w),m]}},[[],0])[0];return u}On.diffArrays=lR;function cR(e,t,n,r){r===void 0&&(r=Bh);var o=[];return kg(e,t).forEach(function(i){o.push({op:"remove",path:n.add(i).toString()})}),kg(t,e).forEach(function(i){o.push({op:"add",path:n.add(i).toString(),value:t[i]})}),aR([e,t]).forEach(function(i){o.push.apply(o,r(e[i],t[i],n.add(i)))}),o}On.diffObjects=cR;function Bh(e,t,n,r){if(r===void 0&&(r=Bh),e===t)return[];var o=(0,Fc.objectType)(e),i=(0,Fc.objectType)(t);return o=="array"&&i=="array"?lR(e,t,n,r):o=="object"&&i=="object"?cR(e,t,n,r):[{op:"replace",path:n.toString(),value:t}]}On.diffAny=Bh;var a0=P0&&P0.__extends||function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(r[i]=o[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(Ht,"__esModule",{value:!0});Ht.apply=Ht.InvalidOperationError=Ht.test=Ht.copy=Ht.move=Ht.replace=Ht.remove=Ht.add=Ht.TestError=Ht.MissingError=void 0;var Ho=xu,l0=s0,nV=On,xo=function(e){a0(t,e);function t(n){var r=e.call(this,"Value required at path: ".concat(n))||this;return r.path=n,r.name="MissingError",r}return t}(Error);Ht.MissingError=xo;var uR=function(e){a0(t,e);function t(n,r){var o=e.call(this,"Test failed: ".concat(n," != ").concat(r))||this;return o.actual=n,o.expected=r,o.name="TestError",o}return t}(Error);Ht.TestError=uR;function c0(e,t,n){if(Array.isArray(e))if(t=="-")e.push(n);else{var r=parseInt(t,10);e.splice(r,0,n)}else e[t]=n}function dR(e,t){if(Array.isArray(e)){var n=parseInt(t,10);e.splice(n,1)}else delete e[t]}function fR(e,t){var n=Ho.Pointer.fromJSON(t.path).evaluate(e);return n.parent===void 0?new xo(t.path):(c0(n.parent,n.key,(0,l0.clone)(t.value)),null)}Ht.add=fR;function hR(e,t){var n=Ho.Pointer.fromJSON(t.path).evaluate(e);return n.value===void 0?new xo(t.path):(dR(n.parent,n.key),null)}Ht.remove=hR;function pR(e,t){var n=Ho.Pointer.fromJSON(t.path).evaluate(e);if(n.parent===null)return new xo(t.path);if(Array.isArray(n.parent)){if(parseInt(n.key,10)>=n.parent.length)return new xo(t.path)}else if(n.value===void 0)return new xo(t.path);return n.parent[n.key]=(0,l0.clone)(t.value),null}Ht.replace=pR;function mR(e,t){var n=Ho.Pointer.fromJSON(t.from).evaluate(e);if(n.value===void 0)return new xo(t.from);var r=Ho.Pointer.fromJSON(t.path).evaluate(e);return r.parent===void 0?new xo(t.path):(dR(n.parent,n.key),c0(r.parent,r.key,n.value),null)}Ht.move=mR;function gR(e,t){var n=Ho.Pointer.fromJSON(t.from).evaluate(e);if(n.value===void 0)return new xo(t.from);var r=Ho.Pointer.fromJSON(t.path).evaluate(e);return r.parent===void 0?new xo(t.path):(c0(r.parent,r.key,(0,l0.clone)(n.value)),null)}Ht.copy=gR;function vR(e,t){var n=Ho.Pointer.fromJSON(t.path).evaluate(e);return(0,nV.diffAny)(n.value,t.value,new Ho.Pointer).length?new uR(n.value,t.value):null}Ht.test=vR;var yR=function(e){a0(t,e);function t(n){var r=e.call(this,"Invalid operation: ".concat(n.op))||this;return r.operation=n,r.name="InvalidOperationError",r}return t}(Error);Ht.InvalidOperationError=yR;function rV(e,t){switch(t.op){case"add":return fR(e,t);case"remove":return hR(e,t);case"replace":return pR(e,t);case"move":return mR(e,t);case"copy":return gR(e,t);case"test":return vR(e,t)}return new yR(t)}Ht.apply=rV;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createTests=e.createPatch=e.applyPatch=e.Pointer=void 0;var t=xu;Object.defineProperty(e,"Pointer",{enumerable:!0,get:function(){return t.Pointer}});var n=Ht,r=On;function o(u,d){return d.map(function(f){return(0,n.apply)(u,f)})}e.applyPatch=o;function i(u){function d(f,h,m){var g=u(f,h,m);return Array.isArray(g)?g:(0,r.diffAny)(f,h,m,d)}return d}function a(u,d,f){var h=new t.Pointer;return(f?i(f):r.diffAny)(u,d,h)}e.createPatch=a;function l(u,d){var f=t.Pointer.fromJSON(d).evaluate(u);if(f!==void 0)return{op:"test",path:d,value:f.value}}function c(u,d){var f=new Array;return d.filter(r.isDestructive).forEach(function(h){var m=l(u,h.path);if(m&&f.push(m),"from"in h){var g=l(u,h.from);g&&f.push(g)}}),f}e.createTests=c})(i0);const oV="_root_w6lfx_1",iV="_removed_w6lfx_16",sV="_added_w6lfx_21",Kp={root:oV,removed:iV,added:sV};function aV(e){const t=se(),{original:n,revised:r}=e,[o,i]=p.useState(!1);p.useEffect(()=>{t.requestSchema(e.original.resourceType).then(()=>i(!0)).catch(console.log)},[t,e.original.resourceType]);const a=p.useMemo(()=>{if(!o)return null;const l=[bo(n)],c=[bo(r)],u=[],d=lV(i0.createPatch(n,r));for(const f of d){const h=f.path,m=cV(h),g=uV(n.resourceType,m),v=f.op==="add"?void 0:Lc(m,l),S=f.op==="remove"?void 0:Lc(m,c);u.push({key:`op-${f.op}-${f.path}`,name:`${nn(f.op)} ${m}`,path:(g==null?void 0:g.path)??n.resourceType+"."+m,property:g,originalValue:Dw(g,v),revisedValue:Dw(g,S)})}return u},[o,n,r]);return a?s.jsxs(de,{className:Kp.root,children:[s.jsx(de.Thead,{children:s.jsxs(de.Tr,{children:[s.jsx(de.Th,{}),s.jsx(de.Th,{children:"Before"}),s.jsx(de.Th,{children:"After"})]})}),s.jsx(de.Tbody,{children:a.map(l=>s.jsxs(de.Tr,{children:[s.jsx(de.Td,{children:l.name}),s.jsx(de.Td,{className:Kp.removed,children:l.originalValue&&s.jsx(Zr,{path:l.path,property:l.property,propertyType:l.originalValue.type,value:l.originalValue.value,ignoreMissingValues:!0})}),s.jsx(de.Td,{className:Kp.added,children:l.revisedValue&&s.jsx(Zr,{path:l.path,property:l.property,propertyType:l.revisedValue.type,value:l.revisedValue.value,ignoreMissingValues:!0})})]},l.key))})]}):null}function lV(e){const t=[];for(const n of e){const{op:r,path:o}=n;if(o.startsWith("/meta/author")||o.startsWith("/meta/compartment")||o.startsWith("/meta/lastUpdated")||o.startsWith("/meta/versionId"))continue;const i=e.filter(l=>l.op===r&&l.path===o).length,a={op:r,path:o};i>1&&(r==="add"||r==="remove")&&/\/[0-9-]+$/.test(o)&&(a.op="replace",a.path=o.replace(/\/[^/]+$/,"")),t.some(l=>l.op===a.op&&l.path===a.path)||t.push(a)}return t}function cV(e){const t=e.split("/").filter(Boolean);let n="";for(let r=0;r<t.length;r++){const o=t[r];o==="-"?n+=".last()":/^\d+$/.test(o)?n+=`[${o}]`:(r>0&&(n+="."),n+=o)}return n.endsWith(".url")&&(n=n.replace(/\.url$/,"")),n}function uV(e,t){var r;const n=wl(e,{resourceType:"SearchParameter",base:[e],code:e+"."+t,expression:e+"."+t});return(r=n==null?void 0:n.elementDefinitions)==null?void 0:r[0]}function Dw(e,t){return t&&{type:Array.isArray(t)?t[0].type:t.type,value:dV(t,!!(e!=null&&e.isArray))}}function dV(e,t){const n=y6(e).flatMap(r=>r.value);return t?n:n[0]}function u0(e){const{profileUrl:t}=e,n=se(),r=n.getAccessPolicy(),o=wt(e.value),[i,a]=p.useState(!1);p.useEffect(()=>{if(o)if(t)n.requestProfileSchema(t,{expandProfile:!0}).then(()=>{yl(t)?a(!0):console.error(`Schema not found for ${t}`)}).catch(c=>{console.error("Error in requestProfileSchema",c)});else{const c=o.resourceType;n.requestSchema(c).then(()=>{a(!0)}).catch(console.error)}},[n,t,o]);const l=p.useMemo(()=>o&&gk(o,Ox.READ,r),[r,o]);return!i||!o?null:s.jsx(wf,{path:o.resourceType,value:{type:o.resourceType,value:e.forceUseInput?e.value:o},profileUrl:t,ignoreMissingValues:e.ignoreMissingValues,accessPolicyResource:l})}const fV="_item_5q6yx_1",hV="_itemPadding_5q6yx_5",Iw={item:fV,itemPadding:hV};function pV(e){return s.jsx(yu,{children:e.children})}function Is(e){var c,u;const{resource:t,profile:n,padding:r,popupMenuItems:o,...i}=e,a=n??((c=t.meta)==null?void 0:c.author),l=e.dateTime??((u=t.meta)==null?void 0:u.lastUpdated);return s.jsxs(o0,{"data-testid":"timeline-item",fill:!0,...i,children:[s.jsxs(te,{justify:"space-between",gap:8,mx:"xs",my:"sm",children:[s.jsx(Hi,{value:a,link:!0,size:"md"}),s.jsxs("div",{style:{flex:1},children:[s.jsx(fe,{size:"sm",children:s.jsx(Cl,{c:"dark",fw:500,value:a,link:!0})}),s.jsxs(fe,{size:"xs",children:[s.jsx(Ge,{c:"dimmed",to:e.resource,children:Fn(l)}),s.jsx(fe,{component:"span",c:"dimmed",mx:8,children:"·"}),s.jsx(Ge,{c:"dimmed",to:e.resource,children:e.resource.resourceType})]})]}),o&&s.jsxs(J,{position:"bottom-end",shadow:"md",width:200,children:[s.jsx(J.Target,{children:s.jsx(tn,{color:"gray",variant:"subtle",radius:"xl","aria-label":`Actions for ${st(e.resource)}`,children:s.jsx(uz,{})})}),o]})]}),s.jsx(Lk,{children:s.jsx("div",{className:rt(Iw.item,{[Iw.itemPadding]:r}),children:e.children})})]})}function xR(e,t){e.sort((n,r)=>{const o=Aw(n,t),i=Aw(r,t);return o>i?1:o<i?-1:Nw(n,t)-Nw(r,t)})}function Aw(e,t){if(!bR(e,t)){const n=e.priority;if(typeof n=="string")return{stat:4,asap:3,urgent:2}[n]??0}return 0}function Nw(e,t){var r;if(!bR(e,t)){if(e.resourceType==="Communication"&&e.sent)return new Date(e.sent).getTime();if((e.resourceType==="DiagnosticReport"||e.resourceType==="Media"||e.resourceType==="Observation")&&e.issued)return new Date(e.issued).getTime();if(e.resourceType==="DocumentReference"&&e.date)return new Date(e.date).getTime()}const n=(r=e.meta)==null?void 0:r.lastUpdated;return n?new Date(n).getTime():0}function bR(e,t){return!!t&&e.resourceType===t.resourceType&&e.id===t.id}const mV="_pinnedComment_5uxzi_2",gV={pinnedComment:mV};function Uh(e){const t=se(),n=t.getProfile(),r=p.useRef(null),o=wt(e.value),[i,a]=p.useState(),[l,c]=p.useState([]),u=e.loadTimelineResources,d=p.useRef(l);d.current=l;const f=p.useCallback(x=>{xR(x,o),x.reverse(),c(x)},[o]),h=p.useCallback(x=>{const C=[];for(const j of x){if(j.status!=="fulfilled")continue;const T=j.value;if(T.type==="history"&&a(T),T.entry)for(const E of T.entry)C.push(E.resource)}f(C)},[f]),m=p.useCallback(x=>f([...d.current,x]),[f]),g=p.useCallback(()=>{var j;let x,C;"resourceType"in e.value?(x=e.value.resourceType,C=e.value.id):[x,C]=(j=e.value.reference)==null?void 0:j.split("/"),u(t,x,C).then(h).catch(console.error)},[t,e.value,u,h]);p.useEffect(()=>g(),[g]);function v(x){!o||!e.createCommunication||t.createResource(e.createCommunication(o,n,x)).then(C=>m(C)).catch(console.error)}function S(x){!o||!e.createMedia||t.createResource(e.createMedia(o,n,x)).then(C=>m(C)).then(()=>Kl({id:"upload-notification",color:"teal",title:"Upload complete",message:"",icon:s.jsx(Ks,{size:16}),autoClose:2e3})).catch(C=>Kl({id:"upload-notification",color:"red",title:"Upload error",message:De(C),icon:s.jsx(ww,{size:16}),autoClose:2e3}))}function y(){he({id:"upload-notification",loading:!0,title:"Initializing upload...",message:"Please wait...",autoClose:!1,withCloseButton:!1})}function w(x){Kl({id:"upload-notification",loading:!0,title:"Uploading...",message:jV(x),autoClose:!1,withCloseButton:!1})}function b(x){Kl({id:"upload-notification",color:"red",title:"Upload error",message:De(x),icon:s.jsx(ww,{size:16}),autoClose:2e3})}return o?s.jsxs(pV,{children:[e.createCommunication&&s.jsx(o0,{children:s.jsx(Ke,{testid:"timeline-form",onSubmit:x=>{v(x.text);const C=r.current;C&&(C.value="",C.focus())},children:s.jsxs(te,{gap:"xs",wrap:"nowrap",style:{width:"100%"},children:[s.jsx(Hi,{value:n}),s.jsx(ve,{name:"text",ref:r,placeholder:"Add comment",style:{width:"100%",maxWidth:300}}),s.jsx(tn,{type:"submit",radius:"xl",color:"blue",variant:"filled",children:s.jsx(yz,{size:16})}),s.jsx(Xx,{securityContext:Et(o),onUpload:S,onUploadStart:y,onUploadProgress:w,onUploadError:b,children:x=>s.jsx(tn,{...x,radius:"xl",color:"blue",variant:"filled",children:s.jsx(Ux,{size:16})})})]})})}),l.map(x=>{var T;if(!x)return null;const C=`${x.resourceType}/${x.id}/${(T=x.meta)==null?void 0:T.versionId}`,j=e.getMenu?e.getMenu({primaryResource:o,currentResource:x,reloadTimeline:g}):void 0;if(x.resourceType===o.resourceType&&x.id===o.id)return s.jsx(vV,{history:i,resource:x,popupMenuItems:j},C);switch(x.resourceType){case"AuditEvent":return s.jsx(wV,{resource:x,popupMenuItems:j},C);case"Communication":return s.jsx(xV,{resource:x,popupMenuItems:j},C);case"DiagnosticReport":return s.jsx(SV,{resource:x,popupMenuItems:j},C);case"Media":return s.jsx(bV,{resource:x,popupMenuItems:j},C);default:return s.jsx(Is,{resource:x,padding:!0,children:s.jsx(u0,{value:x,ignoreMissingValues:!0})},C)}})]}):s.jsx(mn,{style:{width:"100%",height:"100%"},children:s.jsx(Zn,{})})}function vV(e){const{history:t,resource:n,...r}=e,o=yV(t,n);return o?s.jsx(Is,{resource:n,padding:!0,...r,children:s.jsx(aV,{original:o,revised:e.resource})}):s.jsxs(Is,{resource:n,padding:!0,...r,children:[s.jsx("h3",{children:"Created"}),s.jsx(u0,{value:n,ignoreMissingValues:!0,forceUseInput:!0})]})}function yV(e,t){const n=e.entry,r=n.findIndex(o=>{var i,a,l;return((a=(i=o.resource)==null?void 0:i.meta)==null?void 0:a.versionId)===((l=t.meta)==null?void 0:l.versionId)});if(!(r>=n.length-1))return n[r+1].resource}function xV(e){var r,o;const n=!e.resource.priority||e.resource.priority==="routine"?void 0:gV.pinnedComment;return s.jsx(Is,{resource:e.resource,profile:e.resource.sender,dateTime:e.resource.sent,padding:!0,className:n,popupMenuItems:e.popupMenuItems,children:s.jsx("p",{children:(o=(r=e.resource.payload)==null?void 0:r[0])==null?void 0:o.contentString})})}function bV(e){var r;const t=(r=e.resource.content)==null?void 0:r.contentType,n=t&&!t.startsWith("image/")&&!t.startsWith("video/")&&t!=="application/pdf";return s.jsx(Is,{resource:e.resource,padding:!!n,popupMenuItems:e.popupMenuItems,children:s.jsx(mu,{value:e.resource.content})})}function wV(e){return s.jsx(Is,{resource:e.resource,padding:!0,popupMenuItems:e.popupMenuItems,children:s.jsx(Ir,{children:s.jsx("pre",{children:e.resource.outcomeDesc})})})}function SV(e){return s.jsx(Is,{resource:e.resource,padding:!0,popupMenuItems:e.popupMenuItems,children:s.jsx(r0,{value:e.resource})})}function jV(e){if(e.lengthComputable){const t=100*e.loaded/e.total;return`Uploaded: ${Yp(e.loaded)} / ${Yp(e.total)} ${t.toFixed(2)}%`}return`Uploaded: ${Yp(e.loaded)}`}function Yp(e){if(e===0)return"0.00 B";const t=Math.floor(Math.log(e)/Math.log(1024));return(e/Math.pow(1024,t)).toFixed(2)+" "+" KMGTP".charAt(t)+"B"}function CV(e){const{resource:t,...n}=e;return s.jsx(Uh,{value:t,loadTimelineResources:async(r,o,i)=>{const a=`${o}/${i}`;return Promise.allSettled([r.readHistory(o,i),r.search("Task",{_filter:`based-on eq ${a} or focus eq ${a} or subject eq ${a}`,_count:100})])},...n})}function Ne(e){const{children:t,...n}=e;return s.jsx(yu,{children:s.jsx(o0,{...n,children:t})})}function EV(e){const{encounter:t,...n}=e;return s.jsx(Uh,{value:t,loadTimelineResources:async(r,o,i)=>Promise.allSettled([r.readHistory("Encounter",i),r.search("Communication","encounter=Encounter/"+i),r.search("Media","encounter=Encounter/"+i)]),createCommunication:(r,o,i)=>({resourceType:"Communication",status:"completed",encounter:Et(r),subject:r.subject,sender:Et(o),sent:new Date().toISOString(),payload:[{contentString:i}]}),createMedia:(r,o,i)=>({resourceType:"Media",status:"completed",encounter:Et(r),subject:r.subject,operator:Et(o),issued:new Date().toISOString(),content:i}),...n})}function TV(e){let t;try{t=bl(e.path,e.resource)}catch(n){return console.warn("FhirPathDisplay:",n),null}if(t.length>1)throw new Error(`Component "path" for "FhirPathDisplay" must resolve to a single element. Received ${t.length} elements [${JSON.stringify(t,null,2)}]`);return s.jsx(Zr,{value:t[0]||"",propertyType:e.propertyType})}function Mr(e){var n;const t=((n=e.outcome)==null?void 0:n.issue)||e.issues;return!t||t.length===0?null:s.jsx(Vi,{icon:s.jsx(Sl,{size:16}),color:"red",children:t.map(r=>{var o;return s.jsx("div",{"data-testid":"text-field-error",children:WP(r)},(o=r.details)==null?void 0:o.text)})})}function PV(e){return s.jsxs(wn,{title:"Export",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:e.onCancel,children:[s.jsxs(q,{display:"flex",style:{justifyContent:"space-between"},children:[e.exportCsv&&s.jsx(Mw,{text:"CSV",exportLogic:e.exportCsv,onCancel:e.onCancel}),e.exportTransactionBundle&&s.jsx(Mw,{text:"Transaction Bundle",exportLogic:e.exportTransactionBundle,onCancel:e.onCancel})]}),s.jsx(fe,{style:{marginTop:"10px",marginLeft:"2px"},children:"Limited to 1000 records"})]})}function Mw(e){return s.jsx(oe,{onClick:()=>{e.exportLogic(),e.onCancel()},children:`Export as ${e.text}`})}const kV={string:[re.EQUALS,re.NOT,re.CONTAINS,re.EXACT],fulltext:[re.EQUALS,re.NOT,re.CONTAINS,re.EXACT],token:[re.EQUALS,re.NOT],reference:[re.EQUALS,re.NOT],numeric:[re.EQUALS,re.NOT_EQUALS,re.GREATER_THAN,re.LESS_THAN,re.GREATER_THAN_OR_EQUALS,re.LESS_THAN_OR_EQUALS],quantity:[re.EQUALS,re.NOT_EQUALS,re.GREATER_THAN,re.LESS_THAN,re.GREATER_THAN_OR_EQUALS,re.LESS_THAN_OR_EQUALS],date:[re.EQUALS,re.NOT_EQUALS,re.GREATER_THAN,re.LESS_THAN,re.GREATER_THAN_OR_EQUALS,re.LESS_THAN_OR_EQUALS,re.STARTS_AFTER,re.ENDS_BEFORE,re.APPROXIMATELY],datetime:[re.EQUALS,re.NOT_EQUALS,re.GREATER_THAN,re.LESS_THAN,re.GREATER_THAN_OR_EQUALS,re.LESS_THAN_OR_EQUALS,re.STARTS_AFTER,re.ENDS_BEFORE,re.APPROXIMATELY]},RV={eq:"equals",ne:"not equals",gt:"greater than",lt:"less than",ge:"greater than or equals",le:"less than or equals",sa:"starts after",eb:"ends before",ap:"approximately",contains:"contains",exact:"exact",text:"text",not:"not",above:"above",below:"below",in:"in","not-in":"not in","of-type":"of type",missing:"missing",present:"present",identifier:"identifier",iterate:"iterate"};function d0(e,t){return{...e,filters:t,offset:0,name:void 0}}function wR(e,t){return d0(e,(e.filters??[]).filter(n=>n.code!==t))}function Vh(e,t,n,r,o){const i=[];return e.filters&&i.push(...e.filters),i.push({code:t,operator:n,value:r??""}),d0(e,i)}function _V(e,t){if(!e.filters)return e;const n=[...e.filters];return n.splice(t,1),{...e,filters:n,name:void 0}}function DV(e,t){return f0(e,t,-1)}function IV(e,t){return f0(e,t,0)}function AV(e,t){return f0(e,t,1)}function f0(e,t,n){const r=new Date;r.setDate(r.getDate()+n),r.setHours(0,0,0,0);const o=new Date(r.getTime());return o.setDate(o.getDate()+1),o.setTime(o.getTime()-1),p0(e,t,r,o)}function NV(e,t){return h0(e,t,-1)}function MV(e,t){return h0(e,t,0)}function OV(e,t){return h0(e,t,1)}function h0(e,t,n){const r=new Date;r.setMonth(r.getMonth()+n),r.setDate(1),r.setHours(0,0,0,0);const o=new Date(r.getTime());return o.setMonth(o.getMonth()+1),o.setDate(1),o.setHours(0,0,0,0),o.setTime(o.getTime()-1),p0(e,t,r,o)}function LV(e,t){const n=new Date;return n.setMonth(0),n.setDate(1),n.setHours(0,0,0,0),p0(e,t,n,new Date)}function p0(e,t,n,r){return e=wR(e,t),e=Ow(e,t,re.GREATER_THAN_OR_EQUALS,n),e=Ow(e,t,re.LESS_THAN_OR_EQUALS,r),e}function Ow(e,t,n,r){return Vh(e,t,n,r.toISOString())}function Lw(e,t,n=!0){return Vh(e,t,re.MISSING,n.toString())}function $V(e,t){return e.offset===t?e:{...e,offset:t,name:void 0}}function FV(e,t){const n=e.count??Ah,r=(t-1)*n;return $V(e,r)}function zV(e,t,n){return t===BV(e)&&n!==void 0&&n===UV(e)?e:{...e,sortRules:[{code:t,descending:!!n}],name:void 0}}function BV(e){const t=e.sortRules;if(!t||t.length===0)return;const n=t[0].code;return n.startsWith("-")?n.substr(1):n}function UV(e){const t=e.sortRules;return!t||t.length===0?!1:!!t[0].descending}function VV(e){return kV[e.type]}function m0(e){return RV[e]??""}function Li(e){let t=e;return t.includes(".")&&(t=t.split(".").pop()),t==="versionId"?"Version ID":(t=t.replace("[x]",""),t=t.replace(/([A-Z])/g," $1"),t=t.replace(/[-_]/g," "),t=t.replace(/\s+/g," "),t=t.trim(),t.toLowerCase()==="id"?"ID":t.split(/\s/).map(nn).join(" "))}function WV(e,t){var r,o;const n=t.name;return n==="id"?e.id:n==="meta.versionId"?(r=e.meta)==null?void 0:r.versionId:n==="_lastUpdated"?Fn((o=e.meta)==null?void 0:o.lastUpdated):t.elementDefinition&&`${e.resourceType}.${t.name}`===t.elementDefinition.path?HV(e,t.elementDefinition):t.searchParams&&t.searchParams.length===1&&t.name===t.searchParams[0].code?qV(e,t.searchParams[0]):null}function HV(e,t){var i,a,l;const n=((l=(a=(i=t.path)==null?void 0:i.split("."))==null?void 0:a.pop())==null?void 0:l.replaceAll("[x]",""))??"",[r,o]=gu({type:e.resourceType,value:e},n);return r?s.jsx(Zr,{path:t.path,property:t,propertyType:o,value:r,maxWidth:200,ignoreMissingValues:!0,link:!1}):null}function qV(e,t){const n=Lc(t.expression,[{type:e.resourceType,value:e}]);return!n||n.length===0?null:s.jsx(s.Fragment,{children:n.map((r,o)=>s.jsx(Zr,{propertyType:r.type,value:r.value,maxWidth:200,ignoreMissingValues:!0,link:!1},`${o}-${n.length}`))})}function GV(e){const t=p.useRef(!1),[n,r]=p.useState({search:JSON.parse(pr(e.search))}),[o,i]=p.useState(!1);p.useEffect(()=>{r({search:e.search})},[e.search]);const a=p.useMemo(()=>{if(!e.visible)return[];const c=e.search.resourceType,u=QP(c),d=kx(c);return Nc(QV(u,d)).map(f=>({value:f,label:Li(f)}))},[e.visible,e.search.resourceType]);if(!e.visible)return null;function l(c){r({search:{...n.search,fields:c}})}return s.jsx(wn,{title:"Fields",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:()=>{e.onCancel()},size:"auto",withOverlay:!0,closeOnClickOutside:!1,overlayProps:{onMouseDownCapture:()=>{t.current=o},onClick:()=>{t.current||e.onCancel(),t.current=!1},children:s.jsx("div",{"data-testid":"overlay-child"})},children:s.jsxs(Oe,{children:[s.jsx(wh,{style:{width:550},placeholder:"Select fields to display",data:a,value:n.search.fields??[],onChange:l,onDropdownOpen:()=>i(!0),onDropdownClose:()=>i(!1),maxDropdownHeight:"250px",clearButtonProps:{"aria-label":"Clear selection"},clearable:!0,searchable:!0}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{onClick:()=>e.onOk(n.search),children:"OK"})})]})})}function QV(e,t){const n=[],r=new Set,o=new Set;for(const i of Object.keys(e.elements))n.push(i),r.add(i.toLowerCase()),o.add(Li(i));if(t)for(const i of Object.keys(t)){const a=Li(i);!r.has(i)&&!o.has(a)&&(n.push(i),r.add(i),o.add(a))}return n}function SR(e){var o;const{resourceType:t,filter:n}=e,r=(o=wo.types[t].searchParams)==null?void 0:o[n.code];if(r){if(r.type==="reference"&&(n.operator===re.EQUALS||n.operator===re.NOT_EQUALS))return s.jsx(Cl,{value:{reference:n.value}});const i=wl(t,r);if(n.code==="_lastUpdated"||i.type===ko.DATETIME)return s.jsx(s.Fragment,{children:Fn(n.value)})}return s.jsx(s.Fragment,{children:n.value})}function jR(e){const t=wl(e.resourceType,e.searchParam),n="filter-value";switch(t.type){case ko.REFERENCE:return s.jsx(zh,{name:n,defaultValue:e.defaultValue?{reference:e.defaultValue}:void 0,targetTypes:e.searchParam.target,autoFocus:e.autoFocus,onChange:r=>{r?e.onChange(r.reference):e.onChange("")}});case ko.BOOLEAN:return s.jsx(_n,{name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultChecked:e.defaultValue==="true",autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.checked.toString())});case ko.DATE:return s.jsx(ve,{type:"date",name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value)});case ko.DATETIME:return s.jsx(_s,{name:n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:e.onChange});case ko.NUMBER:return s.jsx(ve,{type:"number",name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value)});case ko.QUANTITY:return s.jsx(Ds,{name:n,path:"",defaultValue:KV(e.defaultValue),autoFocus:e.autoFocus,onChange:r=>{r?e.onChange(`${r.value}`):e.onChange("")}});default:return s.jsx(ve,{name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value),placeholder:"Search value"})}}function KV(e){if(e){const[t,n,r]=e.split("|");if(t)return{value:parseFloat(t),system:n,unit:r}}}function YV(e){const[t,n]=p.useState(JSON.parse(pr(e.search))),[r,o]=p.useState(-1),i=p.useRef(t);i.current=t,p.useEffect(()=>{n(JSON.parse(pr(e.search)))},[e.search]);function a(d){n(Vh(i.current,d.code,d.operator,d.value))}if(!e.visible)return null;const l=e.search.resourceType,c=kx(l)??{},u=t.filters||[];return s.jsxs(wn,{title:"Filters",closeButtonProps:{"aria-label":"Close"},size:900,opened:e.visible,onClose:e.onCancel,children:[s.jsx("div",{children:s.jsxs("table",{children:[s.jsxs("colgroup",{children:[s.jsx("col",{style:{width:200}}),s.jsx("col",{style:{width:200}}),s.jsx("col",{style:{width:380}}),s.jsx("col",{style:{width:120}})]}),s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Field"}),s.jsx("th",{children:"Operation"}),s.jsx("th",{children:"Value"}),s.jsx("th",{children:"Actions"})]})}),s.jsxs("tbody",{children:[u.map((d,f)=>f===r?s.jsx($w,{resourceType:l,searchParams:c,defaultValue:d,okText:"Save",onOk:h=>{const m=[...u];m[f]=h,n(d0(i.current,m)),o(-1)},onCancel:()=>o(-1)},`filter-${d.code}-${d.operator}-${d.value}-input`):s.jsx(XV,{resourceType:l,filter:d,onEdit:()=>o(f),onDelete:()=>n(_V(i.current,f))},`filter-${d.code}-${d.operator}-${d.value}-display`)),s.jsx($w,{resourceType:l,searchParams:c,okText:"Add",onOk:a})]})]})}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{onClick:()=>e.onOk(i.current),children:"OK"})})]})}function XV(e){const{filter:t}=e;return s.jsxs("tr",{children:[s.jsx("td",{children:Li(t.code)}),s.jsx("td",{children:m0(t.operator)}),s.jsx("td",{children:s.jsx(SR,{resourceType:e.resourceType,filter:t})}),s.jsxs("td",{children:[s.jsx(oe,{size:"compact-md",variant:"outline",onClick:e.onEdit,children:"Edit"}),s.jsx(oe,{size:"compact-md",variant:"outline",onClick:e.onDelete,children:"Delete"})]})]})}function $w(e){const[t,n]=p.useState(e.defaultValue??{}),r=p.useRef(t);r.current=t;function o(u){n({...r.current,code:u})}function i(u){n({...r.current,operator:u})}function a(u){n({...r.current,value:u})}const l=e.searchParams[t.code],c=l&&VV(l);return s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(It,{"data-testid":"filter-field",defaultValue:r.current.code,onChange:u=>o(u.currentTarget.value),data:["",...Object.keys(e.searchParams).map(u=>({value:u,label:Li(u)}))]})}),s.jsx("td",{children:c&&s.jsx(It,{"data-testid":"filter-operation",defaultValue:t.operator,onChange:u=>i(u.currentTarget.value),data:["",...c.map(u=>({value:u,label:m0(u)}))]})}),s.jsx("td",{children:l&&t.operator&&s.jsx(jR,{resourceType:e.resourceType,searchParam:l,defaultValue:t.value,onChange:a})}),s.jsxs("td",{children:[t.code&&t.operator&&s.jsx(oe,{size:"compact-md",variant:"outline",onClick:()=>{e.onOk(r.current),n({})},children:e.okText}),e.onCancel&&s.jsx(oe,{size:"compact-md",variant:"outline",onClick:e.onCancel,children:"Cancel"})]})]})}function JV(e){const[t,n]=p.useState(e.defaultValue??"");if(!e.visible||!e.searchParam||!e.filter)return null;function r(){e.onOk({...e.filter,value:t})}return s.jsx(wn,{title:e.title,size:"xl",opened:e.visible,onClose:e.onCancel,children:s.jsx(Ke,{onSubmit:r,children:s.jsxs(ur,{children:[s.jsx(ur.Col,{span:10,children:s.jsx(jR,{resourceType:e.resourceType,searchParam:e.searchParam,defaultValue:t,autoFocus:!0,onChange:n})}),s.jsx(ur.Col,{span:2,children:s.jsx(oe,{onClick:r,fullWidth:!0,children:"OK"})})]})})})}function ZV(e){if(!e.searchParams)return null;function t(i,a){o(zV(e.search,i.code,a))}function n(i){o(wR(e.search,i.code))}function r(i,a){e.onPrompt(i,{code:i.code,operator:a,value:""})}function o(i){e.onChange(i)}return e.searchParams.length===1?s.jsx(eW,{search:e.search,searchParam:e.searchParams[0],onSort:t,onPrompt:r,onChange:o,onClear:n}):s.jsx(J.Dropdown,{children:e.searchParams.map(i=>s.jsx(J.Item,{children:Li(i.code)},i.code))})}function eW(e){switch(e.searchParam.type){case"date":return s.jsx(tW,{...e});case"number":case"quantity":return s.jsx(nW,{...e});case"reference":return s.jsx(rW,{...e});case"string":return s.jsx(oW,{...e});case"token":case"uri":return s.jsx(iW,{...e});default:return s.jsxs(s.Fragment,{children:["Unknown search param type: ",e.searchParam.type]})}}function tW(e){const{searchParam:t}=e,n=t.code;return s.jsxs(J.Dropdown,{children:[s.jsx(J.Item,{leftSection:s.jsx(Vx,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort Oldest to Newest"}),s.jsx(J.Item,{leftSection:s.jsx(Wx,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Newest to Oldest"}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(pu,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Equals..."}),s.jsx(J.Item,{leftSection:s.jsx(hu,{size:14}),onClick:()=>e.onPrompt(t,re.NOT_EQUALS),children:"Does not equal..."}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(Ok,{size:14}),onClick:()=>e.onPrompt(t,re.ENDS_BEFORE),children:"Before..."}),s.jsx(J.Item,{leftSection:s.jsx(Mk,{size:14}),onClick:()=>e.onPrompt(t,re.STARTS_AFTER),children:"After..."}),s.jsx(J.Item,{leftSection:s.jsx(tz,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Between..."}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(AV(e.search,n)),children:"Tomorrow"}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(IV(e.search,n)),children:"Today"}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(DV(e.search,n)),children:"Yesterday"}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(OV(e.search,n)),children:"Next Month"}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(MV(e.search,n)),children:"This Month"}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(NV(e.search,n)),children:"Last Month"}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(LV(e.search,n)),children:"Year to date"}),s.jsx(bu,{...e})]})}function nW(e){const{searchParam:t}=e;return s.jsxs(J.Dropdown,{children:[s.jsx(J.Item,{leftSection:s.jsx(Vx,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort Smallest to Largest"}),s.jsx(J.Item,{leftSection:s.jsx(Wx,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Largest to Smallest"}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(pu,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Equals..."}),s.jsx(J.Item,{leftSection:s.jsx(hu,{size:14}),onClick:()=>e.onPrompt(t,re.NOT_EQUALS),children:"Does not equal..."}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(Mk,{size:14}),onClick:()=>e.onPrompt(t,re.GREATER_THAN),children:"Greater than..."}),s.jsx(J.Item,{leftSection:s.jsx(Tg,{size:14}),onClick:()=>e.onPrompt(t,re.GREATER_THAN_OR_EQUALS),children:"Greater than or equal to..."}),s.jsx(J.Item,{leftSection:s.jsx(Ok,{size:14}),onClick:()=>e.onPrompt(t,re.LESS_THAN),children:"Less than..."}),s.jsx(J.Item,{leftSection:s.jsx(Tg,{size:14}),onClick:()=>e.onPrompt(t,re.LESS_THAN_OR_EQUALS),children:"Less than or equal to..."}),s.jsx(bu,{...e})]})}function rW(e){const{searchParam:t}=e;return s.jsxs(J.Dropdown,{children:[s.jsx(J.Item,{leftSection:s.jsx(pu,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Equals..."}),s.jsx(J.Item,{leftSection:s.jsx(hu,{size:14}),onClick:()=>e.onPrompt(t,re.NOT),children:"Does not equal..."}),s.jsx(bu,{...e})]})}function oW(e){const{searchParam:t}=e;return s.jsxs(J.Dropdown,{children:[s.jsx(J.Item,{leftSection:s.jsx(Vx,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort A to Z"}),s.jsx(J.Item,{leftSection:s.jsx(Wx,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Z to A"}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(pu,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Equals..."}),s.jsx(J.Item,{leftSection:s.jsx(hu,{size:14}),onClick:()=>e.onPrompt(t,re.NOT),children:"Does not equal..."}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(oz,{size:14}),onClick:()=>e.onPrompt(t,re.CONTAINS),children:"Contains..."}),s.jsx(J.Item,{leftSection:s.jsx(rz,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Does not contain..."}),s.jsx(bu,{...e})]})}function iW(e){const{searchParam:t}=e;return s.jsxs(J.Dropdown,{children:[s.jsx(J.Item,{leftSection:s.jsx(pu,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Equals..."}),s.jsx(J.Item,{leftSection:s.jsx(hu,{size:14}),onClick:()=>e.onPrompt(t,re.NOT),children:"Does not equal..."}),s.jsx(bu,{...e})]})}function bu(e){const{searchParam:t}=e,n=t.code;return s.jsxs(s.Fragment,{children:[s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(Z8,{size:14}),onClick:()=>e.onChange(Lw(e.search,n)),children:"Missing"}),s.jsx(J.Item,{leftSection:s.jsx(J8,{size:14}),onClick:()=>e.onChange(Lw(e.search,n,!1)),children:"Not missing"}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(xf,{size:14}),onClick:()=>e.onClear(t),children:"Clear filters"})]})}const sW="_root_vlout_1",aW="_table_vlout_8",lW="_tr_vlout_12",cW="_th_vlout_18",uW="_control_vlout_22",dW="_icon_vlout_31",Bl={root:sW,table:aW,tr:lW,th:cW,control:uW,icon:dW};function fW(e){const t=e.resourceType,n=[];for(const r of e.fields||["id","_lastUpdated"])n.push(hW(t,r));return n}function hW(e,t){var o;if(t==="_lastUpdated")return{name:"_lastUpdated",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_lastUpdated",name:"_lastUpdated",type:"date",expression:"Resource.meta.lastUpdated"}]};if(t==="meta.versionId")return{name:"meta.versionId",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_versionId",name:"_versionId",type:"token",expression:"Resource.meta.versionId"}]};const n=Gs(e,t),r=O6(e,t.toLowerCase());if(n&&r)return{name:t,elementDefinition:n,searchParams:[r]};if(n){const i=kx(e);let a;if(i){const l=new RegExp(`${e}\\.${t.replaceAll("[x]","")}([^\\w-]|$)`);a=Object.values(i).filter(c=>!!c.expression&&l.test(c==null?void 0:c.expression)),a.length===0&&(a=void 0)}return{name:t,elementDefinition:n,searchParams:a}}if(r){const i=wl(e,r);return{name:t,elementDefinition:(o=i.elementDefinitions)==null?void 0:o[0],searchParams:[r]}}return{name:t}}class pW extends Event{constructor(t){super("change"),this.definition=t}}class mW extends Event{constructor(t){super("load"),this.response=t}}class Sf extends Event{constructor(t,n){super("click"),this.resource=t,this.browserEvent=n}}function wu(e){var N,F,D;const t=se(),[n,r]=p.useState(),{search:o,onLoad:i}=e,[a,l]=p.useState(o);Mi(o,a)||l(o);const[c,u]=p.useState({selected:{},fieldEditorVisible:!1,filterEditorVisible:!1,exportDialogVisible:!1,filterDialogVisible:!1}),d=p.useRef(c);d.current=c;const f=a.total??"accurate",h=p.useCallback(R=>{r(void 0),t.requestSchema(a.resourceType).then(()=>t.search(a.resourceType,Ra({...a,total:f,fields:void 0}),R)).then(P=>{u({...d.current,searchResponse:P}),i&&i(new mW(P))}).catch(P=>{u({...d.current,searchResponse:void 0}),r(ht(P))})},[t,a,f,i]),m=p.useCallback(()=>{u({...d.current,searchResponse:void 0}),h({cache:"reload"})},[h]);p.useEffect(()=>{h()},[h]);function g(R,P){R.stopPropagation();const L=R.target.checked,V={...d.current.selected};L?V[P]=!0:delete V[P],u({...d.current,selected:V})}function v(R){R.stopPropagation();const $=R.target.checked,L={},V=d.current.searchResponse;$&&(V!=null&&V.entry)&&V.entry.forEach(K=>{var ie;(ie=K.resource)!=null&&ie.id&&(L[K.resource.id]=!0)}),u({...d.current,selected:L})}function S(){var P,$;const R=d.current;if(!((P=R.searchResponse)!=null&&P.entry)||R.searchResponse.entry.length===0)return!1;for(const L of R.searchResponse.entry)if(($=L.resource)!=null&&$.id&&!R.selected[L.resource.id])return!1;return!0}function y(R){e.onChange&&e.onChange(new pW(R))}function w(R,P){if($k(R.target)||R.button===2)return;yt(R);const $=R.button===1||R.ctrlKey||R.metaKey;!$&&e.onClick&&e.onClick(new Sf(P,R)),$&&e.onAuxClick&&e.onAuxClick(new Sf(P,R))}function b(){return!!(e.onExport??e.onExportCsv??e.onExportTransactionBundle)}if(n)return s.jsx(Mr,{outcome:n});if(!GP(a.resourceType))return s.jsx(mn,{style:{width:"100%",height:"100%"},children:s.jsx(Zn,{})});const x=e.checkboxesEnabled,C=fW(a),j=a.resourceType,T=c.searchResponse,E=T==null?void 0:T.entry,_=E==null?void 0:E.map(R=>R.resource),k="subtle",A="gray",O=16,U=window.innerWidth<768;return s.jsxs("div",{className:Bl.root,"data-testid":"search-control",children:[!e.hideToolbar&&s.jsxs(te,{justify:"space-between",mb:"xl",children:[s.jsxs(te,{gap:2,children:[s.jsx(oe,{size:"compact-md",variant:k,color:A,leftSection:s.jsx(az,{size:O}),onClick:()=>u({...d.current,fieldEditorVisible:!0}),children:"Fields"}),s.jsx(oe,{size:"compact-md",variant:k,color:A,leftSection:s.jsx(fz,{size:O}),onClick:()=>u({...d.current,filterEditorVisible:!0}),children:"Filters"}),e.onNew&&s.jsx(oe,{size:"compact-md",variant:k,color:A,leftSection:s.jsx(dz,{size:O}),onClick:e.onNew,children:"New..."}),!U&&b()&&s.jsx(oe,{size:"compact-md",variant:k,color:A,leftSection:s.jsx(Nz,{size:O}),onClick:e.onExport?e.onExport:()=>u({...d.current,exportDialogVisible:!0}),children:"Export..."}),!U&&e.onDelete&&s.jsx(oe,{size:"compact-md",variant:k,color:A,leftSection:s.jsx(Hx,{size:O}),onClick:()=>e.onDelete(Object.keys(c.selected)),children:"Delete..."}),!U&&e.onBulk&&s.jsx(oe,{size:"compact-md",variant:k,color:A,leftSection:s.jsx(ez,{size:O}),onClick:()=>e.onBulk(Object.keys(c.selected)),children:"Bulk..."})]}),s.jsxs(te,{gap:2,children:[T&&s.jsxs(fe,{size:"xs",c:"dimmed","data-testid":"count-display",children:[CR(a,T).toLocaleString(),"-",bW(a,T).toLocaleString(),T.total!==void 0&&` of ${a.total==="estimate"?"~":""}${(N=T.total)==null?void 0:N.toLocaleString()}`]}),s.jsx(tn,{variant:k,color:A,title:"Refresh",onClick:m,children:s.jsx(Tz,{size:O})})]})]}),s.jsxs(de,{className:Bl.table,children:[s.jsxs(de.Thead,{children:[s.jsxs(de.Tr,{children:[x&&s.jsx(de.Th,{children:s.jsx("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:S(),onChange:R=>v(R)})}),C.map(R=>s.jsx(de.Th,{children:s.jsxs(J,{shadow:"md",width:240,position:"bottom-end",children:[s.jsx(J.Target,{children:s.jsx(bn,{className:Bl.control,p:2,children:s.jsxs(te,{justify:"space-between",wrap:"nowrap",children:[s.jsx(fe,{fw:500,children:Li(R.name)}),s.jsx(mn,{className:Bl.icon,children:s.jsx(K8,{size:14,stroke:1.5})})]})})}),s.jsx(ZV,{search:a,searchParams:R.searchParams,onPrompt:(P,$)=>{u({...d.current,filterDialogVisible:!0,filterDialogSearchParam:P,filterDialogFilter:$})},onChange:P=>{y(P)}})]})},R.name))]}),!e.hideFilters&&s.jsxs(de.Tr,{children:[x&&s.jsx(de.Th,{}),C.map(R=>s.jsx(de.Th,{children:R.searchParams&&s.jsx(vW,{resourceType:j,searchParams:R.searchParams,filters:a.filters})},R.name))]})]}),s.jsx(de.Tbody,{children:_==null?void 0:_.map(R=>R&&s.jsxs(de.Tr,{className:Bl.tr,"data-testid":"search-control-row",onClick:P=>w(P,R),onAuxClick:P=>w(P,R),children:[x&&s.jsx(de.Td,{children:s.jsx("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${R.id}`,checked:!!c.selected[R.id],onChange:P=>g(P,R.id)})}),C.map(P=>s.jsx(de.Td,{children:WV(R,P)},P.name))]},R.id))})]}),(_==null?void 0:_.length)===0&&s.jsx(yu,{children:s.jsx(mn,{style:{height:150},children:s.jsx(fe,{size:"xl",c:"dimmed",children:"No results"})})}),T&&s.jsx(mn,{m:"md",p:"md",children:s.jsx(no,{value:yW(a),total:xW(a,T),onChange:R=>y(FV(a,R)),getControlProps:R=>{switch(R){case"previous":return{"aria-label":"Previous page"};case"next":return{"aria-label":"Next page"};default:return{}}}})}),s.jsx(GV,{search:a,visible:d.current.fieldEditorVisible,onOk:R=>{y(R),u({...d.current,fieldEditorVisible:!1})},onCancel:()=>{u({...d.current,fieldEditorVisible:!1})}}),s.jsx(YV,{search:a,visible:d.current.filterEditorVisible,onOk:R=>{y(R),u({...d.current,filterEditorVisible:!1})},onCancel:()=>{u({...d.current,filterEditorVisible:!1})}}),s.jsx(PV,{visible:d.current.exportDialogVisible,exportCsv:e.onExportCsv,exportTransactionBundle:e.onExportTransactionBundle,onCancel:()=>{u({...d.current,exportDialogVisible:!1})}}),s.jsx(JV,{visible:d.current.filterDialogVisible,title:(F=c.filterDialogSearchParam)!=null&&F.code?Li(c.filterDialogSearchParam.code):"",resourceType:j,searchParam:c.filterDialogSearchParam,filter:c.filterDialogFilter,defaultValue:"",onOk:R=>{y(Vh(a,R.code,R.operator,R.value)),u({...d.current,filterDialogVisible:!1})},onCancel:()=>{u({...d.current,filterDialogVisible:!1})}},(D=c.filterDialogSearchParam)==null?void 0:D.code)]})}const gW=wu;function vW(e){const t=(e.filters??[]).filter(n=>e.searchParams.find(r=>r.code===n.code));return t.length===0?s.jsx("span",{children:"no filters"}):s.jsx(s.Fragment,{children:t.map(n=>s.jsxs("div",{children:[m0(n.operator)," ",s.jsx(SR,{resourceType:e.resourceType,filter:n})]},`filter-${n.code}-${n.operator}-${n.value}`))})}function yW(e){return Math.floor((e.offset??0)/(e.count??Ah))+1}function xW(e,t){const n=e.count??Ah,r=ER(e,t);return Math.ceil(r/n)}function CR(e,t){return Math.min(ER(e,t),(e.offset??0)+1)}function bW(e,t){var n;return Math.max(CR(e,t)+(((n=t.entry)==null?void 0:n.length)??0)-1,0)}function ER(e,t){var r,o;let n=t.total;return n===void 0&&(n=(e.offset??0)+(((r=t.entry)==null?void 0:r.length)??0)+((o=t.link)!=null&&o.some(i=>i.relation==="next")?1:0)),n}function wW(e){const t=se(),[n,r]=p.useState(!1),[o,i]=p.useState(),{query:a,fields:l}=e,[c,u]=p.useState(),[d,f]=p.useState({}),h=p.useRef();h.current=c;const m=p.useRef({});m.current=d,p.useEffect(()=>{i(void 0),t.graphql(a).then(u).catch(b=>i(ht(b)))},[t,a]);function g(b,x){b.stopPropagation();const j=b.target.checked,T={...m.current};j?T[x]=!0:delete T[x],f(T)}function v(b){var E;b.stopPropagation();const C=b.target.checked,j={},T=(E=h.current)==null?void 0:E.data.ResourceList;C&&T&&T.forEach(_=>{_.id&&(j[_.id]=!0)}),f(j)}function S(){var x;const b=(x=h.current)==null?void 0:x.data.ResourceList;if(!b||b.length===0)return!1;for(const C of b)if(C.id&&!m.current[C.id])return!1;return!0}function y(b,x){$k(b.target)||(yt(b),b.button!==1&&e.onClick&&e.onClick(new Sf(x,b)),b.button===1&&e.onAuxClick&&e.onAuxClick(new Sf(x,b)))}if(p.useEffect(()=>{t.requestSchema(e.resourceType).then(()=>r(!0)).catch(console.log)},[t,e.resourceType]),!n)return s.jsx(Zn,{});const w=e.checkboxesEnabled;return s.jsxs("div",{onContextMenu:b=>yt(b),"data-testid":"search-control",children:[s.jsxs(de,{children:[s.jsx(de.Thead,{children:s.jsxs(de.Tr,{children:[w&&s.jsx(de.Th,{children:s.jsx("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:S(),onChange:b=>v(b)})}),l.map(b=>s.jsx(de.Th,{children:b.name},b.name))]})}),s.jsx(de.Tbody,{children:c==null?void 0:c.data.ResourceList.map(b=>b&&s.jsxs(de.Tr,{"data-testid":"search-control-row",onClick:x=>y(x,b),onAuxClick:x=>y(x,b),children:[w&&s.jsx(de.Td,{children:s.jsx("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${b.id}`,checked:!!d[b.id],onChange:x=>g(x,b.id)})}),l.map(x=>s.jsx(de.Td,{children:s.jsx(TV,{propertyType:x.propertyType,path:x.fhirPath,resource:b})},x.name))]},b.id))})]}),(c==null?void 0:c.data.ResourceList.length)===0&&s.jsx("div",{"data-testid":"empty-search",children:"No results"}),o&&s.jsx("div",{"data-testid":"search-error",children:s.jsx("pre",{style:{textAlign:"left"},children:JSON.stringify(o,void 0,2)})}),e.onBulk&&s.jsx(oe,{onClick:()=>e.onBulk(Object.keys(m.current)),children:"Bulk..."})]})}const SW=p.memo(wW);function ro(e){return s.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 491 491",style:{width:e.size,height:e.size},children:[s.jsx("title",{children:"Medplum Logo"}),s.jsx("path",{fill:e.fill??"#ad7136",d:"M282 67c6-16 16-29 29-40L289 0c-22 17-37 41-43 68l17 23 19-24z"}),s.jsx("path",{fill:e.fill??"#946af9",d:"M311 63c-17 0-33 4-48 11-16-7-32-11-49-11-87 0-158 96-158 214s71 214 158 214c17 0 33-4 49-11 15 7 31 11 48 11 87 0 158-96 158-214S398 63 311 63z"}),s.jsx("path",{fill:e.fill??"#7857c5",d:"M231 489l-17 2c-87 0-158-96-158-214S127 63 214 63l17 1c-39 12-70 102-70 213s31 201 70 212z"}),s.jsx("path",{fill:e.fill??"#40bc26",d:"M207 220a176 176 0 01-177 43A176 176 0 01251 43l1 5c17 59 2 125-45 172z"}),s.jsx("path",{fill:e.fill??"#33961e",d:"M252 48A421 421 0 0057 270l-27-7A176 176 0 01251 43l1 5z"})]})}function jW(e){const{group:t}=e;return s.jsx(Yn,{withBorder:!0,radius:"md",p:"xs",display:"flex",style:{alignItems:"center",justifyContent:"center"},children:s.jsxs(te,{children:[t.measureScore&&s.jsx(TW,{group:t}),!t.measureScore&&s.jsx(EW,{group:t})]})})}function CW(e){const{measure:t}=e;return s.jsxs(s.Fragment,{children:[s.jsx(fe,{fz:"md",fw:500,mb:8,children:t.title}),s.jsx(fe,{fz:"xs",c:"dimmed",mb:8,children:t.subtitle})]})}function EW(e){const{group:t}=e,n=t.population,r=n==null?void 0:n.find(c=>Oi(c.code)==="numerator"),o=n==null?void 0:n.find(c=>Oi(c.code)==="denominator"),i=r==null?void 0:r.count,a=o==null?void 0:o.count;if(a===0)return s.jsxs(q,{children:[s.jsx(ge,{order:3,children:"Not Applicable"}),s.jsx(fe,{children:`Denominator: ${a}`})]});if(i===void 0||a===void 0)return s.jsxs(q,{children:[s.jsx(ge,{order:3,children:"Insufficient Data"}),s.jsx(fe,{children:`Numerator: ${i}`}),s.jsx(fe,{children:`Denominator: ${a}`})]});const l=i/a*100;return s.jsx(kh,{size:120,thickness:12,roundCaps:!0,sections:[{value:l,color:TR(l)}],label:s.jsx(Es,{justify:"center",children:s.jsxs(fe,{fw:700,fz:18,children:[i," / ",a]})})})}function TW(e){var r,o,i;const{group:t}=e,n=((r=t.measureScore)==null?void 0:r.unit)??((o=t.measureScore)==null?void 0:o.code);return s.jsx(s.Fragment,{children:n==="%"?s.jsx(kh,{size:120,thickness:12,roundCaps:!0,sections:[{value:PW(t),color:TR(((i=t==null?void 0:t.measureScore)==null?void 0:i.value)??0)}],label:s.jsx(Es,{justify:"center",children:s.jsx(fe,{fw:700,fz:18,children:s.jsx($c,{value:t.measureScore})})})}):s.jsx(Es,{h:120,align:"center",children:s.jsx(ge,{order:3,children:s.jsx($c,{value:t.measureScore})})})})}function PW(e){var r,o;const t=(r=e.measureScore)==null?void 0:r.value,n=(o=e.measureScore)==null?void 0:o.unit;return t?t<=1&&n==="%"?t*100:t:0}function TR(e){return e<=33?"red":e<=67?"yellow":"green"}function kW(e){var r;const t=wt(e.measureReport),[n]=U8("Measure",{url:t==null?void 0:t.measure});return t?s.jsxs(q,{children:[n&&s.jsx(CW,{measure:n}),s.jsx(ux,{cols:{base:3,sm:1},spacing:{base:"md",sm:"sm"},children:(r=t.group)==null?void 0:r.map((o,i)=>s.jsx(jW,{group:o},o.id??i))})]}):null}function RW(e){const{patient:t,...n}=e,r=p.useCallback((o,i,a)=>{const l=`${i}/${a}`,c=100;return Promise.allSettled([o.readHistory("Patient",a),o.search("Communication",{subject:l,_count:c}),o.search("Device",{patient:l,_count:c}),o.search("DeviceRequest",{patient:l,_count:c}),o.search("DiagnosticReport",{subject:l,_count:c}),o.search("Media",{subject:l,_count:c}),o.search("ServiceRequest",{subject:l,_count:c}),o.search("Task",{subject:l,_count:c})])},[]);return s.jsx(Uh,{value:t,loadTimelineResources:r,createCommunication:(o,i,a)=>({resourceType:"Communication",status:"completed",subject:Et(o),sender:Et(i),sent:new Date().toISOString(),payload:[{contentString:a}]}),createMedia:(o,i,a)=>({resourceType:"Media",status:"completed",subject:Et(o),operator:Et(i),issued:new Date().toISOString(),content:a}),...n})}const _W="_section_14dzq_2",DW="_hovering_14dzq_11",IW="_editing_14dzq_15",AW="_bottomActions_14dzq_20",_a={section:_W,hovering:DW,editing:IW,bottomActions:AW};function NW(e){const t=se(),n=wt(e.value),[r,o]=p.useState(!1),[i,a]=p.useState(),[l,c]=p.useState(),[u,d]=p.useState();function f(){c(void 0)}function h(){a(void 0)}const m=p.useRef();if(m.current=u,p.useEffect(()=>{t.requestSchema("PlanDefinition").then(()=>o(!0)).catch(console.log)},[t]),p.useEffect(()=>(d(zW(n??{resourceType:"PlanDefinition",status:"active"})),document.addEventListener("mouseover",f),document.addEventListener("click",h),()=>{document.removeEventListener("mouseover",f),document.removeEventListener("click",h)}),[n]),!r||!u)return null;function g(v,S){d({...m.current,[v]:S})}return s.jsx("div",{children:s.jsxs(Ke,{testid:"questionnaire-form",onSubmit:()=>e.onSubmit(u),children:[s.jsx(ve,{label:"Plan Title",defaultValue:u.title,onChange:v=>g("title",v.currentTarget.value)}),s.jsx(PR,{actions:u.action||[],selectedKey:i,setSelectedKey:a,hoverKey:l,setHoverKey:c,onChange:v=>g("action",v)}),s.jsx(oe,{type:"submit",children:"Save"})]})})}function PR(e){const t=p.useRef();t.current=e.actions;function n(i){e.onChange(t.current.map(a=>a.id===i.id?i:a))}function r(i){e.onChange([...t.current,i]),e.setSelectedKey(i.id)}function o(i){e.onChange(t.current.filter(a=>a!==i))}return s.jsxs("div",{className:_a.section,children:[e.actions.map(i=>s.jsx("div",{children:s.jsx(MW,{action:i,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,setHoverKey:e.setHoverKey,onChange:n,onRemove:()=>o(i)})},i.id)),s.jsx("div",{className:_a.bottomActions,children:s.jsx(Ze,{href:"#",onClick:i=>{yt(i),r({id:RR()})},children:"Add action"})})]})}function MW(e){const{action:t}=e,n=FW(t),r=e.selectedKey===e.action.id,o=e.hoverKey===e.action.id;function i(c){c.stopPropagation(),e.setSelectedKey(e.action.id)}function a(c){yt(c),e.setHoverKey(e.action.id)}const l=rt(_a.section,{[_a.editing]:r,[_a.hovering]:o&&!r});return s.jsxs("div",{"data-testid":t.id,className:l,onClick:i,onMouseOver:a,onFocus:a,children:[r?s.jsx(LW,{action:t,actionType:n,onChange:e.onChange,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,setHoverKey:e.setHoverKey,onRemove:e.onRemove}):s.jsx(OW,{action:t,actionType:n}),s.jsx("div",{className:_a.bottomActions,children:s.jsx(Ze,{href:"#",onClick:c=>{c.preventDefault(),e.onRemove()},children:"Remove"})})]})}const Rg={path:"PlanDefinition.action.timing[x]",min:0,max:1,description:"",isArray:!1,constraints:[],type:["dateTime","Period","Range","Timing"].map(e=>({code:e}))};function OW(e){const{action:t,actionType:n}=e,[r,o]=kR(t);return s.jsxs("div",{children:[s.jsxs("div",{children:[t.title||"Untitled"," ",n&&`(${n})`]}),t.definitionCanonical&&s.jsx("div",{children:s.jsx(bf,{value:{reference:t.definitionCanonical}})}),r&&s.jsx("div",{children:s.jsx(Zr,{property:Rg,propertyType:o,value:r})})]})}function LW(e){const{action:t}=e,[n,r]=p.useState(e.actionType);function o(i,a){e.onChange({...t,[i]:a})}return s.jsxs(Oe,{gap:"xl",children:[s.jsx(ve,{name:`actionTitle-${t.id}`,label:"Title",defaultValue:t.title,onChange:i=>o("title",i.currentTarget.value)}),s.jsx(ve,{name:`actionDescription-${t.id}`,label:"Description",defaultValue:t.description,onChange:i=>o("description",i.currentTarget.value)}),s.jsx(It,{label:"Type of Action",description:"The type of the action to be performed.",name:`actionType-${t.id}`,defaultValue:n,onChange:i=>r(i.currentTarget.value),data:["","appointment","lab","questionnaire","task"]}),t.action&&t.action.length>0&&s.jsx(PR,{actions:t.action,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,setHoverKey:e.setHoverKey,onChange:i=>o("action",i)}),(()=>{switch(n){case"appointment":return s.jsx(ld,{title:"Appointment",description:"The subject must schedule an appointment from the schedule.",resourceType:"Schedule",action:t,onChange:e.onChange});case"lab":return s.jsx(ld,{title:"Lab",description:"The subject must complete the following lab panel.",resourceType:"ActivityDefinition",action:t,onChange:e.onChange});case"questionnaire":return s.jsx(ld,{title:"Questionnaire",description:"The subject must complete the selected questionnaire.",resourceType:"Questionnaire",action:t,onChange:e.onChange});case"task":return s.jsx(ld,{title:"Task",description:"The subject must complete the following task.",resourceType:"ActivityDefinition",action:t,onChange:e.onChange});default:return null}})(),s.jsx(vt,{title:"Timing",description:"When the action should take place.",children:s.jsx($W,{name:"timing-"+t.id,action:t,onChange:e.onChange})})]})}function ld(e){const{id:t,definitionCanonical:n}=e.action,r=n!=null&&n.startsWith(e.resourceType+"/")?{reference:n}:void 0;return s.jsx(Ys,{name:t,resourceType:e.resourceType,defaultValue:r,loadOnFocus:!0,onChange:o=>{o?e.onChange({...e.action,definitionCanonical:st(o)}):e.onChange({...e.action,definitionCanonical:void 0})}})}function $W(e){const t=e.action,n="timing",[r,o]=kR(t);return s.jsx(jl,{property:Rg,name:"timing[x]",path:"PlanDefinition.timing[x]",defaultValue:r,defaultPropertyType:o,onChange:(i,a)=>{e.onChange(Xk(t,n,a??n,Rg,i))},outcome:void 0})}function FW(e){var t,n,r;if((t=e.definitionCanonical)!=null&&t.startsWith("Schedule"))return"appointment";if((n=e.definitionCanonical)!=null&&n.startsWith("Questionnaire/"))return"questionnaire";if((r=e.definitionCanonical)!=null&&r.startsWith("ActivityDefinition/"))return"task"}function kR(e){return gu({type:"PlanDefinitionAction",value:e},"timing")}let Xp=1;function RR(e){if(e){if(e.startsWith("id-")){const t=parseInt(e.substring(3),10);isNaN(t)||(Xp=Math.max(Xp,t+1))}return e}return"id-"+Xp++}function zW(e){return{...e,action:_R(e.action)}}function _R(e){if(e)return e.map(t=>({...t,id:RR(t.id),action:_R(t.action)}))}var jt=(e=>(e.group="group",e.display="display",e.question="question",e.boolean="boolean",e.decimal="decimal",e.integer="integer",e.date="date",e.dateTime="dateTime",e.time="time",e.string="string",e.text="text",e.url="url",e.choice="choice",e.openChoice="open-choice",e.attachment="attachment",e.reference="reference",e.quantity="quantity",e))(jt||{});function BW(e){return e.type==="choice"||e.type==="open-choice"}function UW(e,t){if(!e.enableWhen)return!0;const n=e.enableBehavior??"any";for(const r of e.enableWhen){const o=DR(t,r.question);if(r.operator==="exists"&&!r.answerBoolean&&!(o!=null&&o.length)){if(n==="any")return!0;continue}const{anyMatch:i,allMatch:a}=HW(r,o,n);if(n==="any"&&i)return!0;if(n==="all"&&!a)return!1}return n!=="any"}function VW(e,t,n){return e.map(r=>{var a;const o=(a=n.answerOption)==null?void 0:a.find(l=>qs(l.valueCoding)===r||l[t]===r),i=vn({type:"QuestionnaireItemAnswerOption",value:o},"value");return{[t]:i==null?void 0:i.value}})}function DR(e,t){if(e)for(const n of e){if(n.linkId===t)return n.answer;if(n.item){const r=DR(n.item,t);if(r)return r}}}function WW(e,t,n){if(n==="exists")return!!e===t.value;if(e){const r=n==="="||n==="!="?n==null?void 0:n.replace("=","~"):n,[{value:o}]=Lc(`%actualAnswer ${r} %expectedAnswer`,[e],{"%actualAnswer":e,"%expectedAnswer":t});return o}else return!1}function HW(e,t,n){const r=t||[],o=vn({type:"QuestionnaireItemEnableWhen",value:e},"answer[x]");let i=!1,a=!0;for(const l of r){const c=vn({type:"QuestionnaireResponseItemAnswer",value:l},"value[x]"),{operator:u}=e;if(WW(c,o,u)?i=!0:a=!1,n==="any"&&i)break}return{anyMatch:i,allMatch:a}}function IR(e){var n,r;const t=xl(e,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource");if(t){if(t.valueCode!==void 0)return[t.valueCode];if(t.valueCodeableConcept)return(r=(n=t.valueCodeableConcept)==null?void 0:n.coding)==null?void 0:r.map(o=>o.code)}}function Jp(e,t){var o;const n=Xr(e);let r=xl(n,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource");return!t||t.length===0?(r&&(n.extension=(o=n.extension)==null?void 0:o.filter(i=>i!==r)),n):(r||(n.extension||(n.extension=[]),r={url:"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource"},n.extension.push(r)),t.length===1?(r.valueCode=t[0],delete r.valueCodeableConcept):(r.valueCodeableConcept={coding:t.map(i=>({code:i}))},delete r.valueCode),n)}function qW(e,t,n){const r=xl(e,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceFilter");if(!(r!=null&&r.valueString))return;let o=r.valueString;t!=null&&t.reference&&(o=o.replaceAll("$subj",t.reference)),n!=null&&n.reference&&(o=o.replaceAll("$encounter",n.reference));const i={},a=o.split("&");for(const l of a){const[c,u]=xg(l,"=",2);i[c]=u}return i}function GW(e){return{resourceType:"QuestionnaireResponse",questionnaire:st(e),item:AR(e.item),status:"in-progress"}}function AR(e){return(e==null?void 0:e.map(NR))??[]}function NR(e){var t;return{id:KW(),linkId:e.linkId,text:e.text,item:AR(e.item),answer:((t=e.initial)==null?void 0:t.map(YW))??[]}}let QW=1;function KW(){return"id-"+QW++}function YW(e){return{...e}}function XW(e){return e.value.display||e.value.reference||pr(e.value)}function JW(e){var n,r,o,i;const t=(n=e==null?void 0:e.item)==null?void 0:n[0];if(t){const a=xl(t,"http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl");if(((i=(o=(r=a==null?void 0:a.valueCodeableConcept)==null?void 0:r.coding)==null?void 0:o[0])==null?void 0:i.code)==="page")return e.item.length}return 1}const MR=p.createContext({});function _g(e){const t=p.useContext(MR),n=e.item,r=e.response;function o(u){var f,h,m,g;let d;Array.isArray(u)?d=u:e.index>=(((h=(f=e.response)==null?void 0:f.answer)==null?void 0:h.length)??0)?d=(((m=e.response)==null?void 0:m.answer)??[]).concat([u]):d=(((g=e.response)==null?void 0:g.answer)??[]).map((S,y)=>y===e.index?u:S)??[],e.onChange({id:r==null?void 0:r.id,linkId:r==null?void 0:r.linkId,text:n.text,answer:d})}const i=n.type;if(!i)return null;const a=n.linkId;if(!a)return null;const l=n.initial&&n.initial.length>0?n.initial[0]:void 0,c=g0(r,e.index)??vn({type:"QuestionnaireItemInitial",value:l},"value");switch(i){case jt.display:return s.jsx("p",{children:e.item.text},e.item.linkId);case jt.boolean:return s.jsx(Kk,{title:e.item.text,htmlFor:e.item.linkId,children:s.jsx(_n,{id:e.item.linkId,name:e.item.linkId,defaultChecked:c==null?void 0:c.value,onChange:u=>o({valueBoolean:u.currentTarget.checked})})},e.item.linkId);case jt.decimal:return s.jsx(ve,{type:"number",step:"any",id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueDecimal:u.currentTarget.valueAsNumber})});case jt.integer:return s.jsx(ve,{type:"number",step:1,id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueInteger:u.currentTarget.valueAsNumber})});case jt.date:return s.jsx(ve,{type:"date",id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueDate:u.currentTarget.value})});case jt.dateTime:return s.jsx(_s,{name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueDateTime:u})});case jt.time:return s.jsx(ve,{type:"time",id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueTime:u.currentTarget.value})});case jt.string:case jt.url:return s.jsx(ve,{id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueString:u.currentTarget.value})});case jt.text:return s.jsx(Us,{id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueString:u.currentTarget.value})});case jt.attachment:return s.jsx(te,{py:4,children:s.jsx(Bk,{path:"",name:a,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueAttachment:u})})});case jt.reference:return s.jsx(zh,{name:a,required:n.required,targetTypes:IR(n),searchCriteria:qW(n,t.subject,t.encounter),defaultValue:c==null?void 0:c.value,onChange:u=>o({valueReference:u})});case jt.quantity:return s.jsx(Ds,{path:"",name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueQuantity:u}),disableWheel:!0});case jt.choice:case jt.openChoice:return oH(n)&&!n.answerValueSet?s.jsx(ZW,{name:a,item:n,initial:l,response:r,onChangeAnswer:u=>o(u)}):s.jsx(eH,{name:a,item:n,initial:l,response:r,onChangeAnswer:u=>o(u)});default:return null}}function ZW(e){var c;const{name:t,item:n,initial:r,response:o}=e;if(!((c=n.answerOption)!=null&&c.length))return s.jsx(OR,{});const i=vn({type:"QuestionnaireItemInitial",value:r},"value"),a=[""];for(const u of n.answerOption){const d=vn({type:"QuestionnaireItemAnswerOption",value:u},"value");a.push(Fw(d))}const l=g0(o)??i;if(n.repeats){const{propertyName:u,data:d}=iH(e.item),f=nH(o);return s.jsx(wh,{data:d,placeholder:"Select items",searchable:!0,defaultValue:f||[Fw(i)],onChange:h=>{const m=VW(h,u,n);e.onChangeAnswer(m)}})}return s.jsx(It,{id:t,name:t,onChange:u=>{const d=u.currentTarget.selectedIndex;if(d===0){e.onChangeAnswer({});return}const f=n.answerOption[d-1],h=vn({type:"QuestionnaireItemAnswerOption",value:f},"value"),m="value"+nn(h.type);e.onChangeAnswer({[m]:h.value})},defaultValue:qs(l==null?void 0:l.value)||(l==null?void 0:l.value),data:a})}function eH(e){var a;const{name:t,item:n,initial:r,onChangeAnswer:o,response:i}=e;return!((a=n.answerOption)!=null&&a.length)&&!n.answerValueSet?s.jsx(OR,{}):n.answerValueSet?s.jsx(Jk,{path:"",name:t,binding:n.answerValueSet,onChange:l=>o({valueCoding:l}),creatable:n.type===jt.openChoice}):s.jsx(tH,{name:(i==null?void 0:i.id)??t,item:n,initial:r,response:i,onChangeAnswer:o})}function tH(e){const{name:t,item:n,initial:r,onChangeAnswer:o,response:i}=e,a=Gs("QuestionnaireItemAnswerOption","value[x]"),l=vn({type:"QuestionnaireItemInitial",value:r},"value"),c=[];let u;if(n.answerOption)for(let h=0;h<n.answerOption.length;h++){const m=n.answerOption[h],g=`${t}-option-${h}`,v=vn({type:"QuestionnaireItemAnswerOption",value:m},"value");v!=null&&v.value&&(l&&pr(v)===pr(l)&&(u=g),c.push([g,v]))}const d=g0(i),f=rH(c,d);return s.jsx(ks.Group,{name:t,value:f??u,onChange:h=>{const m=c.find(g=>g[0]===h);if(m){const g=m[1],v="value"+nn(g.type);o({[v]:g.value})}},children:c.map(([h,m])=>s.jsx(ks,{id:h,value:h,py:4,label:s.jsx(Zr,{property:a,propertyType:m.type,value:m.value})},h))})}function OR(){return s.jsx(ve,{disabled:!0,placeholder:"No Answers Defined"})}function LR(e){return vn({type:"QuestionnaireItemAnswer",value:e},"value")}function g0(e,t=0){const n=e.answer;return LR((n==null?void 0:n[t])??{})}function nH(e){const t=e.answer;return t?t.map(r=>LR(r)).map(r=>qs(r==null?void 0:r.value)||(r==null?void 0:r.value)):[]}function rH(e,t){var n;return(n=e.find(r=>Mi(r[1].value,t==null?void 0:t.value)))==null?void 0:n[0]}function Fw(e){if(e)return e.type==="CodeableConcept"?Oi(e.value):e.type==="Coding"?qs(e.value):e.type==="Reference"?XW(e):e.value.toString()}function oH(e){var t;return!!((t=e.extension)!=null&&t.some(n=>{var r,o,i;return n.url==="http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl"&&((i=(o=(r=n.valueCodeableConcept)==null?void 0:r.coding)==null?void 0:o[0])==null?void 0:i.code)==="drop-down"}))}function iH(e){var i;if(((i=e.answerOption)==null?void 0:i.length)===0)return{propertyName:"",data:[]};const t=e.answerOption[0],n=vn({type:"QuestionnaireItemAnswerOption",value:t},"value"),r="value"+nn(n.type),o=(e.answerOption??[]).map(a=>({value:zw(a,r),label:zw(a,r)}));return{propertyName:r,data:o}}function zw(e,t){var n;return qs(e.valueCoding)||((n=e[t])==null?void 0:n.toString())}const sH="_section_cpwxo_1",aH="_hovering_cpwxo_10",lH="_editing_cpwxo_14",cH="_questionBody_cpwxo_19",uH="_topActions_cpwxo_23",dH="_bottomActions_cpwxo_32",fH="_movementActions_cpwxo_43",hH="_movementIcons_cpwxo_55",pH="_columnAlignment_cpwxo_59",mH="_linkIdInput_cpwxo_64",gH="_typeSelect_cpwxo_69",br={section:sH,hovering:aH,editing:lH,questionBody:cH,topActions:uH,bottomActions:dH,movementActions:fH,movementIcons:hH,columnAlignment:pH,linkIdInput:mH,typeSelect:gH};function vH(e){const t=se(),n=wt(e.questionnaire),[r,o]=p.useState(!1),[i,a]=p.useState(),[l,c]=p.useState(),[u,d]=p.useState();function f(){d(void 0)}function h(){c(void 0)}p.useEffect(()=>{t.requestSchema("Questionnaire").then(()=>o(!0)).catch(console.log)},[t]),p.useEffect(()=>(a(wH(n??{resourceType:"Questionnaire",status:"active"})),document.addEventListener("mouseover",f),document.addEventListener("click",h),()=>{document.removeEventListener("mouseover",f),document.removeEventListener("click",h)}),[n]);const m=(g,v)=>{a(g),e.autoSave&&!v&&e.onSubmit&&e.onSubmit(g)};return!r||!i?null:s.jsx("div",{children:s.jsxs(Ke,{testid:"questionnaire-form",onSubmit:()=>e.onSubmit(i),children:[s.jsx($R,{item:i,selectedKey:l,setSelectedKey:c,hoverKey:u,setHoverKey:d,onChange:m}),s.jsx(oe,{type:"submit",children:"Save"})]})})}function $R(e){var b;const t=e.item,n=e.item,r=ni(e.item),o=r||n.type===jt.group,i=n.linkId??"[untitled]",a=e.selectedKey===e.item.id,l=e.hoverKey===e.item.id,c=p.useRef();c.current=e.item;function u(x){yt(x),e.setSelectedKey(e.item.id)}function d(x){yt(x),e.setHoverKey(e.item.id)}function f(x){var j;const C=c.current;e.onChange({...C,item:(j=C.item)==null?void 0:j.map(T=>T.id===x.id?x:T)})}function h(x,C){e.onChange({...e.item,item:[...e.item.item??[],x]},C)}function m(x){var C;e.onChange({...e.item,item:(C=e.item.item)==null?void 0:C.filter(j=>j!==x)})}function g(x,C){e.onChange({...c.current,[x]:C})}function v(x){e.onChange({...e.item,...x})}function S(x){var C;e.onChange({...e.item,item:(C=e.item.item)==null?void 0:C.map(j=>j===x?{...j,repeats:!j.repeats}:j)})}function y(x,C){const j=CH(e.item.item,x,C);e.onChange({...e.item,item:j})}const w=rt(br.section,{[br.editing]:a,[br.hovering]:l&&!a});return s.jsxs("div",{"data-testid":n.linkId,className:w,onClick:u,onMouseOver:d,onFocus:d,children:[s.jsx("div",{className:br.questionBody,children:a?s.jsxs(s.Fragment,{children:[r&&s.jsx(ve,{size:"xl",defaultValue:t.title,onBlur:x=>g("title",x.currentTarget.value)}),!r&&s.jsx(Us,{autosize:!0,minRows:2,defaultValue:n.text,onBlur:x=>g("text",x.currentTarget.value)}),n.type==="reference"&&s.jsx(bH,{item:n,onChange:v}),BW(n)&&s.jsx(yH,{item:n,onChange:x=>v(x)})]}):s.jsxs(s.Fragment,{children:[t.title&&s.jsx(ge,{children:t.title}),n.text&&s.jsx("div",{children:n.text}),!o&&s.jsx(_g,{item:n,index:0,onChange:()=>{},response:{linkId:n.linkId}})]})}),(b=n.item)==null?void 0:b.map((x,C)=>s.jsx("div",{children:s.jsx($R,{item:x,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,isFirst:C===0,isLast:C===(e.item.item??[]).length-1,setHoverKey:e.setHoverKey,onChange:f,onRemove:()=>m(x),onRepeatable:S,onMoveUp:()=>y(C,-1),onMoveDown:()=>y(C,1)})},x.id)),!o&&s.jsx("div",{className:br.topActions,children:a?s.jsxs(s.Fragment,{children:[s.jsx(ve,{size:"xs",className:br.linkIdInput,defaultValue:n.linkId,onBlur:x=>g("linkId",x.currentTarget.value)}),!o&&s.jsx(It,{size:"xs",className:br.typeSelect,defaultValue:n.type,onChange:x=>g("type",x.currentTarget.value),data:[{value:"display",label:"Display"},{value:"boolean",label:"Boolean"},{value:"decimal",label:"Decimal"},{value:"integer",label:"Integer"},{value:"date",label:"Date"},{value:"dateTime",label:"Date/Time"},{value:"time",label:"Time"},{value:"string",label:"String"},{value:"text",label:"Text"},{value:"url",label:"URL"},{value:"choice",label:"Choice"},{value:"open-choice",label:"Open Choice"},{value:"attachment",label:"Attachment"},{value:"reference",label:"Reference"},{value:"quantity",label:"Quantity"}]})]}):s.jsx("div",{children:i})}),!r&&s.jsx(q,{className:br.movementActions,children:s.jsxs(q,{className:br.columnAlignment,children:[!e.isFirst&&s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),e.onMoveUp&&e.onMoveUp()},children:s.jsx(X8,{"data-testid":"up-button",size:15,className:br.movementIcons})}),!e.isLast&&s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),e.onMoveDown&&e.onMoveDown()},children:s.jsx(Y8,{"data-testid":"down-button",size:15,className:br.movementIcons})})]})}),s.jsxs("div",{className:br.bottomActions,children:[o&&s.jsxs(s.Fragment,{children:[s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),h({id:As(),linkId:Ag("q"),type:"string",text:"Question"})},children:"Add item"}),s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),h({id:As(),linkId:Ag("g"),type:"group",text:"Group"},!0)},children:"Add group"})]}),r&&s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),h(jH(),!0)},children:"Add Page"}),a&&!r&&s.jsxs(s.Fragment,{children:[s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),e.onRepeatable&&e.onRepeatable(n)},children:n.repeats?"Remove Repeatable":"Make Repeatable"}),s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),e.onRemove&&e.onRemove()},children:"Remove"})]})]})]})}function yH(e){const t=Gs("QuestionnaireItemAnswerOption","value[x]"),n=e.item.answerOption??[];return s.jsxs("div",{children:[e.item.answerValueSet!==void 0?s.jsx(ve,{placeholder:"Enter Value Set",defaultValue:e.item.answerValueSet,onChange:r=>e.onChange({...e.item,answerValueSet:r.target.value})}):s.jsx(xH,{options:n,property:t,item:e.item,onChange:e.onChange}),s.jsxs(q,{display:"flex",children:[s.jsx(Ze,{href:"#",onClick:r=>{yt(r),e.onChange({...e.item,answerValueSet:void 0,answerOption:[...n,{id:As()}]})},children:"Add choice"}),s.jsx(Rh,{w:"lg"}),s.jsx(Ze,{href:"#",onClick:r=>{yt(r),e.onChange({...e.item,answerOption:[],answerValueSet:""})},children:"Add value set"})]})]})}function xH(e){return s.jsx("div",{children:e.options.map(t=>{const[n,r]=gu({type:"QuestionnaireItemAnswerOption",value:t},"value");return s.jsxs("div",{style:{display:"flex",flexDirection:"row",justifyContent:"space-between",alignItems:"center",width:"80%"},children:[s.jsx("div",{children:s.jsx(jl,{name:"value[x]",path:"Questionnaire.answerOption.value[x]",property:e.property,defaultPropertyType:r,defaultValue:n,onChange:(o,i)=>{const a=[...e.options],l=a.findIndex(c=>c.id===t.id);a[l]={id:t.id,[i]:o},e.onChange({...e.item,answerOption:a})},outcome:void 0},t.id)}),s.jsx("div",{children:s.jsx(Ze,{href:"#",onClick:o=>{yt(o),e.onChange({...e.item,answerOption:e.options.filter(i=>i.id!==t.id)})},children:"Remove"})})]},t.id)})})}function bH(e){const t=IR(e.item)??[];return s.jsxs(s.Fragment,{children:[t.map((n,r)=>s.jsxs(te,{children:[s.jsx(Kx,{name:"resourceType",placeholder:"Resource Type",defaultValue:n,onChange:o=>{e.onChange(Jp(e.item,t.map(i=>i===n?o:i)))}}),s.jsx(Ze,{href:"#",onClick:o=>{yt(o),e.onChange(Jp(e.item,t.filter(i=>i!==n)))},children:"Remove"})]},`${n}-${r}`)),s.jsx(Ze,{href:"#",onClick:n=>{yt(n),e.onChange(Jp(e.item,[...t,""]))},children:"Add Resource Type"})]})}let Dg=1,Ig=1;function Ag(e){return e+Dg++}function As(){return"id-"+Ig++}function wH(e){return{...e,id:e.id||As(),item:FR(e.item)}}function FR(e){if(e)return e.forEach(t=>{var n,r;(n=t.id)!=null&&n.match(/^id-\d+$/)&&(Ig=Math.max(Ig,parseInt(t.id.substring(3),10)+1)),(r=t.linkId)!=null&&r.match(/^q\d+$/)&&(Dg=Math.max(Dg,parseInt(t.linkId.substring(1),10)+1))}),e.map(t=>({...t,id:t.id||As(),item:FR(t.item),answerOption:SH(t.answerOption)}))}function SH(e){if(e)return e.map(t=>({...t,id:t.id||As()}))}function jH(){return{id:As(),linkId:Ag("s"),type:"group",text:"New Page",extension:[{url:"http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl",valueCodeableConcept:{coding:[{system:"http://hl7.org/fhir/questionnaire-item-control",code:"page"}]}}]}}function CH(e,t,n){const r=e??[],o=t+n;if(o<0||o>=r.length)return r;const i=[...r];return[i[t],i[o]]=[i[o],i[t]],i}function zR(e){const{item:t,response:n,onChange:r}=e,[o,i]=p.useState(EH(t,n??{linkId:t.linkId}));if(!e.checkForQuestionEnabled(t)||!n)return null;if(t.type===jt.display)return s.jsx("p",{children:t.text},t.linkId);const a=(t==null?void 0:t.repeats)&&t.type!==jt.choice&&t.type!==jt.openChoice;return t.type===jt.boolean?s.jsx(_g,{item:t,response:n,onChange:l=>r([l]),index:0},t.linkId):s.jsxs(vt,{htmlFor:e.item.linkId,title:e.item.text,withAsterisk:e.item.required,children:[[...Array(o)].map((l,c)=>s.jsx(_g,{item:t,response:n,onChange:u=>r([u]),index:c},`${t.linkId}-${c}`)),a&&s.jsx(Ze,{onClick:()=>i(l=>l+1),children:"Add Item"})]},e.item.linkId)}function EH(e,t){if(e.type===jt.choice||e.type===jt.openChoice)return 1;const n=t.answer;return n!=null&&n.length?n.length:1}function BR(e){const[t,n]=p.useState(e.response);if(t.length===0)return null;function r(i,a){const l=t.map((c,u)=>u===a?i[0]:c);n(l),e.onChange(l)}function o(){const i=NR(e.item);n([...t,i])}return s.jsxs(s.Fragment,{children:[t.map((i,a)=>s.jsx(UR,{item:e.item,response:i,checkForQuestionEnabled:e.checkForQuestionEnabled,onChange:l=>r(l,a)},i.id)),e.item.repeats&&s.jsx(Ze,{onClick:o,children:`Add Group: ${e.item.text}`})]})}function UR(e){var i;const{response:t,checkForQuestionEnabled:n,onChange:r}=e;function o(a){var d;const l=(d=t.item)==null?void 0:d.map(f=>a.find(m=>m.id===f.id)??f),c=l==null?void 0:l.concat(a.slice(1)),u={...t,item:c};r([u])}return e.checkForQuestionEnabled(e.item)?s.jsxs("div",{children:[e.item.text&&s.jsx(ge,{order:3,mb:"md",children:e.item.text}),s.jsx(Oe,{children:(i=e.item.item)==null?void 0:i.map(a=>{var l,c,u;return a.type===jt.group?a.repeats?s.jsx(BR,{item:a,response:((l=t.item)==null?void 0:l.filter(d=>d.linkId===a.linkId))??[],checkForQuestionEnabled:n,onChange:o},a.linkId):s.jsx(UR,{item:a,checkForQuestionEnabled:n,response:((c=t.item)==null?void 0:c.find(d=>d.linkId===a.linkId))??{linkId:a.linkId},onChange:o},a.linkId):s.jsx(zR,{item:a,response:(u=t.item)==null?void 0:u.find(d=>d.linkId===a.linkId),onChange:o,checkForQuestionEnabled:n},a.linkId)})})]},e.item.linkId):null}function TH(e){const{items:t,response:n,activePage:r,onChange:o,nextStep:i,prevStep:a,numberOfPages:l,renderPages:c,submitButtonText:u,excludeButtons:d,checkForQuestionEnabled:f}=e,h=t.map(m=>{var S;const g=((S=n==null?void 0:n.item)==null?void 0:S.filter(y=>y.linkId===m.linkId))??[],v=m.type===jt.group?s.jsx(BR,{item:m,response:g,onChange:o,checkForQuestionEnabled:f},m.linkId):s.jsx(zR,{item:m,response:g==null?void 0:g[0],onChange:o,checkForQuestionEnabled:f},m.linkId);return c?s.jsx(tl.Step,{label:m.text,children:v},m.linkId):v});return s.jsxs(s.Fragment,{children:[c&&s.jsx(tl,{active:r??0,allowNextStepsSelect:!1,p:6,children:h}),!c&&s.jsx(Oe,{children:h}),!d&&s.jsx(PH,{activePage:r??0,numberOfPages:l,nextStep:c?i:void 0,prevStep:c?a:void 0,renderPages:c,submitButtonText:u})]})}function PH(e){const t=e.renderPages&&e.activePage>0,n=e.renderPages&&e.activePage<e.numberOfPages-1,r=!e.renderPages||e.activePage===e.numberOfPages-1;return s.jsxs(te,{justify:"flex-end",mt:"xl",gap:"xs",children:[t&&s.jsx(oe,{onClick:e.prevStep,children:"Back"}),n&&s.jsx(oe,{onClick:o=>{const i=o.currentTarget.closest("form");e.nextStep&&i.reportValidity()&&e.nextStep()},children:"Next"}),r&&s.jsx(oe,{type:"submit",children:e.submitButtonText??"Submit"})]})}function VR(e){const t=se(),n=t.getProfile(),[r,o]=p.useState(!1),i=wt(e.questionnaire),[a,l]=p.useState(),[c,u]=p.useState(0),{onChange:d}=e;p.useEffect(()=>{t.requestSchema("Questionnaire").then(()=>t.requestSchema("QuestionnaireResponse")).then(()=>o(!0)).catch(console.log)},[t]),p.useEffect(()=>{l(i?GW(i):void 0)},[i]);const f=p.useCallback(S=>{l(y=>{const w=(y==null?void 0:y.item)??[],x={resourceType:"QuestionnaireResponse",status:"in-progress",item:WR(w,Array.isArray(S)?S:[S])};if(d)try{d(x)}catch(C){console.error("Error invoking QuestionnaireForm.onChange callback",C)}return x})},[d]);function h(S){return UW(S,(a==null?void 0:a.item)??[])}if(!r||!i||!a)return null;const m=JW(i),g=()=>u(S=>S+1),v=()=>u(S=>S-1);return s.jsx(MR.Provider,{value:{subject:e.subject,encounter:e.encounter},children:s.jsxs(Ke,{testid:"questionnaire-form",onSubmit:()=>{e.onSubmit&&a&&e.onSubmit({...a,questionnaire:st(i),subject:e.subject,source:Et(n),authored:new Date().toISOString(),status:"completed"})},children:[i.title&&s.jsx(ge,{children:i.title}),s.jsx(TH,{items:i.item??[],response:a,onChange:f,renderPages:!e.disablePagination&&m>1,activePage:c,numberOfPages:m,excludeButtons:e.excludeButtons,submitButtonText:e.submitButtonText,checkForQuestionEnabled:h,nextStep:g,prevStep:v})]})})}function kH(e,t){const n=WR(e.item??[],t.item??[]);return{...t,item:n.length>0?n:void 0,answer:t.answer&&t.answer.length>0?t.answer:e.answer}}function WR(e,t){const n=[],r=new Set;for(const o of e){const i=o.id,a=t.find(l=>l.id===i);a?(n.push(kH(o,a)),r.add(a.id)):n.push(o)}for(const o of t)r.has(o.id)||n.push(o);return n}const RH="_section_4m5it_1",_H={section:RH},DH=["gender","age","gestationalAge","context","appliesTo","category"],IH={definition:{resourceType:"ObservationDefinition",code:{text:""}},onSubmit:()=>{}};function AH(e){e=Object.assign(IH,e);const t=e.definition,[n,r]=p.useState([]),[o,i]=p.useState(1),[a,l]=p.useState(1);return p.useEffect(()=>{const g=OH(t,l);r(LH(g.qualifiedInterval||[],i))},[t]),s.jsxs(Ke,{testid:"reference-range-editor",onSubmit:c,children:[s.jsx(Oe,{children:n.map(g=>{var v;return s.jsx(NH,{unit:FH((v=t.quantitativeDetails)==null?void 0:v.unit),onChange:f,onAdd:h,onRemove:m,onRemoveGroup:d,intervalGroup:g},`group-${g.id}`)})}),s.jsx(tn,{title:"Add Group",variant:"subtle",size:"sm",onClick:g=>{yt(g),u({id:`group-id-${o}`,filters:{},intervals:[]}),i(v=>v+1)},children:s.jsx(yf,{})}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{type:"submit",children:"Save"})})]});function c(){const g=n.flatMap(v=>v.intervals).filter(v=>!zH(v));e.onSubmit({...t,qualifiedInterval:g})}function u(g){r(v=>[...v,g])}function d(g){r(v=>v.filter(S=>S.id!==g.id))}function f(g,v){r(S=>{S=[...S];const y=S.find(b=>b.id===g),w=y==null?void 0:y.intervals.findIndex(b=>b.id===v.id);return w!==void 0&&(y!=null&&y.intervals[w])&&(y.intervals[w]=v),S})}function h(g,v){v.id===void 0&&(v.id=`id-${a}`,l(S=>S+1)),r(S=>{S=[...S];const y=S.findIndex(w=>w.id===g);if(y!==-1){const w={...S[y]};v={...v,...w.filters},w.intervals=[...w.intervals,v],S[y]=w}return S})}function m(g,v){r(S=>{S=[...S];const y=S.find(w=>w.id===g);return y&&(y.intervals=y.intervals.filter(w=>w.id!==v.id)),S})}}function NH(e){const{intervalGroup:t,unit:n}=e;return s.jsx(yu,{"data-testid":t.id,className:_H.section,children:s.jsxs(Oe,{gap:"lg",children:[s.jsx(te,{justify:"flex-end",children:s.jsx(tn,{title:"Remove Group",variant:"subtle","data-testid":`remove-group-button-${t.id}`,size:"sm",onClick:r=>{yt(r),e.onRemoveGroup(t)},children:s.jsx(vf,{})},`remove-group-button-${t.id}`)}),s.jsx(MH,{intervalGroup:t,onChange:e.onChange}),s.jsx(cn,{}),t.intervals.map(r=>s.jsxs(Oe,{gap:"xs",children:[s.jsxs(te,{children:[s.jsx(ve,{"data-testid":`condition-${r.id}`,defaultValue:r.condition,label:"Condition: ",size:"sm",onChange:o=>{yt(o),e.onChange(t.id,{...r,condition:o.currentTarget.value.trim()})}},`condition-${r.id}`),s.jsx(tn,{title:"Remove Interval",variant:"subtle",size:"sm","data-testid":`remove-interval-${r.id}`,onClick:o=>{yt(o),e.onRemove(t.id,r)},children:s.jsx(vf,{})},`remove-interval-${r.id}`)]}),s.jsx(Zx,{path:"",onChange:o=>{e.onChange(t.id,{...r,range:o})},name:`range-${r.id}`,defaultValue:r.range},`range-${r.id}`)]},`interval-${r.id}`)),s.jsx(tn,{title:"Add Interval",variant:"subtle",size:"sm",onClick:r=>{yt(r),e.onAdd(t.id,{range:{low:{unit:n},high:{unit:n}}})},children:s.jsx(yf,{})})]})})}function MH(e){var r,o;const{intervalGroup:t,onChange:n}=e;t.filters.age||(t.filters.age={});for(const i of["low","high"])(r=t.filters.age[i])!=null&&r.unit||(t.filters.age[i]={...t.filters.age[i],unit:"years",system:"http://unitsofmeasure.org"});return s.jsxs(Oe,{style:{maxWidth:"50%"},children:[s.jsx(te,{children:s.jsx(It,{data:["","male","female"],label:"Gender:",defaultValue:t.filters.gender||"",onChange:i=>{for(const a of t.intervals){let l=i.currentTarget.value;l===""&&(l=void 0),n(t.id,{...a,gender:l})}}})}),s.jsxs(te,{gap:"xs",children:[s.jsx(fe,{component:"label",htmlFor:`div-age-${t.id}`,children:"Age:"}),s.jsx("div",{id:`div-age-${t.id}`,children:s.jsx(Zx,{path:"",name:`age-${t.id}`,defaultValue:t.filters.age,onChange:i=>{for(const a of t.intervals)n(t.id,{...a,age:i})}},`age-${t.id}`)})]}),s.jsx(It,{data:["","pre-puberty","follicular","midcycle","luteal","postmenopausal"],label:"Endocrine:",defaultValue:((o=t.filters.context)==null?void 0:o.text)||"",onChange:i=>{for(const a of t.intervals){let l=i.currentTarget.value;l===""?(l=void 0,n(t.id,{...a,context:void 0})):n(t.id,{...a,context:{text:l,coding:[{code:l,system:"http://terminology.hl7.org/CodeSystem/referencerange-meaning"}]}})}}}),s.jsx(It,{data:["","reference","critical","absolute"],label:"Category: ",defaultValue:t.filters.category,onChange:i=>{for(const a of t.intervals){const l=i.currentTarget.value;l===""?n(t.id,{...a,category:void 0}):n(t.id,{...a,category:l})}}})]})}function OH(e,t){const n=e.qualifiedInterval||[];let r=Math.max(...n.map(o=>{var a;const i=parseInt(((a=o.id)==null?void 0:a.substring(3))||"",10);return isNaN(i)?Number.NEGATIVE_INFINITY:i}))+1;return Number.isFinite(r)||(r=1),e={...e,qualifiedInterval:n.map(o=>({...o,id:o.id||`id-${r++}`}))},t(r),e}function LH(e,t){let n=1;const r={};for(const o of e){const i=$H(o);i in r||(r[i]={id:`group-id-${n++}`,filters:Object.fromEntries(DH.map(a=>[a,o[a]])),intervals:[]}),r[i].intervals.push(o)}return t(n),Object.values(r)}function $H(e){var n,r;return[`gender=${e.gender}`,`age=${Mc(e.age)}`,`gestationalAge=${Mc(e.gestationalAge)}`,`context=${(n=e.context)==null?void 0:n.text}`,`appliesTo=${(r=e.appliesTo)==null?void 0:r.map(o=>o.text).join("+")}`,`category=${e.category}`].join(":")}function FH(e){return e&&(v6(e,"http://unitsofmeasure.org")||e.text)}function zH(e){var t,n,r,o;return((n=(t=e.range)==null?void 0:t.low)==null?void 0:n.value)===void 0&&((o=(r=e.range)==null?void 0:r.high)==null?void 0:o.value)===void 0}function BH(e){var u;const t=se(),n=wt(e.value),[r,o]=p.useState(!1),[i,a]=p.useState();if(p.useEffect(()=>{n&&!r&&(t.executeBatch(l(n)).then(a).catch(console.log),o(!0))},[t,n,r]),!n||!i)return null;return s.jsx(ur,{children:(u=n.action)==null?void 0:u.map((d,f)=>{var v,S,y,w,b,x;const h=d.resource&&c(d.resource),m=(S=(v=h==null?void 0:h.input)==null?void 0:v[0])==null?void 0:S.valueReference,g=(w=(y=h==null?void 0:h.output)==null?void 0:y[0])==null?void 0:w.valueReference;return s.jsxs(p.Fragment,{children:[s.jsx(ur.Col,{span:1,p:"md",children:(h==null?void 0:h.status)==="completed"?s.jsx(sz,{}):s.jsx(Dz,{color:"gray"})}),s.jsxs(ur.Col,{span:9,p:"xs",children:[s.jsx(fe,{fw:500,children:d.title}),d.description&&s.jsx("div",{children:d.description}),s.jsxs("div",{children:["Last edited by ",s.jsx(Cl,{value:(b=h==null?void 0:h.meta)==null?void 0:b.author})," on ",Fn((x=h==null?void 0:h.meta)==null?void 0:x.lastUpdated)]}),s.jsxs("div",{children:["Status: ",s.jsx(n0,{status:(h==null?void 0:h.status)||"unknown"})]})]}),s.jsxs(ur.Col,{span:2,p:"md",children:[m&&!g&&s.jsx(oe,{onClick:()=>e.onStart(h,m),children:"Start"}),m&&g&&s.jsx(oe,{onClick:()=>e.onEdit(h,m,g),children:"Edit"})]})]},`action-${f}`)})});function l(d){var h;const f=[];if(d.action)for(const m of d.action)(h=m.resource)!=null&&h.reference&&f.push({request:{method:"GET",url:m.resource.reference}});return{resourceType:"Bundle",type:"batch",entry:f}}function c(d){for(const f of i==null?void 0:i.entry)if(f.resource&&d.reference===st(f.resource))return f.resource}}function HR(e,t){const n=UH(e,t);return VH(n,e,t)}function UH(e,t){const n=e.length,r=t.length,o=n+r+1,i=1+2*o,a=i/2|0,l=new Array(i);l[a+1]={i:0,j:-1,prev:void 0,snake:!0};for(let c=0;c<o;c++){for(let u=-c;u<=c;u+=2){const d=a+u,f=d+1,h=d-1,m=l[f],g=l[h];let v,S=0;u===-c||u!==c&&g.i<m.i?(S=m.i,v=m):(S=g.i+1,v=g),l[h]=void 0;let y=S-u,w={i:S,j:y,prev:WH(v),snake:!1};for(;S<n&&y<r&&e[S]===t[y];)S++,y++;if(S>w.i&&(w={i:S,j:y,prev:w,snake:!0}),l[d]=w,S>=n&&y>=r)return l[d]}l[a+c-1]=void 0}}function VH(e,t,n){const r=[];let o=e;for(o.snake&&(o=o.prev);o!=null&&o.prev&&o.prev.j>=0;){const i=o.i,a=o.j;o=o.prev;const l=o.i,c=o.j,u={position:l,lines:t.slice(l,i)},d={position:c,lines:n.slice(c,a)};let f;u.lines.length===0&&d.lines.length>0?f="insert":u.lines.length>0&&d.lines.length===0?f="delete":f="change",r.push({original:u,revised:d,type:f}),o.snake&&(o=o.prev)}return r}function WH(e){return e&&!e.snake&&e.prev?e.prev:e}function HH(e){const t=e.entry.filter(r=>!!r.resource).map(r=>{var o;return{meta:(o=r.resource)==null?void 0:o.meta,lines:pr(r.resource,!0).match(/[^\r\n]+/g)}}).sort((r,o)=>r.meta.lastUpdated.localeCompare(o.meta.lastUpdated)),n=t[0].lines.map(r=>({id:t[0].meta.versionId,meta:t[0].meta,value:r,span:1}));return qH(n,t),GH(n),n}function qH(e,t){for(let n=1;n<t.length;n++){const r=HR(t[n-1].lines,t[n].lines);for(const o of r){const i=o.original.position,a=o.original.lines,l=o.revised.lines;if((o.type==="delete"||o.type==="change")&&e.splice(i,a.length),o.type==="insert"||o.type==="change")for(let c=0;c<o.revised.lines.length;c++)e.splice(i+c,0,{id:t[n].meta.versionId,meta:t[n].meta,value:l[c],span:1})}}}function GH(e){let t=0;for(;t<e.length;){let n=t;for(;n<e.length&&e[n].id===e[t].id;)e[n].span=-1,n++;e[t].span=n-t,t=n}}const QH="_container_1oj0p_1",KH="_root_1oj0p_5",YH="_startRow_1oj0p_20",XH="_normalRow_1oj0p_24",JH="_author_1oj0p_28",ZH="_dateTime_1oj0p_32",eq="_lineNumber_1oj0p_37",tq="_line_1oj0p_37",nq="_pre_1oj0p_52",Co={container:QH,root:KH,startRow:YH,normalRow:XH,author:JH,dateTime:ZH,lineNumber:eq,line:tq,pre:nq};function rq(e,t){return`/${e.resourceType}/${e.id}/_history/${t}`}function oq(e){const t=Math.floor((Date.now()-Date.parse(e))/1e3),n=Math.floor(t/31536e3);if(n>0)return fa(n,"year");const r=Math.floor(t/2592e3);if(r>0)return fa(r,"month");const o=Math.floor(t/86400);if(o>0)return fa(o,"day");const i=Math.floor(t/3600);if(i>0)return fa(i,"hour");const a=Math.floor(t/60);return a>0?fa(a,"minute"):fa(t,"second")}function fa(e,t){return`${e} ${e===1?t:t+"s"} ago`}function iq(e){var a,l;const t=se(),[n,r]=p.useState(e.history);if(p.useEffect(()=>{!e.history&&e.resourceType&&e.id&&t.readHistory(e.resourceType,e.id).then(r).catch(console.log)},[t,e.history,e.resourceType,e.id]),!n)return s.jsx("div",{children:"Loading..."});const o=(l=(a=n.entry)==null?void 0:a[0])==null?void 0:l.resource;if(!o)return null;const i=HH(n);return s.jsx("div",{className:Co.container,children:s.jsx("table",{className:Co.root,children:s.jsx("tbody",{children:i.map((c,u)=>s.jsxs("tr",{className:c.span>0?Co.startRow:Co.normalRow,children:[c.span>0&&s.jsxs(s.Fragment,{children:[s.jsx("td",{className:Co.author,rowSpan:c.span,children:s.jsx(Ua,{value:c.meta.author,link:!0})}),s.jsx("td",{className:Co.dateTime,rowSpan:c.span,children:s.jsx(Ge,{to:rq(o,c.meta.versionId),children:oq(c.meta.lastUpdated)})})]}),s.jsx("td",{className:Co.lineNumber,children:u+1}),s.jsx("td",{className:Co.line,children:s.jsx("pre",{className:Co.pre,children:c.value})})]},"row-"+u))})})})}const sq="_removed_mgz0k_2",aq="_added_mgz0k_7",Bw={removed:sq,added:aq};function lq(e){let t=e.original,n=e.revised;e.ignoreMeta&&(t={...t,meta:void 0},n={...n,meta:void 0});const r=pr(t,!0).match(/[^\r\n]+/g),o=pr(n,!0).match(/[^\r\n]+/g),i=HR(r,o);return s.jsx("pre",{style:{color:"gray"},children:i.map((a,l)=>s.jsx(cq,{delta:a},"delta"+l))})}function cq(e){return s.jsxs(s.Fragment,{children:["...",s.jsx("br",{}),e.delta.original.lines.length>0&&s.jsx("div",{className:Bw.removed,children:e.delta.original.lines.join(`
541
+ }`.replace(/\s+/g," ");return(await e.graphql(r)).data.StructureDefinitionList[0]}function vU(e){return e.type==="profile"&&!(e!=null&&e.error)&&Gt(e.resourceType)}const yU="_indented_ldk1d_1",tR={indented:yU};function nR({propertyDisplayName:e,onClick:t,testId:n}){const r=e?`Add ${e}`:"Add";return e?s.jsx(oe,{title:r,size:"sm",color:"green.6",variant:"subtle","data-testid":n,leftSection:s.jsx(yf,{size:"1.25rem"}),onClick:t,children:r}):s.jsx(tn,{title:r,color:"green.6","data-testid":n,onClick:t,children:s.jsx(yf,{size:"1.25rem"})})}function rR({propertyDisplayName:e,onClick:t,testId:n}){return s.jsx(tn,{title:e?`Remove ${e}`:"Remove",color:"red.5","data-testid":n,variant:"subtle",onClick:t,children:s.jsx(vf,{size:"1.25rem"})})}function xU(e){var m,g;const{slice:t,property:n}=e,[r,o]=p.useState(e.defaultValue),i=((m=t.typeSchema)==null?void 0:m.elements)??t.elements,a=p.useContext(bt),l=p.useMemo(()=>{var v;if(Bt(i))return rl({parentContext:a,elements:i,path:e.path,profileUrl:(v=t.typeSchema)==null?void 0:v.url})},[a,e.path,(g=t.typeSchema)==null?void 0:g.url,i]);function c(v){o(v),e.onChange&&e.onChange(v)}const u=t.min>0,d=Gt(t.elements),f=ck(t.name),h=e.property.readonly&&r.length===0;return Fh(bt.Provider,l,s.jsx(vt,{title:f,description:t.definition,withAsterisk:u,fhirPath:`${n.path}:${t.name}`,testId:e.testId,readonly:e.property.readonly,children:h?s.jsx(fe,{c:"dimmed",children:"(empty)"}):s.jsxs(Oe,{className:d?tR.indented:void 0,children:[r.map((v,S)=>s.jsxs(te,{wrap:"nowrap",children:[s.jsx("div",{style:{flexGrow:1},"data-testid":e.testId&&`${e.testId}-elements-${S}`,children:s.jsx(e0,{elementDefinitionType:t.type[0],name:t.name,defaultValue:v,onChange:y=>{const w=[...r];w[S]=y,c(w)},outcome:e.outcome,min:t.min,max:t.max,binding:t.binding,path:e.path,valuePath:void 0,readOnly:e.property.readonly})}),!e.property.readonly&&r.length>t.min&&s.jsx(rR,{propertyDisplayName:f,testId:e.testId&&`${e.testId}-remove-${S}`,onClick:y=>{yt(y);const w=[...r];w.splice(S,1),c(w)}})]},`${S}-${r.length}`)),!e.property.readonly&&r.length<t.max&&s.jsx(te,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:s.jsx(nR,{propertyDisplayName:f,onClick:v=>{yt(v);const S=[...r,void 0];c(S)},testId:e.testId&&`${e.testId}-add`})})]})}))}function bU(e,t,n){return t===void 0?e:n===void 0?t:`${t}[${n}]`}function wU(e){var w;const{property:t}=e,n=se(),[r,o]=p.useState(!0),[i,a]=p.useState([]),[l]=p.useState(()=>Array.isArray(e.defaultValue)?e.defaultValue:[]),[c,u]=p.useState(()=>[l]),d=p.useContext(bt),f=(w=t.type[0])==null?void 0:w.code;p.useEffect(()=>{Wk({medplum:n,property:t}).then(b=>{a(b);const x=Vk(l,b,t.slicing,d.profileUrl);SU(x,b),u(x),o(!1)}).catch(b=>{console.error(b),o(!1)})},[n,t,l,d.profileUrl,u]);function h(b,x){const C=[...c];if(C[x]=b,u(C),e.onChange){const j=C.flat().filter(T=>T!==void 0);e.onChange(j)}}if(r)return s.jsx("div",{children:"Loading..."});const m=i.length,g=c[m],v=!(e.hideNonSliceValues??(f==="Extension"&&i.length>0)),S=Rs(t.path),y=e.property.readonly&&i.length===0&&l.length===0;return s.jsxs(Oe,{className:e.indent?tR.indented:void 0,children:[y&&s.jsx(fe,{c:"dimmed",children:"(empty)"}),i.map((b,x)=>s.jsx(xU,{slice:b,path:e.path,valuePath:e.valuePath,property:t,defaultValue:c[x],onChange:C=>{h(C,x)},testId:`slice-${b.name}`},b.name)),v&&g.map((b,x)=>s.jsxs(te,{wrap:"nowrap",style:{flexGrow:1},children:[s.jsx("div",{style:{flexGrow:1},children:s.jsx(jl,{arrayElement:!0,property:e.property,name:e.name+"."+x,path:e.path,valuePath:bU(e.path,e.valuePath,x),defaultValue:b,onChange:C=>{const j=[...g];j[x]=C,h(j,m)},defaultPropertyType:void 0,outcome:e.outcome})}),!e.property.readonly&&s.jsx(rR,{propertyDisplayName:S,testId:`nonsliced-remove-${x}`,onClick:C=>{yt(C);const j=[...g];j.splice(x,1),h(j,m)}})]},`${x}-${g.length}`)),!e.property.readonly&&v&&c.flat().length<t.max&&s.jsx(te,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:s.jsx(nR,{propertyDisplayName:S,onClick:b=>{yt(b);const x=[...g];x.push(void 0),h(x,m)},testId:"nonsliced-add"})})]})}function SU(e,t){for(let n=0;n<t.length;n++){const r=t[n],o=e[n];for(;o.length<r.min;)o.push(void 0)}}function jU(e){const[t,n]=p.useState(!1),r=ZS(),o=p.useRef(null),i={...e.styles};return t||(i.input||(i.input={}),i.input.WebkitTextSecurity="disc"),s.jsxs(Es,{gap:"xs",children:[s.jsx(Us,{...e,styles:{...i,root:{...i.root??{},flexGrow:1}},ref:o,autosize:!0,minRows:1,onFocus:()=>n(!0),onBlur:()=>n(!1)}),s.jsx(tn,{title:"Copy secret",onClick:()=>{var a;r.copy((a=o.current)==null?void 0:a.value),he({color:"green",message:"Copied"})},children:s.jsx(Ak,{})})]})}const CU=["sun","mon","tue","wed","thu","fri","sat"];function EU(e){const[t,n]=p.useState(e.defaultValue),[r,o]=p.useState(!e.disabled&&(e.defaultModalOpen??!1)),i=p.useRef();return i.current=t,s.jsxs(s.Fragment,{children:[s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx("span",{children:sk(i.current)||"No repeat"}),s.jsx(oe,{disabled:e.disabled,onClick:()=>o(!0),children:"Edit"})]}),!e.disabled&&s.jsx(TU,{path:e.path,visible:r,defaultValue:i.current,onOk:a=>{e.onChange&&e.onChange(a),n(a),o(!1)},onCancel:()=>o(!1)})]})}const kw={repeat:{period:1,periodUnit:"d"}};function TU(e){const[t,n]=p.useState(e.defaultValue||kw),{getExtendedProps:r}=p.useContext(bt),[o,i,a,l,c]=p.useMemo(()=>["event","repeat","repeat.period","repeat.periodUnit","repeat.dayOfWeek"].map(v=>r(e.path+"."+v)),[r,e.path]),u=p.useRef();u.current=t;function d(v){n({...u.current,event:[v]})}function f(v){n({...u.current,repeat:v})}function h(v){var S;f({...(S=u.current)==null?void 0:S.repeat,period:v})}function m(v){var S;f({...(S=u.current)==null?void 0:S.repeat,periodUnit:v})}function g(v){var S;f({...(S=u.current)==null?void 0:S.repeat,dayOfWeek:v})}return s.jsx(wn,{title:"Timing",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:()=>e.onCancel(),children:s.jsxs(Oe,{children:[s.jsx(vt,{title:"Starts on",htmlFor:"timing-dialog-start",children:s.jsx(_s,{disabled:o==null?void 0:o.readonly,name:"timing-dialog-start",onChange:v=>d(v)})}),s.jsx(lu,{disabled:i==null?void 0:i.readonly,label:"Repeat",checked:!!t.repeat,onChange:v=>f(v.currentTarget.checked?kw.repeat:void 0)}),t.repeat&&s.jsxs(s.Fragment,{children:[s.jsx(vt,{title:"Repeat every",htmlFor:"timing-dialog-period",children:s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(ve,{disabled:a==null?void 0:a.readonly,type:"number",step:1,id:"timing-dialog-period",name:"timing-dialog-period",defaultValue:t.repeat.period||1,onChange:v=>h(parseInt(v.currentTarget.value,10)||1)}),s.jsx(It,{disabled:l==null?void 0:l.readonly,id:"timing-dialog-periodUnit",name:"timing-dialog-periodUnit",defaultValue:t.repeat.periodUnit,onChange:v=>m(v.currentTarget.value),data:[{label:"second",value:"s"},{label:"minute",value:"min"},{label:"hour",value:"h"},{label:"day",value:"d"},{label:"week",value:"wk"},{label:"month",value:"mo"},{label:"year",value:"a"}]})]})}),t.repeat.periodUnit==="wk"&&s.jsx(vt,{title:"Repeat on",children:s.jsx(_c.Group,{multiple:!0,onChange:g,children:s.jsx(te,{justify:"space-between",mt:"md",gap:"xs",children:CU.map(v=>s.jsx(_c,{value:v,size:"xs",radius:"xl",disabled:c==null?void 0:c.readonly,children:v.charAt(0).toUpperCase()},v))})})})]}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{onClick:()=>e.onOk(t),children:"OK"})})]})})}function jl(e){var l;const{property:t,name:n,onChange:r,defaultValue:o}=e,i=e.defaultPropertyType&&e.defaultPropertyType!=="undefined"?e.defaultPropertyType:t.type[0].code,a=t.type;if((t.isArray||t.max>1)&&!e.arrayElement){if(i===H.Attachment)return s.jsx(NB,{name:n,defaultValue:o,onChange:r,disabled:t.readonly});const c=((l=a[0])==null?void 0:l.code)!==H.Extension;return s.jsx(wU,{property:t,name:n,path:e.path,valuePath:e.valuePath,defaultValue:o,indent:c,onChange:r,outcome:e.outcome})}else return a.length>1?s.jsx(PU,{elementDefinitionTypes:a,...e}):s.jsx(e0,{name:n,defaultValue:o,onChange:c=>{if(e.onChange){const u=e.name.replace("[x]",nn(a[0].code));e.onChange(c,u)}},outcome:e.outcome,elementDefinitionType:a[0],min:t.min,max:t.min,binding:t.binding,path:e.path,valuePath:e.valuePath,readOnly:t.readonly})}function PU(e){const t=e.elementDefinitionTypes;let n;e.defaultPropertyType&&(n=t.find(i=>i.code===e.defaultPropertyType)),n||(n=t[0]);const[r,o]=p.useState(n);return s.jsxs(te,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[s.jsx(It,{disabled:e.property.readonly,style:{width:"200px"},defaultValue:r.code,"data-testid":e.name&&e.name+"-selector",onChange:i=>{o(t.find(a=>a.code===i.currentTarget.value))},data:t.map(i=>({value:i.code,label:i.code}))}),s.jsx(e0,{name:e.name,defaultValue:e.defaultValue,outcome:e.outcome,elementDefinitionType:r,onChange:i=>{e.onChange&&e.onChange(i,e.name.replace("[x]",nn(r.code)))},min:e.property.min,max:e.property.max,binding:e.property.binding,path:e.property.path,valuePath:e.valuePath,readOnly:e.property.readonly})]})}function e0(e){const{name:t,onChange:n,outcome:r,binding:o,path:i,valuePath:a,readOnly:l}=e,c=e.min!==void 0&&e.min>0,u=e.elementDefinitionType.code,d=p.useContext(bt),f=p.useMemo(()=>{if(!Px(u)||!Gt(e.defaultValue))return e.defaultValue;const g=Object.create(null);if(d.path===e.path)mw(g,d.elements);else{const v=Ac(d.path,e.path);if(v===void 0)return e.defaultValue;mw(g,d.elements,v)}return Bt(g)?g:e.defaultValue},[u,d.path,d.elements,e.path,e.defaultValue]);if(!u)return s.jsx("div",{children:"Property type not specified "});function h(){return{name:t,defaultValue:f,onChange:n,outcome:r,path:i,valuePath:a,disabled:l}}function m(){const g=Je(e.outcome,a??i);return{id:t,name:t,"data-testid":t,defaultValue:f,required:c,error:g,disabled:l}}switch(u){case H.SystemString:case H.canonical:case H.string:case H.time:case H.uri:case H.url:return e.path==="Project.secret.value[x]"?s.jsx(jU,{...m(),onChange:g=>{e.onChange&&e.onChange(g.currentTarget.value)}}):s.jsx(ve,{...m(),onChange:g=>{n&&n(g.currentTarget.value)}});case H.date:return s.jsx(ve,{...m(),type:"date",onChange:g=>{n&&n(g.currentTarget.value)}});case H.dateTime:case H.instant:return s.jsx(_s,{...m(),onChange:n,outcome:r});case H.decimal:case H.integer:case H.positiveInt:case H.unsignedInt:return s.jsx(ve,{...m(),type:"number",step:u===H.decimal?"any":"1",onChange:g=>{if(n){const v=g.currentTarget.valueAsNumber;n(Number.isNaN(v)?void 0:v)}}});case H.code:return s.jsx(zk,{...m(),error:void 0,onChange:n,binding:o==null?void 0:o.valueSet});case H.boolean:return s.jsx(_n,{...m(),defaultChecked:!!f,onChange:g=>{n&&n(g.currentTarget.checked)}});case H.base64Binary:case H.markdown:return s.jsx(Us,{...m(),spellCheck:u!==H.base64Binary,onChange:g=>{n&&n(g.currentTarget.value)}});case H.Address:return s.jsx(G8,{...h()});case H.Annotation:return s.jsx(Q8,{...h()});case H.Attachment:return s.jsx(Bk,{...h()});case H.CodeableConcept:return s.jsx(GB,{binding:o==null?void 0:o.valueSet,...h()});case H.Coding:return s.jsx(Jk,{binding:o==null?void 0:o.valueSet,...h()});case H.ContactDetail:return s.jsx(JB,{...h()});case H.ContactPoint:return s.jsx(Zk,{...h()});case H.Extension:return s.jsx(tU,{...h(),propertyType:e.elementDefinitionType});case H.HumanName:return s.jsx(nU,{...h()});case H.Identifier:return s.jsx(rU,{...h()});case H.Money:return s.jsx(iU,{...h()});case H.Period:return s.jsx(sU,{...h()});case H.Duration:case H.Quantity:return s.jsx(Ds,{...h()});case H.Range:return s.jsx(Zx,{...h()});case H.Ratio:return s.jsx(lU,{...h()});case H.Reference:return s.jsx(zh,{...h(),targetTypes:RU(e.elementDefinitionType)});case H.Timing:return s.jsx(EU,{...h()});case H.Dosage:case H.UsageContext:default:return s.jsx(t0,{...h(),typeName:u})}}const kU=[`${A$}/fhir/StructureDefinition/`,"https://medplum.com/fhir/StructureDefinition/"];function RU(e){var t;return(t=e==null?void 0:e.targetProfile)==null?void 0:t.map(n=>{const r=kU.find(o=>n.startsWith(o));return r?n.slice(r.length):n})}function _U(e){const[t,n]=p.useState(e.defaultValue??{}),r=p.useContext(bt),o=p.useMemo(()=>q8(r.elements),[r.elements]);function i(l){n(l),e.onChange&&e.onChange(l)}const a={type:e.type,value:t};return s.jsx(Oe,{style:{flexGrow:1},"data-testid":e.testId,children:o.map(([l,c])=>{const[u,d]=UB(a,l,c),f=c.min!==void 0&&c.min>0,h=e.valuePath?e.valuePath+"."+l:void 0,m=s.jsx(jl,{property:c,name:l,path:e.path+"."+l,valuePath:h,defaultValue:u,defaultPropertyType:d,onChange:(g,v)=>{i(Xk({...t},l,v??l,c,g))},outcome:e.outcome},l);return e.type==="Extension"||zx.includes(l)?m:c.type.length===1&&c.type[0].code==="boolean"?s.jsx(Kk,{title:Rs(l),description:c.description,htmlFor:l,fhirPath:c.path,withAsterisk:f,readonly:c.readonly,children:m},l):s.jsx(vt,{title:Rs(l),description:c.description,withAsterisk:f,htmlFor:l,outcome:e.outcome,fhirPath:c.path,errorExpression:h,readonly:c.readonly,children:m},l)})})}function t0(e){const[t]=p.useState(()=>e.defaultValue??{}),n=p.useContext(bt),r=e.profileUrl??(n==null?void 0:n.profileUrl),o=p.useMemo(()=>Dh(e.typeName,r),[e.typeName,r]),i=(o==null?void 0:o.type)??e.typeName,a=p.useMemo(()=>{if(o)return rl({parentContext:n,elements:o.elements,path:e.path,profileUrl:o.url,accessPolicyResource:e.accessPolicyResource})},[o,n,e.path,e.accessPolicyResource]);return o?Fh(bt.Provider,a,s.jsx(_U,{path:e.path,valuePath:e.valuePath,type:i,defaultValue:t,onChange:e.onChange,outcome:e.outcome})):s.jsxs("div",{children:[i," not implemented"]})}const DU="_root_1vii2_1",IU={root:DU};function yu(e){const{children:t,...n}=e;return s.jsx(zy,{className:IU.root,...n,children:t})}const AU="_noteBody_10swh_1",NU="_noteCite_10swh_5",MU="_noteRoot_10swh_10",Rw={noteBody:AU,noteCite:NU,noteRoot:MU};function oR({value:e}){return e?s.jsx(Oe,{justify:"flex-start",gap:"xs",children:e.map(t=>{var n;return t.text&&s.jsx(Ly,{classNames:{cite:Rw.noteCite,root:Rw.noteRoot},cite:((n=t.authorReference)==null?void 0:n.display)||t.authorString,icon:null,children:t.text},`note-${t.text}`)})}):null}function Cl(e){const{value:t,link:n,...r}=e,[o,i]=p.useState(),a=wt(t,i);let l;if(o&&!UP(o))l=`[${De(o)}]`;else if(a)l=Wo(a);else return null;return n?s.jsx(Ge,{to:t,...r,children:l}):s.jsx(fe,{component:"span",...r,children:l})}function Ua(e){return s.jsxs(te,{gap:"xs",children:[s.jsx(Hi,{size:24,radius:12,value:e.value,link:e.link}),s.jsx(Cl,{value:e.value,link:e.link})]})}const OU={draft:"blue",active:"blue","on-hold":"yellow",revoked:"red",completed:"green","entered-in-error":"red",unknown:"gray",retired:"gray",registered:"blue",preliminary:"blue",final:"green",amended:"yellow",corrected:"yellow",cancelled:"red",requested:"blue",received:"blue",accepted:"blue",rejected:"red",ready:"blue","in-progress":"blue",failed:"red",proposed:"blue",pending:"blue",booked:"blue",arrived:"blue",fulfilled:"green",noshow:"red","checked-in":"blue",waitlist:"gray",routine:"gray",urgent:"red",asap:"red",stat:"red","not-done":"red",connected:"green",disconnected:"red"};function n0(e){return s.jsx(ru,{color:OU[e.status],children:e.status})}const LU="_table_pe9td_1",$U="_criticalRow_pe9td_12",FU="_noteBody_pe9td_23",zU="_noteCite_pe9td_27",BU="_noteRoot_pe9td_32",iR={table:LU,criticalRow:$U,noteBody:FU,noteCite:zU,noteRoot:BU};r0.defaultProps={hideObservationNotes:!1,hideSpecimenInfo:!1};function r0(e){var a;const t=se(),n=wt(e.value),[r,o]=p.useState();if(p.useEffect(()=>{n!=null&&n.specimen&&Promise.allSettled(n.specimen.map(l=>t.readReference(l))).then(l=>l.filter(c=>c.status==="fulfilled").map(c=>c.value)).then(o).catch(console.error)},[t,n]),!n)return null;const i=(r==null?void 0:r.flatMap(l=>l.note||[]))||[];if(n.presentedForm&&n.presentedForm.length>0){const l=n.presentedForm[0];(a=l.contentType)!=null&&a.startsWith("text/plain")&&l.data&&i.push({text:window.atob(l.data)})}return s.jsxs(Oe,{children:[s.jsx(ge,{children:"Diagnostic Report"}),s.jsx(UU,{value:n}),r&&!e.hideSpecimenInfo&&VU(r),n.result&&s.jsx(WU,{hideObservationNotes:e.hideObservationNotes,value:n.result}),i.length>0&&s.jsx(oR,{value:i})]})}function UU({value:e}){var t,n;return s.jsxs(te,{mt:"md",gap:30,children:[e.subject&&s.jsxs("div",{children:[s.jsx(fe,{size:"xs",tt:"uppercase",c:"dimmed",children:"Subject"}),s.jsx(Ua,{value:e.subject,link:!0})]}),(t=e.resultsInterpreter)==null?void 0:t.map(r=>s.jsxs("div",{children:[s.jsx(fe,{size:"xs",tt:"uppercase",c:"dimmed",children:"Interpreter"}),s.jsx(Ua,{value:r,link:!0})]},r.reference)),(n=e.performer)==null?void 0:n.map(r=>s.jsxs("div",{children:[s.jsx(fe,{size:"xs",tt:"uppercase",c:"dimmed",children:"Performer"}),s.jsx(Ua,{value:r,link:!0})]},r.reference)),e.issued&&s.jsxs("div",{children:[s.jsx(fe,{size:"xs",tt:"uppercase",c:"dimmed",children:"Issued"}),s.jsx(fe,{children:Fn(e.issued)})]}),e.status&&s.jsxs("div",{children:[s.jsx(fe,{size:"xs",tt:"uppercase",c:"dimmed",children:"Status"}),s.jsx(fe,{children:nn(e.status)})]})]})}function VU(e){return s.jsxs(Oe,{gap:"xs",children:[s.jsx(ge,{order:2,size:"h6",children:"Specimens"}),s.jsx(Ln,{type:"ordered",children:e==null?void 0:e.map(t=>{var n;return s.jsx(Ln.Item,{ml:"sm",children:s.jsxs(te,{gap:20,children:[s.jsxs(te,{gap:5,children:[s.jsx(fe,{fw:500,children:"Collected:"})," ",Fn((n=t.collection)==null?void 0:n.collectedDateTime)]}),s.jsxs(te,{gap:5,children:[s.jsx(fe,{fw:500,children:"Received:"})," ",Fn(t.receivedTime)]})]})},`specimen-${t.id}`)})})]})}function WU(e){return s.jsxs("table",{className:iR.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Test"}),s.jsx("th",{children:"Value"}),s.jsx("th",{children:"Reference Range"}),s.jsx("th",{children:"Interpretation"}),s.jsx("th",{children:"Category"}),s.jsx("th",{children:"Performer"}),s.jsx("th",{children:"Status"})]})}),s.jsx("tbody",{children:s.jsx(sR,{value:e.value,ancestorIds:e.ancestorIds,hideObservationNotes:e.hideObservationNotes})})]})}function sR(e){var t;return s.jsx(s.Fragment,{children:(t=e.value)==null?void 0:t.map(n=>s.jsx(HU,{value:n,ancestorIds:e.ancestorIds,hideObservationNotes:e.hideObservationNotes},`obs-${Qs(n)?n.reference:n.id}`))})}function HU(e){var o,i;const t=wt(e.value);if(!t||(o=e.ancestorIds)!=null&&o.includes(t.id))return null;const n=!e.hideObservationNotes&&t.note,r=QU(t);return s.jsxs(s.Fragment,{children:[s.jsxs("tr",{className:rt({[iR.criticalRow]:r}),children:[s.jsx("td",{rowSpan:n?2:1,children:s.jsx(Ge,{to:t,children:s.jsx(yo,{value:t.code})})}),s.jsx("td",{children:s.jsx(qU,{value:t})}),s.jsx("td",{children:s.jsx(GU,{value:t.referenceRange})}),s.jsx("td",{children:t.interpretation&&t.interpretation.length>0&&s.jsx(yo,{value:t.interpretation[0]})}),s.jsx("td",{children:t.category&&t.category.length>0&&s.jsx(s.Fragment,{children:t.category.map(a=>s.jsx("div",{children:s.jsx(yo,{value:a})},`category-${Oi(a)}`))})}),s.jsx("td",{children:(i=t.performer)==null?void 0:i.map(a=>s.jsx(bf,{value:a},a.reference))}),s.jsx("td",{children:t.status&&s.jsx(n0,{status:t.status})})]}),t.hasMember&&s.jsx(sR,{value:t.hasMember,ancestorIds:e.ancestorIds?[...e.ancestorIds,t.id]:[t.id],hideObservationNotes:e.hideObservationNotes}),n&&s.jsx("tr",{children:s.jsx("td",{colSpan:6,children:s.jsx(oR,{value:t.note})})})]})}function qU(e){const t=e.value;return s.jsx(s.Fragment,{children:ak(t)})}function GU(e){const t=e.value&&e.value.length>0&&e.value[0];return t?t.text?s.jsx(s.Fragment,{children:t.text}):s.jsx(Jx,{value:t}):null}function QU(e){var n,r,o,i;const t=(i=(o=(r=(n=e.interpretation)==null?void 0:n[0])==null?void 0:r.coding)==null?void 0:o[0])==null?void 0:i.code;return t==="AA"||t==="LL"||t==="HH"||t==="A"}const KU="_paper_1igaj_1",YU="_fill_1igaj_20",_w={paper:KU,fill:YU};function o0(e){const{width:t,fill:n,className:r,children:o,...i}=e,a=t?{maxWidth:t}:void 0;return s.jsx(Yn,{className:rt(_w.paper,n&&_w.fill,r),style:a,shadow:"sm",radius:"sm",withBorder:!0,...i,children:o})}var i0={},xu={};Object.defineProperty(xu,"__esModule",{value:!0});xu.Pointer=void 0;function XU(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function JU(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var ZU=function(){function e(t){t===void 0&&(t=[""]),this.tokens=t}return e.fromJSON=function(t){var n=t.split("/").map(XU);if(n[0]!=="")throw new Error("Invalid JSON Pointer: ".concat(t));return new e(n)},e.prototype.toString=function(){return this.tokens.map(JU).join("/")},e.prototype.evaluate=function(t){for(var n=null,r="",o=t,i=1,a=this.tokens.length;i<a;i++)n=o,r=this.tokens[i],!(r=="__proto__"||r=="constructor"||r=="prototype")&&(o=(n||{})[r]);return{parent:n,key:r,value:o}},e.prototype.get=function(t){return this.evaluate(t).value},e.prototype.set=function(t,n){var r=this.evaluate(t);r.parent&&(r.parent[r.key]=n)},e.prototype.push=function(t){this.tokens.push(t)},e.prototype.add=function(t){var n=this.tokens.concat(String(t));return new e(n)},e}();xu.Pointer=ZU;var Ht={},s0={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.clone=e.objectType=e.hasOwnProperty=void 0,e.hasOwnProperty=Object.prototype.hasOwnProperty;function t(o){return o===void 0?"undefined":o===null?"null":Array.isArray(o)?"array":typeof o}e.objectType=t;function n(o){return o!=null&&typeof o=="object"}function r(o){if(!n(o))return o;if(o.constructor==Array){for(var i=o.length,a=new Array(i),l=0;l<i;l++)a[l]=r(o[l]);return a}if(o.constructor==Date){var c=new Date(+o);return c}var u={};for(var d in o)e.hasOwnProperty.call(o,d)&&(u[d]=r(o[d]));return u}e.clone=r})(s0);var On={};Object.defineProperty(On,"__esModule",{value:!0});On.diffAny=On.diffObjects=On.diffArrays=On.intersection=On.subtract=On.isDestructive=void 0;var Fc=s0;function eV(e){var t=e.op;return t==="remove"||t==="replace"||t==="copy"||t==="move"}On.isDestructive=eV;function kg(e,t){var n={};for(var r in e)Fc.hasOwnProperty.call(e,r)&&e[r]!==void 0&&(n[r]=1);for(var o in t)Fc.hasOwnProperty.call(t,o)&&t[o]!==void 0&&delete n[o];return Object.keys(n)}On.subtract=kg;function aR(e){for(var t=e.length,n={},r=0;r<t;r++){var o=e[r];for(var i in o)Fc.hasOwnProperty.call(o,i)&&o[i]!==void 0&&(n[i]=(n[i]||0)+1)}for(var i in n)n[i]<t&&delete n[i];return Object.keys(n)}On.intersection=aR;function tV(e){return e.op==="add"}function nV(e){return e.op==="remove"}function Qp(e,t){return{operations:e.operations.concat(t),cost:e.cost+1}}function lR(e,t,n,r){r===void 0&&(r=Bh);var o={"0,0":{operations:[],cost:0}};function i(d,f){var h="".concat(d,",").concat(f),m=o[h];if(m===void 0){if(d>0&&f>0&&!r(e[d-1],t[f-1],n.add(String(d-1))).length)m=i(d-1,f-1);else{var g=[];if(d>0){var v=i(d-1,f),S={op:"remove",index:d-1};g.push(Qp(v,S))}if(f>0){var y=i(d,f-1),w={op:"add",index:d-1,value:t[f-1]};g.push(Qp(y,w))}if(d>0&&f>0){var b=i(d-1,f-1),x={op:"replace",index:d-1,original:e[d-1],value:t[f-1]};g.push(Qp(b,x))}var C=g.sort(function(j,T){return j.cost-T.cost})[0];m=C}o[h]=m}return m}var a=isNaN(e.length)||e.length<=0?0:e.length,l=isNaN(t.length)||t.length<=0?0:t.length,c=i(a,l).operations,u=c.reduce(function(d,f){var h=d[0],m=d[1];if(tV(f)){var g=f.index+1+m,v=g<a+m?String(g):"-",S={op:f.op,path:n.add(v).toString(),value:f.value};return[h.concat(S),m+1]}else if(nV(f)){var S={op:f.op,path:n.add(String(f.index+m)).toString()};return[h.concat(S),m-1]}else{var y=n.add(String(f.index+m)),w=r(f.original,f.value,y);return[h.concat.apply(h,w),m]}},[[],0])[0];return u}On.diffArrays=lR;function cR(e,t,n,r){r===void 0&&(r=Bh);var o=[];return kg(e,t).forEach(function(i){o.push({op:"remove",path:n.add(i).toString()})}),kg(t,e).forEach(function(i){o.push({op:"add",path:n.add(i).toString(),value:t[i]})}),aR([e,t]).forEach(function(i){o.push.apply(o,r(e[i],t[i],n.add(i)))}),o}On.diffObjects=cR;function Bh(e,t,n,r){if(r===void 0&&(r=Bh),e===t)return[];var o=(0,Fc.objectType)(e),i=(0,Fc.objectType)(t);return o=="array"&&i=="array"?lR(e,t,n,r):o=="object"&&i=="object"?cR(e,t,n,r):[{op:"replace",path:n.toString(),value:t}]}On.diffAny=Bh;var a0=P0&&P0.__extends||function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(r[i]=o[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(Ht,"__esModule",{value:!0});Ht.apply=Ht.InvalidOperationError=Ht.test=Ht.copy=Ht.move=Ht.replace=Ht.remove=Ht.add=Ht.TestError=Ht.MissingError=void 0;var Ho=xu,l0=s0,rV=On,xo=function(e){a0(t,e);function t(n){var r=e.call(this,"Value required at path: ".concat(n))||this;return r.path=n,r.name="MissingError",r}return t}(Error);Ht.MissingError=xo;var uR=function(e){a0(t,e);function t(n,r){var o=e.call(this,"Test failed: ".concat(n," != ").concat(r))||this;return o.actual=n,o.expected=r,o.name="TestError",o}return t}(Error);Ht.TestError=uR;function c0(e,t,n){if(Array.isArray(e))if(t=="-")e.push(n);else{var r=parseInt(t,10);e.splice(r,0,n)}else e[t]=n}function dR(e,t){if(Array.isArray(e)){var n=parseInt(t,10);e.splice(n,1)}else delete e[t]}function fR(e,t){var n=Ho.Pointer.fromJSON(t.path).evaluate(e);return n.parent===void 0?new xo(t.path):(c0(n.parent,n.key,(0,l0.clone)(t.value)),null)}Ht.add=fR;function hR(e,t){var n=Ho.Pointer.fromJSON(t.path).evaluate(e);return n.value===void 0?new xo(t.path):(dR(n.parent,n.key),null)}Ht.remove=hR;function pR(e,t){var n=Ho.Pointer.fromJSON(t.path).evaluate(e);if(n.parent===null)return new xo(t.path);if(Array.isArray(n.parent)){if(parseInt(n.key,10)>=n.parent.length)return new xo(t.path)}else if(n.value===void 0)return new xo(t.path);return n.parent[n.key]=(0,l0.clone)(t.value),null}Ht.replace=pR;function mR(e,t){var n=Ho.Pointer.fromJSON(t.from).evaluate(e);if(n.value===void 0)return new xo(t.from);var r=Ho.Pointer.fromJSON(t.path).evaluate(e);return r.parent===void 0?new xo(t.path):(dR(n.parent,n.key),c0(r.parent,r.key,n.value),null)}Ht.move=mR;function gR(e,t){var n=Ho.Pointer.fromJSON(t.from).evaluate(e);if(n.value===void 0)return new xo(t.from);var r=Ho.Pointer.fromJSON(t.path).evaluate(e);return r.parent===void 0?new xo(t.path):(c0(r.parent,r.key,(0,l0.clone)(n.value)),null)}Ht.copy=gR;function vR(e,t){var n=Ho.Pointer.fromJSON(t.path).evaluate(e);return(0,rV.diffAny)(n.value,t.value,new Ho.Pointer).length?new uR(n.value,t.value):null}Ht.test=vR;var yR=function(e){a0(t,e);function t(n){var r=e.call(this,"Invalid operation: ".concat(n.op))||this;return r.operation=n,r.name="InvalidOperationError",r}return t}(Error);Ht.InvalidOperationError=yR;function oV(e,t){switch(t.op){case"add":return fR(e,t);case"remove":return hR(e,t);case"replace":return pR(e,t);case"move":return mR(e,t);case"copy":return gR(e,t);case"test":return vR(e,t)}return new yR(t)}Ht.apply=oV;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createTests=e.createPatch=e.applyPatch=e.Pointer=void 0;var t=xu;Object.defineProperty(e,"Pointer",{enumerable:!0,get:function(){return t.Pointer}});var n=Ht,r=On;function o(u,d){return d.map(function(f){return(0,n.apply)(u,f)})}e.applyPatch=o;function i(u){function d(f,h,m){var g=u(f,h,m);return Array.isArray(g)?g:(0,r.diffAny)(f,h,m,d)}return d}function a(u,d,f){var h=new t.Pointer;return(f?i(f):r.diffAny)(u,d,h)}e.createPatch=a;function l(u,d){var f=t.Pointer.fromJSON(d).evaluate(u);if(f!==void 0)return{op:"test",path:d,value:f.value}}function c(u,d){var f=new Array;return d.filter(r.isDestructive).forEach(function(h){var m=l(u,h.path);if(m&&f.push(m),"from"in h){var g=l(u,h.from);g&&f.push(g)}}),f}e.createTests=c})(i0);const iV="_root_w6lfx_1",sV="_removed_w6lfx_16",aV="_added_w6lfx_21",Kp={root:iV,removed:sV,added:aV};function lV(e){const t=se(),{original:n,revised:r}=e,[o,i]=p.useState(!1);p.useEffect(()=>{t.requestSchema(e.original.resourceType).then(()=>i(!0)).catch(console.log)},[t,e.original.resourceType]);const a=p.useMemo(()=>{if(!o)return null;const l=[bo(n)],c=[bo(r)],u=[],d=cV(i0.createPatch(n,r));for(const f of d){const h=f.path,m=uV(h),g=dV(n.resourceType,m),v=f.op==="add"?void 0:Lc(m,l),S=f.op==="remove"?void 0:Lc(m,c);u.push({key:`op-${f.op}-${f.path}`,name:`${nn(f.op)} ${m}`,path:(g==null?void 0:g.path)??n.resourceType+"."+m,property:g,originalValue:Dw(g,v),revisedValue:Dw(g,S)})}return u},[o,n,r]);return a?s.jsxs(de,{className:Kp.root,children:[s.jsx(de.Thead,{children:s.jsxs(de.Tr,{children:[s.jsx(de.Th,{}),s.jsx(de.Th,{children:"Before"}),s.jsx(de.Th,{children:"After"})]})}),s.jsx(de.Tbody,{children:a.map(l=>s.jsxs(de.Tr,{children:[s.jsx(de.Td,{children:l.name}),s.jsx(de.Td,{className:Kp.removed,children:l.originalValue&&s.jsx(Zr,{path:l.path,property:l.property,propertyType:l.originalValue.type,value:l.originalValue.value,ignoreMissingValues:!0})}),s.jsx(de.Td,{className:Kp.added,children:l.revisedValue&&s.jsx(Zr,{path:l.path,property:l.property,propertyType:l.revisedValue.type,value:l.revisedValue.value,ignoreMissingValues:!0})})]},l.key))})]}):null}function cV(e){const t=[];for(const n of e){const{op:r,path:o}=n;if(o.startsWith("/meta/author")||o.startsWith("/meta/compartment")||o.startsWith("/meta/lastUpdated")||o.startsWith("/meta/versionId"))continue;const i=e.filter(l=>l.op===r&&l.path===o).length,a={op:r,path:o};i>1&&(r==="add"||r==="remove")&&/\/[0-9-]+$/.test(o)&&(a.op="replace",a.path=o.replace(/\/[^/]+$/,"")),t.some(l=>l.op===a.op&&l.path===a.path)||t.push(a)}return t}function uV(e){const t=e.split("/").filter(Boolean);let n="";for(let r=0;r<t.length;r++){const o=t[r];o==="-"?n+=".last()":/^\d+$/.test(o)?n+=`[${o}]`:(r>0&&(n+="."),n+=o)}return n.endsWith(".url")&&(n=n.replace(/\.url$/,"")),n}function dV(e,t){var r;const n=wl(e,{resourceType:"SearchParameter",base:[e],code:e+"."+t,expression:e+"."+t});return(r=n==null?void 0:n.elementDefinitions)==null?void 0:r[0]}function Dw(e,t){return t&&{type:Array.isArray(t)?t[0].type:t.type,value:fV(t,!!(e!=null&&e.isArray))}}function fV(e,t){const n=y6(e).flatMap(r=>r.value);return t?n:n[0]}function u0(e){const{profileUrl:t}=e,n=se(),r=n.getAccessPolicy(),o=wt(e.value),[i,a]=p.useState(!1);p.useEffect(()=>{if(o)if(t)n.requestProfileSchema(t,{expandProfile:!0}).then(()=>{yl(t)?a(!0):console.error(`Schema not found for ${t}`)}).catch(c=>{console.error("Error in requestProfileSchema",c)});else{const c=o.resourceType;n.requestSchema(c).then(()=>{a(!0)}).catch(console.error)}},[n,t,o]);const l=p.useMemo(()=>o&&gk(o,Ox.READ,r),[r,o]);return!i||!o?null:s.jsx(wf,{path:o.resourceType,value:{type:o.resourceType,value:e.forceUseInput?e.value:o},profileUrl:t,ignoreMissingValues:e.ignoreMissingValues,accessPolicyResource:l})}const hV="_item_5q6yx_1",pV="_itemPadding_5q6yx_5",Iw={item:hV,itemPadding:pV};function mV(e){return s.jsx(yu,{children:e.children})}function Is(e){var c,u;const{resource:t,profile:n,padding:r,popupMenuItems:o,...i}=e,a=n??((c=t.meta)==null?void 0:c.author),l=e.dateTime??((u=t.meta)==null?void 0:u.lastUpdated);return s.jsxs(o0,{"data-testid":"timeline-item",fill:!0,...i,children:[s.jsxs(te,{justify:"space-between",gap:8,mx:"xs",my:"sm",children:[s.jsx(Hi,{value:a,link:!0,size:"md"}),s.jsxs("div",{style:{flex:1},children:[s.jsx(fe,{size:"sm",children:s.jsx(Cl,{c:"dark",fw:500,value:a,link:!0})}),s.jsxs(fe,{size:"xs",children:[s.jsx(Ge,{c:"dimmed",to:e.resource,children:Fn(l)}),s.jsx(fe,{component:"span",c:"dimmed",mx:8,children:"·"}),s.jsx(Ge,{c:"dimmed",to:e.resource,children:e.resource.resourceType})]})]}),o&&s.jsxs(J,{position:"bottom-end",shadow:"md",width:200,children:[s.jsx(J.Target,{children:s.jsx(tn,{color:"gray",variant:"subtle",radius:"xl","aria-label":`Actions for ${st(e.resource)}`,children:s.jsx(dz,{})})}),o]})]}),s.jsx(Lk,{children:s.jsx("div",{className:rt(Iw.item,{[Iw.itemPadding]:r}),children:e.children})})]})}function xR(e,t){e.sort((n,r)=>{const o=Aw(n,t),i=Aw(r,t);return o>i?1:o<i?-1:Nw(n,t)-Nw(r,t)})}function Aw(e,t){if(!bR(e,t)){const n=e.priority;if(typeof n=="string")return{stat:4,asap:3,urgent:2}[n]??0}return 0}function Nw(e,t){var r;if(!bR(e,t)){if(e.resourceType==="Communication"&&e.sent)return new Date(e.sent).getTime();if((e.resourceType==="DiagnosticReport"||e.resourceType==="Media"||e.resourceType==="Observation")&&e.issued)return new Date(e.issued).getTime();if(e.resourceType==="DocumentReference"&&e.date)return new Date(e.date).getTime()}const n=(r=e.meta)==null?void 0:r.lastUpdated;return n?new Date(n).getTime():0}function bR(e,t){return!!t&&e.resourceType===t.resourceType&&e.id===t.id}const gV="_pinnedComment_5uxzi_2",vV={pinnedComment:gV};function Uh(e){const t=se(),n=t.getProfile(),r=p.useRef(null),o=wt(e.value),[i,a]=p.useState(),[l,c]=p.useState([]),u=e.loadTimelineResources,d=p.useRef(l);d.current=l;const f=p.useCallback(x=>{xR(x,o),x.reverse(),c(x)},[o]),h=p.useCallback(x=>{const C=[];for(const j of x){if(j.status!=="fulfilled")continue;const T=j.value;if(T.type==="history"&&a(T),T.entry)for(const E of T.entry)C.push(E.resource)}f(C)},[f]),m=p.useCallback(x=>f([...d.current,x]),[f]),g=p.useCallback(()=>{var j;let x,C;"resourceType"in e.value?(x=e.value.resourceType,C=e.value.id):[x,C]=(j=e.value.reference)==null?void 0:j.split("/"),u(t,x,C).then(h).catch(console.error)},[t,e.value,u,h]);p.useEffect(()=>g(),[g]);function v(x){!o||!e.createCommunication||t.createResource(e.createCommunication(o,n,x)).then(C=>m(C)).catch(console.error)}function S(x){!o||!e.createMedia||t.createResource(e.createMedia(o,n,x)).then(C=>m(C)).then(()=>Kl({id:"upload-notification",color:"teal",title:"Upload complete",message:"",icon:s.jsx(Ks,{size:16}),autoClose:2e3})).catch(C=>Kl({id:"upload-notification",color:"red",title:"Upload error",message:De(C),icon:s.jsx(ww,{size:16}),autoClose:2e3}))}function y(){he({id:"upload-notification",loading:!0,title:"Initializing upload...",message:"Please wait...",autoClose:!1,withCloseButton:!1})}function w(x){Kl({id:"upload-notification",loading:!0,title:"Uploading...",message:CV(x),autoClose:!1,withCloseButton:!1})}function b(x){Kl({id:"upload-notification",color:"red",title:"Upload error",message:De(x),icon:s.jsx(ww,{size:16}),autoClose:2e3})}return o?s.jsxs(mV,{children:[e.createCommunication&&s.jsx(o0,{children:s.jsx(Ke,{testid:"timeline-form",onSubmit:x=>{v(x.text);const C=r.current;C&&(C.value="",C.focus())},children:s.jsxs(te,{gap:"xs",wrap:"nowrap",style:{width:"100%"},children:[s.jsx(Hi,{value:n}),s.jsx(ve,{name:"text",ref:r,placeholder:"Add comment",style:{width:"100%",maxWidth:300}}),s.jsx(tn,{type:"submit",radius:"xl",color:"blue",variant:"filled",children:s.jsx(xz,{size:16})}),s.jsx(Xx,{securityContext:Et(o),onUpload:S,onUploadStart:y,onUploadProgress:w,onUploadError:b,children:x=>s.jsx(tn,{...x,radius:"xl",color:"blue",variant:"filled",children:s.jsx(Ux,{size:16})})})]})})}),l.map(x=>{var T;if(!x)return null;const C=`${x.resourceType}/${x.id}/${(T=x.meta)==null?void 0:T.versionId}`,j=e.getMenu?e.getMenu({primaryResource:o,currentResource:x,reloadTimeline:g}):void 0;if(x.resourceType===o.resourceType&&x.id===o.id)return s.jsx(yV,{history:i,resource:x,popupMenuItems:j},C);switch(x.resourceType){case"AuditEvent":return s.jsx(SV,{resource:x,popupMenuItems:j},C);case"Communication":return s.jsx(bV,{resource:x,popupMenuItems:j},C);case"DiagnosticReport":return s.jsx(jV,{resource:x,popupMenuItems:j},C);case"Media":return s.jsx(wV,{resource:x,popupMenuItems:j},C);default:return s.jsx(Is,{resource:x,padding:!0,children:s.jsx(u0,{value:x,ignoreMissingValues:!0})},C)}})]}):s.jsx(mn,{style:{width:"100%",height:"100%"},children:s.jsx(Zn,{})})}function yV(e){const{history:t,resource:n,...r}=e,o=xV(t,n);return o?s.jsx(Is,{resource:n,padding:!0,...r,children:s.jsx(lV,{original:o,revised:e.resource})}):s.jsxs(Is,{resource:n,padding:!0,...r,children:[s.jsx("h3",{children:"Created"}),s.jsx(u0,{value:n,ignoreMissingValues:!0,forceUseInput:!0})]})}function xV(e,t){const n=e.entry,r=n.findIndex(o=>{var i,a,l;return((a=(i=o.resource)==null?void 0:i.meta)==null?void 0:a.versionId)===((l=t.meta)==null?void 0:l.versionId)});if(!(r>=n.length-1))return n[r+1].resource}function bV(e){var r,o;const n=!e.resource.priority||e.resource.priority==="routine"?void 0:vV.pinnedComment;return s.jsx(Is,{resource:e.resource,profile:e.resource.sender,dateTime:e.resource.sent,padding:!0,className:n,popupMenuItems:e.popupMenuItems,children:s.jsx("p",{children:(o=(r=e.resource.payload)==null?void 0:r[0])==null?void 0:o.contentString})})}function wV(e){var r;const t=(r=e.resource.content)==null?void 0:r.contentType,n=t&&!t.startsWith("image/")&&!t.startsWith("video/")&&t!=="application/pdf";return s.jsx(Is,{resource:e.resource,padding:!!n,popupMenuItems:e.popupMenuItems,children:s.jsx(mu,{value:e.resource.content})})}function SV(e){return s.jsx(Is,{resource:e.resource,padding:!0,popupMenuItems:e.popupMenuItems,children:s.jsx(Ir,{children:s.jsx("pre",{children:e.resource.outcomeDesc})})})}function jV(e){return s.jsx(Is,{resource:e.resource,padding:!0,popupMenuItems:e.popupMenuItems,children:s.jsx(r0,{value:e.resource})})}function CV(e){if(e.lengthComputable){const t=100*e.loaded/e.total;return`Uploaded: ${Yp(e.loaded)} / ${Yp(e.total)} ${t.toFixed(2)}%`}return`Uploaded: ${Yp(e.loaded)}`}function Yp(e){if(e===0)return"0.00 B";const t=Math.floor(Math.log(e)/Math.log(1024));return(e/Math.pow(1024,t)).toFixed(2)+" "+" KMGTP".charAt(t)+"B"}function EV(e){const{resource:t,...n}=e;return s.jsx(Uh,{value:t,loadTimelineResources:async(r,o,i)=>{const a=`${o}/${i}`;return Promise.allSettled([r.readHistory(o,i),r.search("Task",{_filter:`based-on eq ${a} or focus eq ${a} or subject eq ${a}`,_count:100})])},...n})}function Ne(e){const{children:t,...n}=e;return s.jsx(yu,{children:s.jsx(o0,{...n,children:t})})}function TV(e){const{encounter:t,...n}=e;return s.jsx(Uh,{value:t,loadTimelineResources:async(r,o,i)=>Promise.allSettled([r.readHistory("Encounter",i),r.search("Communication","encounter=Encounter/"+i),r.search("Media","encounter=Encounter/"+i)]),createCommunication:(r,o,i)=>({resourceType:"Communication",status:"completed",encounter:Et(r),subject:r.subject,sender:Et(o),sent:new Date().toISOString(),payload:[{contentString:i}]}),createMedia:(r,o,i)=>({resourceType:"Media",status:"completed",encounter:Et(r),subject:r.subject,operator:Et(o),issued:new Date().toISOString(),content:i}),...n})}function PV(e){let t;try{t=bl(e.path,e.resource)}catch(n){return console.warn("FhirPathDisplay:",n),null}if(t.length>1)throw new Error(`Component "path" for "FhirPathDisplay" must resolve to a single element. Received ${t.length} elements [${JSON.stringify(t,null,2)}]`);return s.jsx(Zr,{value:t[0]||"",propertyType:e.propertyType})}function Mr(e){var n;const t=((n=e.outcome)==null?void 0:n.issue)||e.issues;return!t||t.length===0?null:s.jsx(Vi,{icon:s.jsx(Sl,{size:16}),color:"red",children:t.map(r=>{var o;return s.jsx("div",{"data-testid":"text-field-error",children:WP(r)},(o=r.details)==null?void 0:o.text)})})}function kV(e){return s.jsxs(wn,{title:"Export",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:e.onCancel,children:[s.jsxs(q,{display:"flex",style:{justifyContent:"space-between"},children:[e.exportCsv&&s.jsx(Mw,{text:"CSV",exportLogic:e.exportCsv,onCancel:e.onCancel}),e.exportTransactionBundle&&s.jsx(Mw,{text:"Transaction Bundle",exportLogic:e.exportTransactionBundle,onCancel:e.onCancel})]}),s.jsx(fe,{style:{marginTop:"10px",marginLeft:"2px"},children:"Limited to 1000 records"})]})}function Mw(e){return s.jsx(oe,{onClick:()=>{e.exportLogic(),e.onCancel()},children:`Export as ${e.text}`})}const RV={string:[re.EQUALS,re.NOT,re.CONTAINS,re.EXACT],fulltext:[re.EQUALS,re.NOT,re.CONTAINS,re.EXACT],token:[re.EQUALS,re.NOT],reference:[re.EQUALS,re.NOT],numeric:[re.EQUALS,re.NOT_EQUALS,re.GREATER_THAN,re.LESS_THAN,re.GREATER_THAN_OR_EQUALS,re.LESS_THAN_OR_EQUALS],quantity:[re.EQUALS,re.NOT_EQUALS,re.GREATER_THAN,re.LESS_THAN,re.GREATER_THAN_OR_EQUALS,re.LESS_THAN_OR_EQUALS],date:[re.EQUALS,re.NOT_EQUALS,re.GREATER_THAN,re.LESS_THAN,re.GREATER_THAN_OR_EQUALS,re.LESS_THAN_OR_EQUALS,re.STARTS_AFTER,re.ENDS_BEFORE,re.APPROXIMATELY],datetime:[re.EQUALS,re.NOT_EQUALS,re.GREATER_THAN,re.LESS_THAN,re.GREATER_THAN_OR_EQUALS,re.LESS_THAN_OR_EQUALS,re.STARTS_AFTER,re.ENDS_BEFORE,re.APPROXIMATELY]},_V={eq:"equals",ne:"not equals",gt:"greater than",lt:"less than",ge:"greater than or equals",le:"less than or equals",sa:"starts after",eb:"ends before",ap:"approximately",contains:"contains",exact:"exact",text:"text",not:"not",above:"above",below:"below",in:"in","not-in":"not in","of-type":"of type",missing:"missing",present:"present",identifier:"identifier",iterate:"iterate"};function d0(e,t){return{...e,filters:t,offset:0,name:void 0}}function wR(e,t){return d0(e,(e.filters??[]).filter(n=>n.code!==t))}function Vh(e,t,n,r,o){const i=[];return e.filters&&i.push(...e.filters),i.push({code:t,operator:n,value:r??""}),d0(e,i)}function DV(e,t){if(!e.filters)return e;const n=[...e.filters];return n.splice(t,1),{...e,filters:n,name:void 0}}function IV(e,t){return f0(e,t,-1)}function AV(e,t){return f0(e,t,0)}function NV(e,t){return f0(e,t,1)}function f0(e,t,n){const r=new Date;r.setDate(r.getDate()+n),r.setHours(0,0,0,0);const o=new Date(r.getTime());return o.setDate(o.getDate()+1),o.setTime(o.getTime()-1),p0(e,t,r,o)}function MV(e,t){return h0(e,t,-1)}function OV(e,t){return h0(e,t,0)}function LV(e,t){return h0(e,t,1)}function h0(e,t,n){const r=new Date;r.setMonth(r.getMonth()+n),r.setDate(1),r.setHours(0,0,0,0);const o=new Date(r.getTime());return o.setMonth(o.getMonth()+1),o.setDate(1),o.setHours(0,0,0,0),o.setTime(o.getTime()-1),p0(e,t,r,o)}function $V(e,t){const n=new Date;return n.setMonth(0),n.setDate(1),n.setHours(0,0,0,0),p0(e,t,n,new Date)}function p0(e,t,n,r){return e=wR(e,t),e=Ow(e,t,re.GREATER_THAN_OR_EQUALS,n),e=Ow(e,t,re.LESS_THAN_OR_EQUALS,r),e}function Ow(e,t,n,r){return Vh(e,t,n,r.toISOString())}function Lw(e,t,n=!0){return Vh(e,t,re.MISSING,n.toString())}function FV(e,t){return e.offset===t?e:{...e,offset:t,name:void 0}}function zV(e,t){const n=e.count??Ah,r=(t-1)*n;return FV(e,r)}function BV(e,t,n){return t===UV(e)&&n!==void 0&&n===VV(e)?e:{...e,sortRules:[{code:t,descending:!!n}],name:void 0}}function UV(e){const t=e.sortRules;if(!t||t.length===0)return;const n=t[0].code;return n.startsWith("-")?n.substr(1):n}function VV(e){const t=e.sortRules;return!t||t.length===0?!1:!!t[0].descending}function WV(e){return RV[e.type]}function m0(e){return _V[e]??""}function Li(e){let t=e;return t.includes(".")&&(t=t.split(".").pop()),t==="versionId"?"Version ID":(t=t.replace("[x]",""),t=t.replace(/([A-Z])/g," $1"),t=t.replace(/[-_]/g," "),t=t.replace(/\s+/g," "),t=t.trim(),t.toLowerCase()==="id"?"ID":t.split(/\s/).map(nn).join(" "))}function HV(e,t){var r,o;const n=t.name;return n==="id"?e.id:n==="meta.versionId"?(r=e.meta)==null?void 0:r.versionId:n==="_lastUpdated"?Fn((o=e.meta)==null?void 0:o.lastUpdated):t.elementDefinition&&`${e.resourceType}.${t.name}`===t.elementDefinition.path?qV(e,t.elementDefinition):t.searchParams&&t.searchParams.length===1&&t.name===t.searchParams[0].code?GV(e,t.searchParams[0]):null}function qV(e,t){var i,a,l;const n=((l=(a=(i=t.path)==null?void 0:i.split("."))==null?void 0:a.pop())==null?void 0:l.replaceAll("[x]",""))??"",[r,o]=gu({type:e.resourceType,value:e},n);return r?s.jsx(Zr,{path:t.path,property:t,propertyType:o,value:r,maxWidth:200,ignoreMissingValues:!0,link:!1}):null}function GV(e,t){const n=Lc(t.expression,[{type:e.resourceType,value:e}]);return!n||n.length===0?null:s.jsx(s.Fragment,{children:n.map((r,o)=>s.jsx(Zr,{propertyType:r.type,value:r.value,maxWidth:200,ignoreMissingValues:!0,link:!1},`${o}-${n.length}`))})}function QV(e){const t=p.useRef(!1),[n,r]=p.useState({search:JSON.parse(pr(e.search))}),[o,i]=p.useState(!1);p.useEffect(()=>{r({search:e.search})},[e.search]);const a=p.useMemo(()=>{if(!e.visible)return[];const c=e.search.resourceType,u=QP(c),d=kx(c);return Nc(KV(u,d)).map(f=>({value:f,label:Li(f)}))},[e.visible,e.search.resourceType]);if(!e.visible)return null;function l(c){r({search:{...n.search,fields:c}})}return s.jsx(wn,{title:"Fields",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:()=>{e.onCancel()},size:"auto",withOverlay:!0,closeOnClickOutside:!1,overlayProps:{onMouseDownCapture:()=>{t.current=o},onClick:()=>{t.current||e.onCancel(),t.current=!1},children:s.jsx("div",{"data-testid":"overlay-child"})},children:s.jsxs(Oe,{children:[s.jsx(wh,{style:{width:550},placeholder:"Select fields to display",data:a,value:n.search.fields??[],onChange:l,onDropdownOpen:()=>i(!0),onDropdownClose:()=>i(!1),maxDropdownHeight:"250px",clearButtonProps:{"aria-label":"Clear selection"},clearable:!0,searchable:!0}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{onClick:()=>e.onOk(n.search),children:"OK"})})]})})}function KV(e,t){const n=[],r=new Set,o=new Set;for(const i of Object.keys(e.elements))n.push(i),r.add(i.toLowerCase()),o.add(Li(i));if(t)for(const i of Object.keys(t)){const a=Li(i);!r.has(i)&&!o.has(a)&&(n.push(i),r.add(i),o.add(a))}return n}function SR(e){var o;const{resourceType:t,filter:n}=e,r=(o=wo.types[t].searchParams)==null?void 0:o[n.code];if(r){if(r.type==="reference"&&(n.operator===re.EQUALS||n.operator===re.NOT_EQUALS))return s.jsx(Cl,{value:{reference:n.value}});const i=wl(t,r);if(n.code==="_lastUpdated"||i.type===ko.DATETIME)return s.jsx(s.Fragment,{children:Fn(n.value)})}return s.jsx(s.Fragment,{children:n.value})}function jR(e){const t=wl(e.resourceType,e.searchParam),n="filter-value";switch(t.type){case ko.REFERENCE:return s.jsx(zh,{name:n,defaultValue:e.defaultValue?{reference:e.defaultValue}:void 0,targetTypes:e.searchParam.target,autoFocus:e.autoFocus,onChange:r=>{r?e.onChange(r.reference):e.onChange("")}});case ko.BOOLEAN:return s.jsx(_n,{name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultChecked:e.defaultValue==="true",autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.checked.toString())});case ko.DATE:return s.jsx(ve,{type:"date",name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value)});case ko.DATETIME:return s.jsx(_s,{name:n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:e.onChange});case ko.NUMBER:return s.jsx(ve,{type:"number",name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value)});case ko.QUANTITY:return s.jsx(Ds,{name:n,path:"",defaultValue:YV(e.defaultValue),autoFocus:e.autoFocus,onChange:r=>{r?e.onChange(`${r.value}`):e.onChange("")}});default:return s.jsx(ve,{name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value),placeholder:"Search value"})}}function YV(e){if(e){const[t,n,r]=e.split("|");if(t)return{value:parseFloat(t),system:n,unit:r}}}function XV(e){const[t,n]=p.useState(JSON.parse(pr(e.search))),[r,o]=p.useState(-1),i=p.useRef(t);i.current=t,p.useEffect(()=>{n(JSON.parse(pr(e.search)))},[e.search]);function a(d){n(Vh(i.current,d.code,d.operator,d.value))}if(!e.visible)return null;const l=e.search.resourceType,c=kx(l)??{},u=t.filters||[];return s.jsxs(wn,{title:"Filters",closeButtonProps:{"aria-label":"Close"},size:900,opened:e.visible,onClose:e.onCancel,children:[s.jsx("div",{children:s.jsxs("table",{children:[s.jsxs("colgroup",{children:[s.jsx("col",{style:{width:200}}),s.jsx("col",{style:{width:200}}),s.jsx("col",{style:{width:380}}),s.jsx("col",{style:{width:120}})]}),s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Field"}),s.jsx("th",{children:"Operation"}),s.jsx("th",{children:"Value"}),s.jsx("th",{children:"Actions"})]})}),s.jsxs("tbody",{children:[u.map((d,f)=>f===r?s.jsx($w,{resourceType:l,searchParams:c,defaultValue:d,okText:"Save",onOk:h=>{const m=[...u];m[f]=h,n(d0(i.current,m)),o(-1)},onCancel:()=>o(-1)},`filter-${d.code}-${d.operator}-${d.value}-input`):s.jsx(JV,{resourceType:l,filter:d,onEdit:()=>o(f),onDelete:()=>n(DV(i.current,f))},`filter-${d.code}-${d.operator}-${d.value}-display`)),s.jsx($w,{resourceType:l,searchParams:c,okText:"Add",onOk:a})]})]})}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{onClick:()=>e.onOk(i.current),children:"OK"})})]})}function JV(e){const{filter:t}=e;return s.jsxs("tr",{children:[s.jsx("td",{children:Li(t.code)}),s.jsx("td",{children:m0(t.operator)}),s.jsx("td",{children:s.jsx(SR,{resourceType:e.resourceType,filter:t})}),s.jsxs("td",{children:[s.jsx(oe,{size:"compact-md",variant:"outline",onClick:e.onEdit,children:"Edit"}),s.jsx(oe,{size:"compact-md",variant:"outline",onClick:e.onDelete,children:"Delete"})]})]})}function $w(e){const[t,n]=p.useState(e.defaultValue??{}),r=p.useRef(t);r.current=t;function o(u){n({...r.current,code:u})}function i(u){n({...r.current,operator:u})}function a(u){n({...r.current,value:u})}const l=e.searchParams[t.code],c=l&&WV(l);return s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(It,{"data-testid":"filter-field",defaultValue:r.current.code,onChange:u=>o(u.currentTarget.value),data:["",...Object.keys(e.searchParams).map(u=>({value:u,label:Li(u)}))]})}),s.jsx("td",{children:c&&s.jsx(It,{"data-testid":"filter-operation",defaultValue:t.operator,onChange:u=>i(u.currentTarget.value),data:["",...c.map(u=>({value:u,label:m0(u)}))]})}),s.jsx("td",{children:l&&t.operator&&s.jsx(jR,{resourceType:e.resourceType,searchParam:l,defaultValue:t.value,onChange:a})}),s.jsxs("td",{children:[t.code&&t.operator&&s.jsx(oe,{size:"compact-md",variant:"outline",onClick:()=>{e.onOk(r.current),n({})},children:e.okText}),e.onCancel&&s.jsx(oe,{size:"compact-md",variant:"outline",onClick:e.onCancel,children:"Cancel"})]})]})}function ZV(e){const[t,n]=p.useState(e.defaultValue??"");if(!e.visible||!e.searchParam||!e.filter)return null;function r(){e.onOk({...e.filter,value:t})}return s.jsx(wn,{title:e.title,size:"xl",opened:e.visible,onClose:e.onCancel,children:s.jsx(Ke,{onSubmit:r,children:s.jsxs(ur,{children:[s.jsx(ur.Col,{span:10,children:s.jsx(jR,{resourceType:e.resourceType,searchParam:e.searchParam,defaultValue:t,autoFocus:!0,onChange:n})}),s.jsx(ur.Col,{span:2,children:s.jsx(oe,{onClick:r,fullWidth:!0,children:"OK"})})]})})})}function eW(e){if(!e.searchParams)return null;function t(i,a){o(BV(e.search,i.code,a))}function n(i){o(wR(e.search,i.code))}function r(i,a){e.onPrompt(i,{code:i.code,operator:a,value:""})}function o(i){e.onChange(i)}return e.searchParams.length===1?s.jsx(tW,{search:e.search,searchParam:e.searchParams[0],onSort:t,onPrompt:r,onChange:o,onClear:n}):s.jsx(J.Dropdown,{children:e.searchParams.map(i=>s.jsx(J.Item,{children:Li(i.code)},i.code))})}function tW(e){switch(e.searchParam.type){case"date":return s.jsx(nW,{...e});case"number":case"quantity":return s.jsx(rW,{...e});case"reference":return s.jsx(oW,{...e});case"string":return s.jsx(iW,{...e});case"token":case"uri":return s.jsx(sW,{...e});default:return s.jsxs(s.Fragment,{children:["Unknown search param type: ",e.searchParam.type]})}}function nW(e){const{searchParam:t}=e,n=t.code;return s.jsxs(J.Dropdown,{children:[s.jsx(J.Item,{leftSection:s.jsx(Vx,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort Oldest to Newest"}),s.jsx(J.Item,{leftSection:s.jsx(Wx,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Newest to Oldest"}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(pu,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Equals..."}),s.jsx(J.Item,{leftSection:s.jsx(hu,{size:14}),onClick:()=>e.onPrompt(t,re.NOT_EQUALS),children:"Does not equal..."}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(Ok,{size:14}),onClick:()=>e.onPrompt(t,re.ENDS_BEFORE),children:"Before..."}),s.jsx(J.Item,{leftSection:s.jsx(Mk,{size:14}),onClick:()=>e.onPrompt(t,re.STARTS_AFTER),children:"After..."}),s.jsx(J.Item,{leftSection:s.jsx(nz,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Between..."}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(NV(e.search,n)),children:"Tomorrow"}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(AV(e.search,n)),children:"Today"}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(IV(e.search,n)),children:"Yesterday"}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(LV(e.search,n)),children:"Next Month"}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(OV(e.search,n)),children:"This Month"}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange(MV(e.search,n)),children:"Last Month"}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(es,{size:14}),onClick:()=>e.onChange($V(e.search,n)),children:"Year to date"}),s.jsx(bu,{...e})]})}function rW(e){const{searchParam:t}=e;return s.jsxs(J.Dropdown,{children:[s.jsx(J.Item,{leftSection:s.jsx(Vx,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort Smallest to Largest"}),s.jsx(J.Item,{leftSection:s.jsx(Wx,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Largest to Smallest"}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(pu,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Equals..."}),s.jsx(J.Item,{leftSection:s.jsx(hu,{size:14}),onClick:()=>e.onPrompt(t,re.NOT_EQUALS),children:"Does not equal..."}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(Mk,{size:14}),onClick:()=>e.onPrompt(t,re.GREATER_THAN),children:"Greater than..."}),s.jsx(J.Item,{leftSection:s.jsx(Tg,{size:14}),onClick:()=>e.onPrompt(t,re.GREATER_THAN_OR_EQUALS),children:"Greater than or equal to..."}),s.jsx(J.Item,{leftSection:s.jsx(Ok,{size:14}),onClick:()=>e.onPrompt(t,re.LESS_THAN),children:"Less than..."}),s.jsx(J.Item,{leftSection:s.jsx(Tg,{size:14}),onClick:()=>e.onPrompt(t,re.LESS_THAN_OR_EQUALS),children:"Less than or equal to..."}),s.jsx(bu,{...e})]})}function oW(e){const{searchParam:t}=e;return s.jsxs(J.Dropdown,{children:[s.jsx(J.Item,{leftSection:s.jsx(pu,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Equals..."}),s.jsx(J.Item,{leftSection:s.jsx(hu,{size:14}),onClick:()=>e.onPrompt(t,re.NOT),children:"Does not equal..."}),s.jsx(bu,{...e})]})}function iW(e){const{searchParam:t}=e;return s.jsxs(J.Dropdown,{children:[s.jsx(J.Item,{leftSection:s.jsx(Vx,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort A to Z"}),s.jsx(J.Item,{leftSection:s.jsx(Wx,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Z to A"}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(pu,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Equals..."}),s.jsx(J.Item,{leftSection:s.jsx(hu,{size:14}),onClick:()=>e.onPrompt(t,re.NOT),children:"Does not equal..."}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(iz,{size:14}),onClick:()=>e.onPrompt(t,re.CONTAINS),children:"Contains..."}),s.jsx(J.Item,{leftSection:s.jsx(oz,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Does not contain..."}),s.jsx(bu,{...e})]})}function sW(e){const{searchParam:t}=e;return s.jsxs(J.Dropdown,{children:[s.jsx(J.Item,{leftSection:s.jsx(pu,{size:14}),onClick:()=>e.onPrompt(t,re.EQUALS),children:"Equals..."}),s.jsx(J.Item,{leftSection:s.jsx(hu,{size:14}),onClick:()=>e.onPrompt(t,re.NOT),children:"Does not equal..."}),s.jsx(bu,{...e})]})}function bu(e){const{searchParam:t}=e,n=t.code;return s.jsxs(s.Fragment,{children:[s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(ez,{size:14}),onClick:()=>e.onChange(Lw(e.search,n)),children:"Missing"}),s.jsx(J.Item,{leftSection:s.jsx(Z8,{size:14}),onClick:()=>e.onChange(Lw(e.search,n,!1)),children:"Not missing"}),s.jsx(J.Divider,{}),s.jsx(J.Item,{leftSection:s.jsx(xf,{size:14}),onClick:()=>e.onClear(t),children:"Clear filters"})]})}const aW="_root_vlout_1",lW="_table_vlout_8",cW="_tr_vlout_12",uW="_th_vlout_18",dW="_control_vlout_22",fW="_icon_vlout_31",Bl={root:aW,table:lW,tr:cW,th:uW,control:dW,icon:fW};function hW(e){const t=e.resourceType,n=[];for(const r of e.fields||["id","_lastUpdated"])n.push(pW(t,r));return n}function pW(e,t){var o;if(t==="_lastUpdated")return{name:"_lastUpdated",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_lastUpdated",name:"_lastUpdated",type:"date",expression:"Resource.meta.lastUpdated"}]};if(t==="meta.versionId")return{name:"meta.versionId",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_versionId",name:"_versionId",type:"token",expression:"Resource.meta.versionId"}]};const n=Gs(e,t),r=O6(e,t.toLowerCase());if(n&&r)return{name:t,elementDefinition:n,searchParams:[r]};if(n){const i=kx(e);let a;if(i){const l=new RegExp(`${e}\\.${t.replaceAll("[x]","")}([^\\w-]|$)`);a=Object.values(i).filter(c=>!!c.expression&&l.test(c==null?void 0:c.expression)),a.length===0&&(a=void 0)}return{name:t,elementDefinition:n,searchParams:a}}if(r){const i=wl(e,r);return{name:t,elementDefinition:(o=i.elementDefinitions)==null?void 0:o[0],searchParams:[r]}}return{name:t}}class mW extends Event{constructor(t){super("change"),this.definition=t}}class gW extends Event{constructor(t){super("load"),this.response=t}}class Sf extends Event{constructor(t,n){super("click"),this.resource=t,this.browserEvent=n}}function wu(e){var N,F,D;const t=se(),[n,r]=p.useState(),{search:o,onLoad:i}=e,[a,l]=p.useState(o);Mi(o,a)||l(o);const[c,u]=p.useState({selected:{},fieldEditorVisible:!1,filterEditorVisible:!1,exportDialogVisible:!1,filterDialogVisible:!1}),d=p.useRef(c);d.current=c;const f=a.total??"accurate",h=p.useCallback(R=>{r(void 0),t.requestSchema(a.resourceType).then(()=>t.search(a.resourceType,Ra({...a,total:f,fields:void 0}),R)).then(P=>{u({...d.current,searchResponse:P}),i&&i(new gW(P))}).catch(P=>{u({...d.current,searchResponse:void 0}),r(ht(P))})},[t,a,f,i]),m=p.useCallback(()=>{u({...d.current,searchResponse:void 0}),h({cache:"reload"})},[h]);p.useEffect(()=>{h()},[h]);function g(R,P){R.stopPropagation();const L=R.target.checked,V={...d.current.selected};L?V[P]=!0:delete V[P],u({...d.current,selected:V})}function v(R){R.stopPropagation();const $=R.target.checked,L={},V=d.current.searchResponse;$&&(V!=null&&V.entry)&&V.entry.forEach(K=>{var ie;(ie=K.resource)!=null&&ie.id&&(L[K.resource.id]=!0)}),u({...d.current,selected:L})}function S(){var P,$;const R=d.current;if(!((P=R.searchResponse)!=null&&P.entry)||R.searchResponse.entry.length===0)return!1;for(const L of R.searchResponse.entry)if(($=L.resource)!=null&&$.id&&!R.selected[L.resource.id])return!1;return!0}function y(R){e.onChange&&e.onChange(new mW(R))}function w(R,P){if($k(R.target)||R.button===2)return;yt(R);const $=R.button===1||R.ctrlKey||R.metaKey;!$&&e.onClick&&e.onClick(new Sf(P,R)),$&&e.onAuxClick&&e.onAuxClick(new Sf(P,R))}function b(){return!!(e.onExport??e.onExportCsv??e.onExportTransactionBundle)}if(n)return s.jsx(Mr,{outcome:n});if(!GP(a.resourceType))return s.jsx(mn,{style:{width:"100%",height:"100%"},children:s.jsx(Zn,{})});const x=e.checkboxesEnabled,C=hW(a),j=a.resourceType,T=c.searchResponse,E=T==null?void 0:T.entry,_=E==null?void 0:E.map(R=>R.resource),k="subtle",A="gray",O=16,U=window.innerWidth<768;return s.jsxs("div",{className:Bl.root,"data-testid":"search-control",children:[!e.hideToolbar&&s.jsxs(te,{justify:"space-between",mb:"xl",children:[s.jsxs(te,{gap:2,children:[s.jsx(oe,{size:"compact-md",variant:k,color:A,leftSection:s.jsx(lz,{size:O}),onClick:()=>u({...d.current,fieldEditorVisible:!0}),children:"Fields"}),s.jsx(oe,{size:"compact-md",variant:k,color:A,leftSection:s.jsx(hz,{size:O}),onClick:()=>u({...d.current,filterEditorVisible:!0}),children:"Filters"}),e.onNew&&s.jsx(oe,{size:"compact-md",variant:k,color:A,leftSection:s.jsx(fz,{size:O}),onClick:e.onNew,children:"New..."}),!U&&b()&&s.jsx(oe,{size:"compact-md",variant:k,color:A,leftSection:s.jsx(Mz,{size:O}),onClick:e.onExport?e.onExport:()=>u({...d.current,exportDialogVisible:!0}),children:"Export..."}),!U&&e.onDelete&&s.jsx(oe,{size:"compact-md",variant:k,color:A,leftSection:s.jsx(Hx,{size:O}),onClick:()=>e.onDelete(Object.keys(c.selected)),children:"Delete..."}),!U&&e.onBulk&&s.jsx(oe,{size:"compact-md",variant:k,color:A,leftSection:s.jsx(tz,{size:O}),onClick:()=>e.onBulk(Object.keys(c.selected)),children:"Bulk..."})]}),s.jsxs(te,{gap:2,children:[T&&s.jsxs(fe,{size:"xs",c:"dimmed","data-testid":"count-display",children:[CR(a,T).toLocaleString(),"-",wW(a,T).toLocaleString(),T.total!==void 0&&` of ${a.total==="estimate"?"~":""}${(N=T.total)==null?void 0:N.toLocaleString()}`]}),s.jsx(tn,{variant:k,color:A,title:"Refresh",onClick:m,children:s.jsx(Pz,{size:O})})]})]}),s.jsxs(de,{className:Bl.table,children:[s.jsxs(de.Thead,{children:[s.jsxs(de.Tr,{children:[x&&s.jsx(de.Th,{children:s.jsx("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:S(),onChange:R=>v(R)})}),C.map(R=>s.jsx(de.Th,{children:s.jsxs(J,{shadow:"md",width:240,position:"bottom-end",children:[s.jsx(J.Target,{children:s.jsx(bn,{className:Bl.control,p:2,children:s.jsxs(te,{justify:"space-between",wrap:"nowrap",children:[s.jsx(fe,{fw:500,children:Li(R.name)}),s.jsx(mn,{className:Bl.icon,children:s.jsx(Y8,{size:14,stroke:1.5})})]})})}),s.jsx(eW,{search:a,searchParams:R.searchParams,onPrompt:(P,$)=>{u({...d.current,filterDialogVisible:!0,filterDialogSearchParam:P,filterDialogFilter:$})},onChange:P=>{y(P)}})]})},R.name))]}),!e.hideFilters&&s.jsxs(de.Tr,{children:[x&&s.jsx(de.Th,{}),C.map(R=>s.jsx(de.Th,{children:R.searchParams&&s.jsx(yW,{resourceType:j,searchParams:R.searchParams,filters:a.filters})},R.name))]})]}),s.jsx(de.Tbody,{children:_==null?void 0:_.map(R=>R&&s.jsxs(de.Tr,{className:Bl.tr,"data-testid":"search-control-row",onClick:P=>w(P,R),onAuxClick:P=>w(P,R),children:[x&&s.jsx(de.Td,{children:s.jsx("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${R.id}`,checked:!!c.selected[R.id],onChange:P=>g(P,R.id)})}),C.map(P=>s.jsx(de.Td,{children:HV(R,P)},P.name))]},R.id))})]}),(_==null?void 0:_.length)===0&&s.jsx(yu,{children:s.jsx(mn,{style:{height:150},children:s.jsx(fe,{size:"xl",c:"dimmed",children:"No results"})})}),T&&s.jsx(mn,{m:"md",p:"md",children:s.jsx(no,{value:xW(a),total:bW(a,T),onChange:R=>y(zV(a,R)),getControlProps:R=>{switch(R){case"previous":return{"aria-label":"Previous page"};case"next":return{"aria-label":"Next page"};default:return{}}}})}),s.jsx(QV,{search:a,visible:d.current.fieldEditorVisible,onOk:R=>{y(R),u({...d.current,fieldEditorVisible:!1})},onCancel:()=>{u({...d.current,fieldEditorVisible:!1})}}),s.jsx(XV,{search:a,visible:d.current.filterEditorVisible,onOk:R=>{y(R),u({...d.current,filterEditorVisible:!1})},onCancel:()=>{u({...d.current,filterEditorVisible:!1})}}),s.jsx(kV,{visible:d.current.exportDialogVisible,exportCsv:e.onExportCsv,exportTransactionBundle:e.onExportTransactionBundle,onCancel:()=>{u({...d.current,exportDialogVisible:!1})}}),s.jsx(ZV,{visible:d.current.filterDialogVisible,title:(F=c.filterDialogSearchParam)!=null&&F.code?Li(c.filterDialogSearchParam.code):"",resourceType:j,searchParam:c.filterDialogSearchParam,filter:c.filterDialogFilter,defaultValue:"",onOk:R=>{y(Vh(a,R.code,R.operator,R.value)),u({...d.current,filterDialogVisible:!1})},onCancel:()=>{u({...d.current,filterDialogVisible:!1})}},(D=c.filterDialogSearchParam)==null?void 0:D.code)]})}const vW=wu;function yW(e){const t=(e.filters??[]).filter(n=>e.searchParams.find(r=>r.code===n.code));return t.length===0?s.jsx("span",{children:"no filters"}):s.jsx(s.Fragment,{children:t.map(n=>s.jsxs("div",{children:[m0(n.operator)," ",s.jsx(SR,{resourceType:e.resourceType,filter:n})]},`filter-${n.code}-${n.operator}-${n.value}`))})}function xW(e){return Math.floor((e.offset??0)/(e.count??Ah))+1}function bW(e,t){const n=e.count??Ah,r=ER(e,t);return Math.ceil(r/n)}function CR(e,t){return Math.min(ER(e,t),(e.offset??0)+1)}function wW(e,t){var n;return Math.max(CR(e,t)+(((n=t.entry)==null?void 0:n.length)??0)-1,0)}function ER(e,t){var r,o;let n=t.total;return n===void 0&&(n=(e.offset??0)+(((r=t.entry)==null?void 0:r.length)??0)+((o=t.link)!=null&&o.some(i=>i.relation==="next")?1:0)),n}function SW(e){const t=se(),[n,r]=p.useState(!1),[o,i]=p.useState(),{query:a,fields:l}=e,[c,u]=p.useState(),[d,f]=p.useState({}),h=p.useRef();h.current=c;const m=p.useRef({});m.current=d,p.useEffect(()=>{i(void 0),t.graphql(a).then(u).catch(b=>i(ht(b)))},[t,a]);function g(b,x){b.stopPropagation();const j=b.target.checked,T={...m.current};j?T[x]=!0:delete T[x],f(T)}function v(b){var E;b.stopPropagation();const C=b.target.checked,j={},T=(E=h.current)==null?void 0:E.data.ResourceList;C&&T&&T.forEach(_=>{_.id&&(j[_.id]=!0)}),f(j)}function S(){var x;const b=(x=h.current)==null?void 0:x.data.ResourceList;if(!b||b.length===0)return!1;for(const C of b)if(C.id&&!m.current[C.id])return!1;return!0}function y(b,x){$k(b.target)||(yt(b),b.button!==1&&e.onClick&&e.onClick(new Sf(x,b)),b.button===1&&e.onAuxClick&&e.onAuxClick(new Sf(x,b)))}if(p.useEffect(()=>{t.requestSchema(e.resourceType).then(()=>r(!0)).catch(console.log)},[t,e.resourceType]),!n)return s.jsx(Zn,{});const w=e.checkboxesEnabled;return s.jsxs("div",{onContextMenu:b=>yt(b),"data-testid":"search-control",children:[s.jsxs(de,{children:[s.jsx(de.Thead,{children:s.jsxs(de.Tr,{children:[w&&s.jsx(de.Th,{children:s.jsx("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:S(),onChange:b=>v(b)})}),l.map(b=>s.jsx(de.Th,{children:b.name},b.name))]})}),s.jsx(de.Tbody,{children:c==null?void 0:c.data.ResourceList.map(b=>b&&s.jsxs(de.Tr,{"data-testid":"search-control-row",onClick:x=>y(x,b),onAuxClick:x=>y(x,b),children:[w&&s.jsx(de.Td,{children:s.jsx("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${b.id}`,checked:!!d[b.id],onChange:x=>g(x,b.id)})}),l.map(x=>s.jsx(de.Td,{children:s.jsx(PV,{propertyType:x.propertyType,path:x.fhirPath,resource:b})},x.name))]},b.id))})]}),(c==null?void 0:c.data.ResourceList.length)===0&&s.jsx("div",{"data-testid":"empty-search",children:"No results"}),o&&s.jsx("div",{"data-testid":"search-error",children:s.jsx("pre",{style:{textAlign:"left"},children:JSON.stringify(o,void 0,2)})}),e.onBulk&&s.jsx(oe,{onClick:()=>e.onBulk(Object.keys(m.current)),children:"Bulk..."})]})}const jW=p.memo(SW);function ro(e){return s.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 491 491",style:{width:e.size,height:e.size},children:[s.jsx("title",{children:"Medplum Logo"}),s.jsx("path",{fill:e.fill??"#ad7136",d:"M282 67c6-16 16-29 29-40L289 0c-22 17-37 41-43 68l17 23 19-24z"}),s.jsx("path",{fill:e.fill??"#946af9",d:"M311 63c-17 0-33 4-48 11-16-7-32-11-49-11-87 0-158 96-158 214s71 214 158 214c17 0 33-4 49-11 15 7 31 11 48 11 87 0 158-96 158-214S398 63 311 63z"}),s.jsx("path",{fill:e.fill??"#7857c5",d:"M231 489l-17 2c-87 0-158-96-158-214S127 63 214 63l17 1c-39 12-70 102-70 213s31 201 70 212z"}),s.jsx("path",{fill:e.fill??"#40bc26",d:"M207 220a176 176 0 01-177 43A176 176 0 01251 43l1 5c17 59 2 125-45 172z"}),s.jsx("path",{fill:e.fill??"#33961e",d:"M252 48A421 421 0 0057 270l-27-7A176 176 0 01251 43l1 5z"})]})}function CW(e){const{group:t}=e;return s.jsx(Yn,{withBorder:!0,radius:"md",p:"xs",display:"flex",style:{alignItems:"center",justifyContent:"center"},children:s.jsxs(te,{children:[t.measureScore&&s.jsx(PW,{group:t}),!t.measureScore&&s.jsx(TW,{group:t})]})})}function EW(e){const{measure:t}=e;return s.jsxs(s.Fragment,{children:[s.jsx(fe,{fz:"md",fw:500,mb:8,children:t.title}),s.jsx(fe,{fz:"xs",c:"dimmed",mb:8,children:t.subtitle})]})}function TW(e){const{group:t}=e,n=t.population,r=n==null?void 0:n.find(c=>Oi(c.code)==="numerator"),o=n==null?void 0:n.find(c=>Oi(c.code)==="denominator"),i=r==null?void 0:r.count,a=o==null?void 0:o.count;if(a===0)return s.jsxs(q,{children:[s.jsx(ge,{order:3,children:"Not Applicable"}),s.jsx(fe,{children:`Denominator: ${a}`})]});if(i===void 0||a===void 0)return s.jsxs(q,{children:[s.jsx(ge,{order:3,children:"Insufficient Data"}),s.jsx(fe,{children:`Numerator: ${i}`}),s.jsx(fe,{children:`Denominator: ${a}`})]});const l=i/a*100;return s.jsx(kh,{size:120,thickness:12,roundCaps:!0,sections:[{value:l,color:TR(l)}],label:s.jsx(Es,{justify:"center",children:s.jsxs(fe,{fw:700,fz:18,children:[i," / ",a]})})})}function PW(e){var r,o,i;const{group:t}=e,n=((r=t.measureScore)==null?void 0:r.unit)??((o=t.measureScore)==null?void 0:o.code);return s.jsx(s.Fragment,{children:n==="%"?s.jsx(kh,{size:120,thickness:12,roundCaps:!0,sections:[{value:kW(t),color:TR(((i=t==null?void 0:t.measureScore)==null?void 0:i.value)??0)}],label:s.jsx(Es,{justify:"center",children:s.jsx(fe,{fw:700,fz:18,children:s.jsx($c,{value:t.measureScore})})})}):s.jsx(Es,{h:120,align:"center",children:s.jsx(ge,{order:3,children:s.jsx($c,{value:t.measureScore})})})})}function kW(e){var r,o;const t=(r=e.measureScore)==null?void 0:r.value,n=(o=e.measureScore)==null?void 0:o.unit;return t?t<=1&&n==="%"?t*100:t:0}function TR(e){return e<=33?"red":e<=67?"yellow":"green"}function RW(e){var r;const t=wt(e.measureReport),[n]=V8("Measure",{url:t==null?void 0:t.measure});return t?s.jsxs(q,{children:[n&&s.jsx(EW,{measure:n}),s.jsx(ux,{cols:{base:3,sm:1},spacing:{base:"md",sm:"sm"},children:(r=t.group)==null?void 0:r.map((o,i)=>s.jsx(CW,{group:o},o.id??i))})]}):null}function _W(e){const{patient:t,...n}=e,r=p.useCallback((o,i,a)=>{const l=`${i}/${a}`,c=100;return Promise.allSettled([o.readHistory("Patient",a),o.search("Communication",{subject:l,_count:c}),o.search("Device",{patient:l,_count:c}),o.search("DeviceRequest",{patient:l,_count:c}),o.search("DiagnosticReport",{subject:l,_count:c}),o.search("Media",{subject:l,_count:c}),o.search("ServiceRequest",{subject:l,_count:c}),o.search("Task",{subject:l,_count:c})])},[]);return s.jsx(Uh,{value:t,loadTimelineResources:r,createCommunication:(o,i,a)=>({resourceType:"Communication",status:"completed",subject:Et(o),sender:Et(i),sent:new Date().toISOString(),payload:[{contentString:a}]}),createMedia:(o,i,a)=>({resourceType:"Media",status:"completed",subject:Et(o),operator:Et(i),issued:new Date().toISOString(),content:a}),...n})}const DW="_section_14dzq_2",IW="_hovering_14dzq_11",AW="_editing_14dzq_15",NW="_bottomActions_14dzq_20",_a={section:DW,hovering:IW,editing:AW,bottomActions:NW};function MW(e){const t=se(),n=wt(e.value),[r,o]=p.useState(!1),[i,a]=p.useState(),[l,c]=p.useState(),[u,d]=p.useState();function f(){c(void 0)}function h(){a(void 0)}const m=p.useRef();if(m.current=u,p.useEffect(()=>{t.requestSchema("PlanDefinition").then(()=>o(!0)).catch(console.log)},[t]),p.useEffect(()=>(d(BW(n??{resourceType:"PlanDefinition",status:"active"})),document.addEventListener("mouseover",f),document.addEventListener("click",h),()=>{document.removeEventListener("mouseover",f),document.removeEventListener("click",h)}),[n]),!r||!u)return null;function g(v,S){d({...m.current,[v]:S})}return s.jsx("div",{children:s.jsxs(Ke,{testid:"questionnaire-form",onSubmit:()=>e.onSubmit(u),children:[s.jsx(ve,{label:"Plan Title",defaultValue:u.title,onChange:v=>g("title",v.currentTarget.value)}),s.jsx(PR,{actions:u.action||[],selectedKey:i,setSelectedKey:a,hoverKey:l,setHoverKey:c,onChange:v=>g("action",v)}),s.jsx(oe,{type:"submit",children:"Save"})]})})}function PR(e){const t=p.useRef();t.current=e.actions;function n(i){e.onChange(t.current.map(a=>a.id===i.id?i:a))}function r(i){e.onChange([...t.current,i]),e.setSelectedKey(i.id)}function o(i){e.onChange(t.current.filter(a=>a!==i))}return s.jsxs("div",{className:_a.section,children:[e.actions.map(i=>s.jsx("div",{children:s.jsx(OW,{action:i,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,setHoverKey:e.setHoverKey,onChange:n,onRemove:()=>o(i)})},i.id)),s.jsx("div",{className:_a.bottomActions,children:s.jsx(Ze,{href:"#",onClick:i=>{yt(i),r({id:RR()})},children:"Add action"})})]})}function OW(e){const{action:t}=e,n=zW(t),r=e.selectedKey===e.action.id,o=e.hoverKey===e.action.id;function i(c){c.stopPropagation(),e.setSelectedKey(e.action.id)}function a(c){yt(c),e.setHoverKey(e.action.id)}const l=rt(_a.section,{[_a.editing]:r,[_a.hovering]:o&&!r});return s.jsxs("div",{"data-testid":t.id,className:l,onClick:i,onMouseOver:a,onFocus:a,children:[r?s.jsx($W,{action:t,actionType:n,onChange:e.onChange,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,setHoverKey:e.setHoverKey,onRemove:e.onRemove}):s.jsx(LW,{action:t,actionType:n}),s.jsx("div",{className:_a.bottomActions,children:s.jsx(Ze,{href:"#",onClick:c=>{c.preventDefault(),e.onRemove()},children:"Remove"})})]})}const Rg={path:"PlanDefinition.action.timing[x]",min:0,max:1,description:"",isArray:!1,constraints:[],type:["dateTime","Period","Range","Timing"].map(e=>({code:e}))};function LW(e){const{action:t,actionType:n}=e,[r,o]=kR(t);return s.jsxs("div",{children:[s.jsxs("div",{children:[t.title||"Untitled"," ",n&&`(${n})`]}),t.definitionCanonical&&s.jsx("div",{children:s.jsx(bf,{value:{reference:t.definitionCanonical}})}),r&&s.jsx("div",{children:s.jsx(Zr,{property:Rg,propertyType:o,value:r})})]})}function $W(e){const{action:t}=e,[n,r]=p.useState(e.actionType);function o(i,a){e.onChange({...t,[i]:a})}return s.jsxs(Oe,{gap:"xl",children:[s.jsx(ve,{name:`actionTitle-${t.id}`,label:"Title",defaultValue:t.title,onChange:i=>o("title",i.currentTarget.value)}),s.jsx(ve,{name:`actionDescription-${t.id}`,label:"Description",defaultValue:t.description,onChange:i=>o("description",i.currentTarget.value)}),s.jsx(It,{label:"Type of Action",description:"The type of the action to be performed.",name:`actionType-${t.id}`,defaultValue:n,onChange:i=>r(i.currentTarget.value),data:["","appointment","lab","questionnaire","task"]}),t.action&&t.action.length>0&&s.jsx(PR,{actions:t.action,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,setHoverKey:e.setHoverKey,onChange:i=>o("action",i)}),(()=>{switch(n){case"appointment":return s.jsx(ld,{title:"Appointment",description:"The subject must schedule an appointment from the schedule.",resourceType:"Schedule",action:t,onChange:e.onChange});case"lab":return s.jsx(ld,{title:"Lab",description:"The subject must complete the following lab panel.",resourceType:"ActivityDefinition",action:t,onChange:e.onChange});case"questionnaire":return s.jsx(ld,{title:"Questionnaire",description:"The subject must complete the selected questionnaire.",resourceType:"Questionnaire",action:t,onChange:e.onChange});case"task":return s.jsx(ld,{title:"Task",description:"The subject must complete the following task.",resourceType:"ActivityDefinition",action:t,onChange:e.onChange});default:return null}})(),s.jsx(vt,{title:"Timing",description:"When the action should take place.",children:s.jsx(FW,{name:"timing-"+t.id,action:t,onChange:e.onChange})})]})}function ld(e){const{id:t,definitionCanonical:n}=e.action,r=n!=null&&n.startsWith(e.resourceType+"/")?{reference:n}:void 0;return s.jsx(Ys,{name:t,resourceType:e.resourceType,defaultValue:r,loadOnFocus:!0,onChange:o=>{o?e.onChange({...e.action,definitionCanonical:st(o)}):e.onChange({...e.action,definitionCanonical:void 0})}})}function FW(e){const t=e.action,n="timing",[r,o]=kR(t);return s.jsx(jl,{property:Rg,name:"timing[x]",path:"PlanDefinition.timing[x]",defaultValue:r,defaultPropertyType:o,onChange:(i,a)=>{e.onChange(Xk(t,n,a??n,Rg,i))},outcome:void 0})}function zW(e){var t,n,r;if((t=e.definitionCanonical)!=null&&t.startsWith("Schedule"))return"appointment";if((n=e.definitionCanonical)!=null&&n.startsWith("Questionnaire/"))return"questionnaire";if((r=e.definitionCanonical)!=null&&r.startsWith("ActivityDefinition/"))return"task"}function kR(e){return gu({type:"PlanDefinitionAction",value:e},"timing")}let Xp=1;function RR(e){if(e){if(e.startsWith("id-")){const t=parseInt(e.substring(3),10);isNaN(t)||(Xp=Math.max(Xp,t+1))}return e}return"id-"+Xp++}function BW(e){return{...e,action:_R(e.action)}}function _R(e){if(e)return e.map(t=>({...t,id:RR(t.id),action:_R(t.action)}))}var jt=(e=>(e.group="group",e.display="display",e.question="question",e.boolean="boolean",e.decimal="decimal",e.integer="integer",e.date="date",e.dateTime="dateTime",e.time="time",e.string="string",e.text="text",e.url="url",e.choice="choice",e.openChoice="open-choice",e.attachment="attachment",e.reference="reference",e.quantity="quantity",e))(jt||{});function UW(e){return e.type==="choice"||e.type==="open-choice"}function VW(e,t){if(!e.enableWhen)return!0;const n=e.enableBehavior??"any";for(const r of e.enableWhen){const o=DR(t,r.question);if(r.operator==="exists"&&!r.answerBoolean&&!(o!=null&&o.length)){if(n==="any")return!0;continue}const{anyMatch:i,allMatch:a}=qW(r,o,n);if(n==="any"&&i)return!0;if(n==="all"&&!a)return!1}return n!=="any"}function WW(e,t,n){return e.map(r=>{var a;const o=(a=n.answerOption)==null?void 0:a.find(l=>qs(l.valueCoding)===r||l[t]===r),i=vn({type:"QuestionnaireItemAnswerOption",value:o},"value");return{[t]:i==null?void 0:i.value}})}function DR(e,t){if(e)for(const n of e){if(n.linkId===t)return n.answer;if(n.item){const r=DR(n.item,t);if(r)return r}}}function HW(e,t,n){if(n==="exists")return!!e===t.value;if(e){const r=n==="="||n==="!="?n==null?void 0:n.replace("=","~"):n,[{value:o}]=Lc(`%actualAnswer ${r} %expectedAnswer`,[e],{"%actualAnswer":e,"%expectedAnswer":t});return o}else return!1}function qW(e,t,n){const r=t||[],o=vn({type:"QuestionnaireItemEnableWhen",value:e},"answer[x]");let i=!1,a=!0;for(const l of r){const c=vn({type:"QuestionnaireResponseItemAnswer",value:l},"value[x]"),{operator:u}=e;if(HW(c,o,u)?i=!0:a=!1,n==="any"&&i)break}return{anyMatch:i,allMatch:a}}function IR(e){var n,r;const t=xl(e,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource");if(t){if(t.valueCode!==void 0)return[t.valueCode];if(t.valueCodeableConcept)return(r=(n=t.valueCodeableConcept)==null?void 0:n.coding)==null?void 0:r.map(o=>o.code)}}function Jp(e,t){var o;const n=Xr(e);let r=xl(n,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource");return!t||t.length===0?(r&&(n.extension=(o=n.extension)==null?void 0:o.filter(i=>i!==r)),n):(r||(n.extension||(n.extension=[]),r={url:"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource"},n.extension.push(r)),t.length===1?(r.valueCode=t[0],delete r.valueCodeableConcept):(r.valueCodeableConcept={coding:t.map(i=>({code:i}))},delete r.valueCode),n)}function GW(e,t,n){const r=xl(e,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceFilter");if(!(r!=null&&r.valueString))return;let o=r.valueString;t!=null&&t.reference&&(o=o.replaceAll("$subj",t.reference)),n!=null&&n.reference&&(o=o.replaceAll("$encounter",n.reference));const i={},a=o.split("&");for(const l of a){const[c,u]=xg(l,"=",2);i[c]=u}return i}function QW(e){return{resourceType:"QuestionnaireResponse",questionnaire:st(e),item:AR(e.item),status:"in-progress"}}function AR(e){return(e==null?void 0:e.map(NR))??[]}function NR(e){var t;return{id:YW(),linkId:e.linkId,text:e.text,item:AR(e.item),answer:((t=e.initial)==null?void 0:t.map(XW))??[]}}let KW=1;function YW(){return"id-"+KW++}function XW(e){return{...e}}function JW(e){return e.value.display||e.value.reference||pr(e.value)}function ZW(e){var n,r,o,i;const t=(n=e==null?void 0:e.item)==null?void 0:n[0];if(t){const a=xl(t,"http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl");if(((i=(o=(r=a==null?void 0:a.valueCodeableConcept)==null?void 0:r.coding)==null?void 0:o[0])==null?void 0:i.code)==="page")return e.item.length}return 1}const MR=p.createContext({});function _g(e){const t=p.useContext(MR),n=e.item,r=e.response;function o(u){var f,h,m,g;let d;Array.isArray(u)?d=u:e.index>=(((h=(f=e.response)==null?void 0:f.answer)==null?void 0:h.length)??0)?d=(((m=e.response)==null?void 0:m.answer)??[]).concat([u]):d=(((g=e.response)==null?void 0:g.answer)??[]).map((S,y)=>y===e.index?u:S)??[],e.onChange({id:r==null?void 0:r.id,linkId:r==null?void 0:r.linkId,text:n.text,answer:d})}const i=n.type;if(!i)return null;const a=n.linkId;if(!a)return null;const l=n.initial&&n.initial.length>0?n.initial[0]:void 0,c=g0(r,e.index)??vn({type:"QuestionnaireItemInitial",value:l},"value");switch(i){case jt.display:return s.jsx("p",{children:e.item.text},e.item.linkId);case jt.boolean:return s.jsx(Kk,{title:e.item.text,htmlFor:e.item.linkId,children:s.jsx(_n,{id:e.item.linkId,name:e.item.linkId,defaultChecked:c==null?void 0:c.value,onChange:u=>o({valueBoolean:u.currentTarget.checked})})},e.item.linkId);case jt.decimal:return s.jsx(ve,{type:"number",step:"any",id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueDecimal:u.currentTarget.valueAsNumber})});case jt.integer:return s.jsx(ve,{type:"number",step:1,id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueInteger:u.currentTarget.valueAsNumber})});case jt.date:return s.jsx(ve,{type:"date",id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueDate:u.currentTarget.value})});case jt.dateTime:return s.jsx(_s,{name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueDateTime:u})});case jt.time:return s.jsx(ve,{type:"time",id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueTime:u.currentTarget.value})});case jt.string:case jt.url:return s.jsx(ve,{id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueString:u.currentTarget.value})});case jt.text:return s.jsx(Us,{id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueString:u.currentTarget.value})});case jt.attachment:return s.jsx(te,{py:4,children:s.jsx(Bk,{path:"",name:a,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueAttachment:u})})});case jt.reference:return s.jsx(zh,{name:a,required:n.required,targetTypes:IR(n),searchCriteria:GW(n,t.subject,t.encounter),defaultValue:c==null?void 0:c.value,onChange:u=>o({valueReference:u})});case jt.quantity:return s.jsx(Ds,{path:"",name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueQuantity:u}),disableWheel:!0});case jt.choice:case jt.openChoice:return iH(n)&&!n.answerValueSet?s.jsx(eH,{name:a,item:n,initial:l,response:r,onChangeAnswer:u=>o(u)}):s.jsx(tH,{name:a,item:n,initial:l,response:r,onChangeAnswer:u=>o(u)});default:return null}}function eH(e){var c;const{name:t,item:n,initial:r,response:o}=e;if(!((c=n.answerOption)!=null&&c.length))return s.jsx(OR,{});const i=vn({type:"QuestionnaireItemInitial",value:r},"value"),a=[""];for(const u of n.answerOption){const d=vn({type:"QuestionnaireItemAnswerOption",value:u},"value");a.push(Fw(d))}const l=g0(o)??i;if(n.repeats){const{propertyName:u,data:d}=sH(e.item),f=rH(o);return s.jsx(wh,{data:d,placeholder:"Select items",searchable:!0,defaultValue:f||[Fw(i)],onChange:h=>{const m=WW(h,u,n);e.onChangeAnswer(m)}})}return s.jsx(It,{id:t,name:t,onChange:u=>{const d=u.currentTarget.selectedIndex;if(d===0){e.onChangeAnswer({});return}const f=n.answerOption[d-1],h=vn({type:"QuestionnaireItemAnswerOption",value:f},"value"),m="value"+nn(h.type);e.onChangeAnswer({[m]:h.value})},defaultValue:qs(l==null?void 0:l.value)||(l==null?void 0:l.value),data:a})}function tH(e){var a;const{name:t,item:n,initial:r,onChangeAnswer:o,response:i}=e;return!((a=n.answerOption)!=null&&a.length)&&!n.answerValueSet?s.jsx(OR,{}):n.answerValueSet?s.jsx(Jk,{path:"",name:t,binding:n.answerValueSet,onChange:l=>o({valueCoding:l}),creatable:n.type===jt.openChoice}):s.jsx(nH,{name:(i==null?void 0:i.id)??t,item:n,initial:r,response:i,onChangeAnswer:o})}function nH(e){const{name:t,item:n,initial:r,onChangeAnswer:o,response:i}=e,a=Gs("QuestionnaireItemAnswerOption","value[x]"),l=vn({type:"QuestionnaireItemInitial",value:r},"value"),c=[];let u;if(n.answerOption)for(let h=0;h<n.answerOption.length;h++){const m=n.answerOption[h],g=`${t}-option-${h}`,v=vn({type:"QuestionnaireItemAnswerOption",value:m},"value");v!=null&&v.value&&(l&&pr(v)===pr(l)&&(u=g),c.push([g,v]))}const d=g0(i),f=oH(c,d);return s.jsx(ks.Group,{name:t,value:f??u,onChange:h=>{const m=c.find(g=>g[0]===h);if(m){const g=m[1],v="value"+nn(g.type);o({[v]:g.value})}},children:c.map(([h,m])=>s.jsx(ks,{id:h,value:h,py:4,label:s.jsx(Zr,{property:a,propertyType:m.type,value:m.value})},h))})}function OR(){return s.jsx(ve,{disabled:!0,placeholder:"No Answers Defined"})}function LR(e){return vn({type:"QuestionnaireItemAnswer",value:e},"value")}function g0(e,t=0){const n=e.answer;return LR((n==null?void 0:n[t])??{})}function rH(e){const t=e.answer;return t?t.map(r=>LR(r)).map(r=>qs(r==null?void 0:r.value)||(r==null?void 0:r.value)):[]}function oH(e,t){var n;return(n=e.find(r=>Mi(r[1].value,t==null?void 0:t.value)))==null?void 0:n[0]}function Fw(e){if(e)return e.type==="CodeableConcept"?Oi(e.value):e.type==="Coding"?qs(e.value):e.type==="Reference"?JW(e):e.value.toString()}function iH(e){var t;return!!((t=e.extension)!=null&&t.some(n=>{var r,o,i;return n.url==="http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl"&&((i=(o=(r=n.valueCodeableConcept)==null?void 0:r.coding)==null?void 0:o[0])==null?void 0:i.code)==="drop-down"}))}function sH(e){var i;if(((i=e.answerOption)==null?void 0:i.length)===0)return{propertyName:"",data:[]};const t=e.answerOption[0],n=vn({type:"QuestionnaireItemAnswerOption",value:t},"value"),r="value"+nn(n.type),o=(e.answerOption??[]).map(a=>({value:zw(a,r),label:zw(a,r)}));return{propertyName:r,data:o}}function zw(e,t){var n;return qs(e.valueCoding)||((n=e[t])==null?void 0:n.toString())}const aH="_section_cpwxo_1",lH="_hovering_cpwxo_10",cH="_editing_cpwxo_14",uH="_questionBody_cpwxo_19",dH="_topActions_cpwxo_23",fH="_bottomActions_cpwxo_32",hH="_movementActions_cpwxo_43",pH="_movementIcons_cpwxo_55",mH="_columnAlignment_cpwxo_59",gH="_linkIdInput_cpwxo_64",vH="_typeSelect_cpwxo_69",br={section:aH,hovering:lH,editing:cH,questionBody:uH,topActions:dH,bottomActions:fH,movementActions:hH,movementIcons:pH,columnAlignment:mH,linkIdInput:gH,typeSelect:vH};function yH(e){const t=se(),n=wt(e.questionnaire),[r,o]=p.useState(!1),[i,a]=p.useState(),[l,c]=p.useState(),[u,d]=p.useState();function f(){d(void 0)}function h(){c(void 0)}p.useEffect(()=>{t.requestSchema("Questionnaire").then(()=>o(!0)).catch(console.log)},[t]),p.useEffect(()=>(a(SH(n??{resourceType:"Questionnaire",status:"active"})),document.addEventListener("mouseover",f),document.addEventListener("click",h),()=>{document.removeEventListener("mouseover",f),document.removeEventListener("click",h)}),[n]);const m=(g,v)=>{a(g),e.autoSave&&!v&&e.onSubmit&&e.onSubmit(g)};return!r||!i?null:s.jsx("div",{children:s.jsxs(Ke,{testid:"questionnaire-form",onSubmit:()=>e.onSubmit(i),children:[s.jsx($R,{item:i,selectedKey:l,setSelectedKey:c,hoverKey:u,setHoverKey:d,onChange:m}),s.jsx(oe,{type:"submit",children:"Save"})]})})}function $R(e){var b;const t=e.item,n=e.item,r=ni(e.item),o=r||n.type===jt.group,i=n.linkId??"[untitled]",a=e.selectedKey===e.item.id,l=e.hoverKey===e.item.id,c=p.useRef();c.current=e.item;function u(x){yt(x),e.setSelectedKey(e.item.id)}function d(x){yt(x),e.setHoverKey(e.item.id)}function f(x){var j;const C=c.current;e.onChange({...C,item:(j=C.item)==null?void 0:j.map(T=>T.id===x.id?x:T)})}function h(x,C){e.onChange({...e.item,item:[...e.item.item??[],x]},C)}function m(x){var C;e.onChange({...e.item,item:(C=e.item.item)==null?void 0:C.filter(j=>j!==x)})}function g(x,C){e.onChange({...c.current,[x]:C})}function v(x){e.onChange({...e.item,...x})}function S(x){var C;e.onChange({...e.item,item:(C=e.item.item)==null?void 0:C.map(j=>j===x?{...j,repeats:!j.repeats}:j)})}function y(x,C){const j=EH(e.item.item,x,C);e.onChange({...e.item,item:j})}const w=rt(br.section,{[br.editing]:a,[br.hovering]:l&&!a});return s.jsxs("div",{"data-testid":n.linkId,className:w,onClick:u,onMouseOver:d,onFocus:d,children:[s.jsx("div",{className:br.questionBody,children:a?s.jsxs(s.Fragment,{children:[r&&s.jsx(ve,{size:"xl",defaultValue:t.title,onBlur:x=>g("title",x.currentTarget.value)}),!r&&s.jsx(Us,{autosize:!0,minRows:2,defaultValue:n.text,onBlur:x=>g("text",x.currentTarget.value)}),n.type==="reference"&&s.jsx(wH,{item:n,onChange:v}),UW(n)&&s.jsx(xH,{item:n,onChange:x=>v(x)})]}):s.jsxs(s.Fragment,{children:[t.title&&s.jsx(ge,{children:t.title}),n.text&&s.jsx("div",{children:n.text}),!o&&s.jsx(_g,{item:n,index:0,onChange:()=>{},response:{linkId:n.linkId}})]})}),(b=n.item)==null?void 0:b.map((x,C)=>s.jsx("div",{children:s.jsx($R,{item:x,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,isFirst:C===0,isLast:C===(e.item.item??[]).length-1,setHoverKey:e.setHoverKey,onChange:f,onRemove:()=>m(x),onRepeatable:S,onMoveUp:()=>y(C,-1),onMoveDown:()=>y(C,1)})},x.id)),!o&&s.jsx("div",{className:br.topActions,children:a?s.jsxs(s.Fragment,{children:[s.jsx(ve,{size:"xs",className:br.linkIdInput,defaultValue:n.linkId,onBlur:x=>g("linkId",x.currentTarget.value)}),!o&&s.jsx(It,{size:"xs",className:br.typeSelect,defaultValue:n.type,onChange:x=>g("type",x.currentTarget.value),data:[{value:"display",label:"Display"},{value:"boolean",label:"Boolean"},{value:"decimal",label:"Decimal"},{value:"integer",label:"Integer"},{value:"date",label:"Date"},{value:"dateTime",label:"Date/Time"},{value:"time",label:"Time"},{value:"string",label:"String"},{value:"text",label:"Text"},{value:"url",label:"URL"},{value:"choice",label:"Choice"},{value:"open-choice",label:"Open Choice"},{value:"attachment",label:"Attachment"},{value:"reference",label:"Reference"},{value:"quantity",label:"Quantity"}]})]}):s.jsx("div",{children:i})}),!r&&s.jsx(q,{className:br.movementActions,children:s.jsxs(q,{className:br.columnAlignment,children:[!e.isFirst&&s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),e.onMoveUp&&e.onMoveUp()},children:s.jsx(J8,{"data-testid":"up-button",size:15,className:br.movementIcons})}),!e.isLast&&s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),e.onMoveDown&&e.onMoveDown()},children:s.jsx(X8,{"data-testid":"down-button",size:15,className:br.movementIcons})})]})}),s.jsxs("div",{className:br.bottomActions,children:[o&&s.jsxs(s.Fragment,{children:[s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),h({id:As(),linkId:Ag("q"),type:"string",text:"Question"})},children:"Add item"}),s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),h({id:As(),linkId:Ag("g"),type:"group",text:"Group"},!0)},children:"Add group"})]}),r&&s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),h(CH(),!0)},children:"Add Page"}),a&&!r&&s.jsxs(s.Fragment,{children:[s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),e.onRepeatable&&e.onRepeatable(n)},children:n.repeats?"Remove Repeatable":"Make Repeatable"}),s.jsx(Ze,{href:"#",onClick:x=>{x.preventDefault(),e.onRemove&&e.onRemove()},children:"Remove"})]})]})]})}function xH(e){const t=Gs("QuestionnaireItemAnswerOption","value[x]"),n=e.item.answerOption??[];return s.jsxs("div",{children:[e.item.answerValueSet!==void 0?s.jsx(ve,{placeholder:"Enter Value Set",defaultValue:e.item.answerValueSet,onChange:r=>e.onChange({...e.item,answerValueSet:r.target.value})}):s.jsx(bH,{options:n,property:t,item:e.item,onChange:e.onChange}),s.jsxs(q,{display:"flex",children:[s.jsx(Ze,{href:"#",onClick:r=>{yt(r),e.onChange({...e.item,answerValueSet:void 0,answerOption:[...n,{id:As()}]})},children:"Add choice"}),s.jsx(Rh,{w:"lg"}),s.jsx(Ze,{href:"#",onClick:r=>{yt(r),e.onChange({...e.item,answerOption:[],answerValueSet:""})},children:"Add value set"})]})]})}function bH(e){return s.jsx("div",{children:e.options.map(t=>{const[n,r]=gu({type:"QuestionnaireItemAnswerOption",value:t},"value");return s.jsxs("div",{style:{display:"flex",flexDirection:"row",justifyContent:"space-between",alignItems:"center",width:"80%"},children:[s.jsx("div",{children:s.jsx(jl,{name:"value[x]",path:"Questionnaire.answerOption.value[x]",property:e.property,defaultPropertyType:r,defaultValue:n,onChange:(o,i)=>{const a=[...e.options],l=a.findIndex(c=>c.id===t.id);a[l]={id:t.id,[i]:o},e.onChange({...e.item,answerOption:a})},outcome:void 0},t.id)}),s.jsx("div",{children:s.jsx(Ze,{href:"#",onClick:o=>{yt(o),e.onChange({...e.item,answerOption:e.options.filter(i=>i.id!==t.id)})},children:"Remove"})})]},t.id)})})}function wH(e){const t=IR(e.item)??[];return s.jsxs(s.Fragment,{children:[t.map((n,r)=>s.jsxs(te,{children:[s.jsx(Kx,{name:"resourceType",placeholder:"Resource Type",defaultValue:n,onChange:o=>{e.onChange(Jp(e.item,t.map(i=>i===n?o:i)))}}),s.jsx(Ze,{href:"#",onClick:o=>{yt(o),e.onChange(Jp(e.item,t.filter(i=>i!==n)))},children:"Remove"})]},`${n}-${r}`)),s.jsx(Ze,{href:"#",onClick:n=>{yt(n),e.onChange(Jp(e.item,[...t,""]))},children:"Add Resource Type"})]})}let Dg=1,Ig=1;function Ag(e){return e+Dg++}function As(){return"id-"+Ig++}function SH(e){return{...e,id:e.id||As(),item:FR(e.item)}}function FR(e){if(e)return e.forEach(t=>{var n,r;(n=t.id)!=null&&n.match(/^id-\d+$/)&&(Ig=Math.max(Ig,parseInt(t.id.substring(3),10)+1)),(r=t.linkId)!=null&&r.match(/^q\d+$/)&&(Dg=Math.max(Dg,parseInt(t.linkId.substring(1),10)+1))}),e.map(t=>({...t,id:t.id||As(),item:FR(t.item),answerOption:jH(t.answerOption)}))}function jH(e){if(e)return e.map(t=>({...t,id:t.id||As()}))}function CH(){return{id:As(),linkId:Ag("s"),type:"group",text:"New Page",extension:[{url:"http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl",valueCodeableConcept:{coding:[{system:"http://hl7.org/fhir/questionnaire-item-control",code:"page"}]}}]}}function EH(e,t,n){const r=e??[],o=t+n;if(o<0||o>=r.length)return r;const i=[...r];return[i[t],i[o]]=[i[o],i[t]],i}function zR(e){const{item:t,response:n,onChange:r}=e,[o,i]=p.useState(TH(t,n??{linkId:t.linkId}));if(!e.checkForQuestionEnabled(t)||!n)return null;if(t.type===jt.display)return s.jsx("p",{children:t.text},t.linkId);const a=(t==null?void 0:t.repeats)&&t.type!==jt.choice&&t.type!==jt.openChoice;return t.type===jt.boolean?s.jsx(_g,{item:t,response:n,onChange:l=>r([l]),index:0},t.linkId):s.jsxs(vt,{htmlFor:e.item.linkId,title:e.item.text,withAsterisk:e.item.required,children:[[...Array(o)].map((l,c)=>s.jsx(_g,{item:t,response:n,onChange:u=>r([u]),index:c},`${t.linkId}-${c}`)),a&&s.jsx(Ze,{onClick:()=>i(l=>l+1),children:"Add Item"})]},e.item.linkId)}function TH(e,t){if(e.type===jt.choice||e.type===jt.openChoice)return 1;const n=t.answer;return n!=null&&n.length?n.length:1}function BR(e){const[t,n]=p.useState(e.response);if(t.length===0)return null;function r(i,a){const l=t.map((c,u)=>u===a?i[0]:c);n(l),e.onChange(l)}function o(){const i=NR(e.item);n([...t,i])}return s.jsxs(s.Fragment,{children:[t.map((i,a)=>s.jsx(UR,{item:e.item,response:i,checkForQuestionEnabled:e.checkForQuestionEnabled,onChange:l=>r(l,a)},i.id)),e.item.repeats&&s.jsx(Ze,{onClick:o,children:`Add Group: ${e.item.text}`})]})}function UR(e){var i;const{response:t,checkForQuestionEnabled:n,onChange:r}=e;function o(a){var d;const l=(d=t.item)==null?void 0:d.map(f=>a.find(m=>m.id===f.id)??f),c=l==null?void 0:l.concat(a.slice(1)),u={...t,item:c};r([u])}return e.checkForQuestionEnabled(e.item)?s.jsxs("div",{children:[e.item.text&&s.jsx(ge,{order:3,mb:"md",children:e.item.text}),s.jsx(Oe,{children:(i=e.item.item)==null?void 0:i.map(a=>{var l,c,u;return a.type===jt.group?a.repeats?s.jsx(BR,{item:a,response:((l=t.item)==null?void 0:l.filter(d=>d.linkId===a.linkId))??[],checkForQuestionEnabled:n,onChange:o},a.linkId):s.jsx(UR,{item:a,checkForQuestionEnabled:n,response:((c=t.item)==null?void 0:c.find(d=>d.linkId===a.linkId))??{linkId:a.linkId},onChange:o},a.linkId):s.jsx(zR,{item:a,response:(u=t.item)==null?void 0:u.find(d=>d.linkId===a.linkId),onChange:o,checkForQuestionEnabled:n},a.linkId)})})]},e.item.linkId):null}function PH(e){const{items:t,response:n,activePage:r,onChange:o,nextStep:i,prevStep:a,numberOfPages:l,renderPages:c,submitButtonText:u,excludeButtons:d,checkForQuestionEnabled:f}=e,h=t.map(m=>{var S;const g=((S=n==null?void 0:n.item)==null?void 0:S.filter(y=>y.linkId===m.linkId))??[],v=m.type===jt.group?s.jsx(BR,{item:m,response:g,onChange:o,checkForQuestionEnabled:f},m.linkId):s.jsx(zR,{item:m,response:g==null?void 0:g[0],onChange:o,checkForQuestionEnabled:f},m.linkId);return c?s.jsx(tl.Step,{label:m.text,children:v},m.linkId):v});return s.jsxs(s.Fragment,{children:[c&&s.jsx(tl,{active:r??0,allowNextStepsSelect:!1,p:6,children:h}),!c&&s.jsx(Oe,{children:h}),!d&&s.jsx(kH,{activePage:r??0,numberOfPages:l,nextStep:c?i:void 0,prevStep:c?a:void 0,renderPages:c,submitButtonText:u})]})}function kH(e){const t=e.renderPages&&e.activePage>0,n=e.renderPages&&e.activePage<e.numberOfPages-1,r=!e.renderPages||e.activePage===e.numberOfPages-1;return s.jsxs(te,{justify:"flex-end",mt:"xl",gap:"xs",children:[t&&s.jsx(oe,{onClick:e.prevStep,children:"Back"}),n&&s.jsx(oe,{onClick:o=>{const i=o.currentTarget.closest("form");e.nextStep&&i.reportValidity()&&e.nextStep()},children:"Next"}),r&&s.jsx(oe,{type:"submit",children:e.submitButtonText??"Submit"})]})}function VR(e){const t=se(),n=t.getProfile(),[r,o]=p.useState(!1),i=wt(e.questionnaire),[a,l]=p.useState(),[c,u]=p.useState(0),{onChange:d}=e;p.useEffect(()=>{t.requestSchema("Questionnaire").then(()=>t.requestSchema("QuestionnaireResponse")).then(()=>o(!0)).catch(console.log)},[t]),p.useEffect(()=>{l(i?QW(i):void 0)},[i]);const f=p.useCallback(S=>{l(y=>{const w=(y==null?void 0:y.item)??[],x={resourceType:"QuestionnaireResponse",status:"in-progress",item:WR(w,Array.isArray(S)?S:[S])};if(d)try{d(x)}catch(C){console.error("Error invoking QuestionnaireForm.onChange callback",C)}return x})},[d]);function h(S){return VW(S,(a==null?void 0:a.item)??[])}if(!r||!i||!a)return null;const m=ZW(i),g=()=>u(S=>S+1),v=()=>u(S=>S-1);return s.jsx(MR.Provider,{value:{subject:e.subject,encounter:e.encounter},children:s.jsxs(Ke,{testid:"questionnaire-form",onSubmit:()=>{e.onSubmit&&a&&e.onSubmit({...a,questionnaire:st(i),subject:e.subject,source:Et(n),authored:new Date().toISOString(),status:"completed"})},children:[i.title&&s.jsx(ge,{children:i.title}),s.jsx(PH,{items:i.item??[],response:a,onChange:f,renderPages:!e.disablePagination&&m>1,activePage:c,numberOfPages:m,excludeButtons:e.excludeButtons,submitButtonText:e.submitButtonText,checkForQuestionEnabled:h,nextStep:g,prevStep:v})]})})}function RH(e,t){const n=WR(e.item??[],t.item??[]);return{...t,item:n.length>0?n:void 0,answer:t.answer&&t.answer.length>0?t.answer:e.answer}}function WR(e,t){const n=[],r=new Set;for(const o of e){const i=o.id,a=t.find(l=>l.id===i);a?(n.push(RH(o,a)),r.add(a.id)):n.push(o)}for(const o of t)r.has(o.id)||n.push(o);return n}const _H="_section_4m5it_1",DH={section:_H},IH=["gender","age","gestationalAge","context","appliesTo","category"],AH={definition:{resourceType:"ObservationDefinition",code:{text:""}},onSubmit:()=>{}};function NH(e){e=Object.assign(AH,e);const t=e.definition,[n,r]=p.useState([]),[o,i]=p.useState(1),[a,l]=p.useState(1);return p.useEffect(()=>{const g=LH(t,l);r($H(g.qualifiedInterval||[],i))},[t]),s.jsxs(Ke,{testid:"reference-range-editor",onSubmit:c,children:[s.jsx(Oe,{children:n.map(g=>{var v;return s.jsx(MH,{unit:zH((v=t.quantitativeDetails)==null?void 0:v.unit),onChange:f,onAdd:h,onRemove:m,onRemoveGroup:d,intervalGroup:g},`group-${g.id}`)})}),s.jsx(tn,{title:"Add Group",variant:"subtle",size:"sm",onClick:g=>{yt(g),u({id:`group-id-${o}`,filters:{},intervals:[]}),i(v=>v+1)},children:s.jsx(yf,{})}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{type:"submit",children:"Save"})})]});function c(){const g=n.flatMap(v=>v.intervals).filter(v=>!BH(v));e.onSubmit({...t,qualifiedInterval:g})}function u(g){r(v=>[...v,g])}function d(g){r(v=>v.filter(S=>S.id!==g.id))}function f(g,v){r(S=>{S=[...S];const y=S.find(b=>b.id===g),w=y==null?void 0:y.intervals.findIndex(b=>b.id===v.id);return w!==void 0&&(y!=null&&y.intervals[w])&&(y.intervals[w]=v),S})}function h(g,v){v.id===void 0&&(v.id=`id-${a}`,l(S=>S+1)),r(S=>{S=[...S];const y=S.findIndex(w=>w.id===g);if(y!==-1){const w={...S[y]};v={...v,...w.filters},w.intervals=[...w.intervals,v],S[y]=w}return S})}function m(g,v){r(S=>{S=[...S];const y=S.find(w=>w.id===g);return y&&(y.intervals=y.intervals.filter(w=>w.id!==v.id)),S})}}function MH(e){const{intervalGroup:t,unit:n}=e;return s.jsx(yu,{"data-testid":t.id,className:DH.section,children:s.jsxs(Oe,{gap:"lg",children:[s.jsx(te,{justify:"flex-end",children:s.jsx(tn,{title:"Remove Group",variant:"subtle","data-testid":`remove-group-button-${t.id}`,size:"sm",onClick:r=>{yt(r),e.onRemoveGroup(t)},children:s.jsx(vf,{})},`remove-group-button-${t.id}`)}),s.jsx(OH,{intervalGroup:t,onChange:e.onChange}),s.jsx(cn,{}),t.intervals.map(r=>s.jsxs(Oe,{gap:"xs",children:[s.jsxs(te,{children:[s.jsx(ve,{"data-testid":`condition-${r.id}`,defaultValue:r.condition,label:"Condition: ",size:"sm",onChange:o=>{yt(o),e.onChange(t.id,{...r,condition:o.currentTarget.value.trim()})}},`condition-${r.id}`),s.jsx(tn,{title:"Remove Interval",variant:"subtle",size:"sm","data-testid":`remove-interval-${r.id}`,onClick:o=>{yt(o),e.onRemove(t.id,r)},children:s.jsx(vf,{})},`remove-interval-${r.id}`)]}),s.jsx(Zx,{path:"",onChange:o=>{e.onChange(t.id,{...r,range:o})},name:`range-${r.id}`,defaultValue:r.range},`range-${r.id}`)]},`interval-${r.id}`)),s.jsx(tn,{title:"Add Interval",variant:"subtle",size:"sm",onClick:r=>{yt(r),e.onAdd(t.id,{range:{low:{unit:n},high:{unit:n}}})},children:s.jsx(yf,{})})]})})}function OH(e){var r,o;const{intervalGroup:t,onChange:n}=e;t.filters.age||(t.filters.age={});for(const i of["low","high"])(r=t.filters.age[i])!=null&&r.unit||(t.filters.age[i]={...t.filters.age[i],unit:"years",system:"http://unitsofmeasure.org"});return s.jsxs(Oe,{style:{maxWidth:"50%"},children:[s.jsx(te,{children:s.jsx(It,{data:["","male","female"],label:"Gender:",defaultValue:t.filters.gender||"",onChange:i=>{for(const a of t.intervals){let l=i.currentTarget.value;l===""&&(l=void 0),n(t.id,{...a,gender:l})}}})}),s.jsxs(te,{gap:"xs",children:[s.jsx(fe,{component:"label",htmlFor:`div-age-${t.id}`,children:"Age:"}),s.jsx("div",{id:`div-age-${t.id}`,children:s.jsx(Zx,{path:"",name:`age-${t.id}`,defaultValue:t.filters.age,onChange:i=>{for(const a of t.intervals)n(t.id,{...a,age:i})}},`age-${t.id}`)})]}),s.jsx(It,{data:["","pre-puberty","follicular","midcycle","luteal","postmenopausal"],label:"Endocrine:",defaultValue:((o=t.filters.context)==null?void 0:o.text)||"",onChange:i=>{for(const a of t.intervals){let l=i.currentTarget.value;l===""?(l=void 0,n(t.id,{...a,context:void 0})):n(t.id,{...a,context:{text:l,coding:[{code:l,system:"http://terminology.hl7.org/CodeSystem/referencerange-meaning"}]}})}}}),s.jsx(It,{data:["","reference","critical","absolute"],label:"Category: ",defaultValue:t.filters.category,onChange:i=>{for(const a of t.intervals){const l=i.currentTarget.value;l===""?n(t.id,{...a,category:void 0}):n(t.id,{...a,category:l})}}})]})}function LH(e,t){const n=e.qualifiedInterval||[];let r=Math.max(...n.map(o=>{var a;const i=parseInt(((a=o.id)==null?void 0:a.substring(3))||"",10);return isNaN(i)?Number.NEGATIVE_INFINITY:i}))+1;return Number.isFinite(r)||(r=1),e={...e,qualifiedInterval:n.map(o=>({...o,id:o.id||`id-${r++}`}))},t(r),e}function $H(e,t){let n=1;const r={};for(const o of e){const i=FH(o);i in r||(r[i]={id:`group-id-${n++}`,filters:Object.fromEntries(IH.map(a=>[a,o[a]])),intervals:[]}),r[i].intervals.push(o)}return t(n),Object.values(r)}function FH(e){var n,r;return[`gender=${e.gender}`,`age=${Mc(e.age)}`,`gestationalAge=${Mc(e.gestationalAge)}`,`context=${(n=e.context)==null?void 0:n.text}`,`appliesTo=${(r=e.appliesTo)==null?void 0:r.map(o=>o.text).join("+")}`,`category=${e.category}`].join(":")}function zH(e){return e&&(v6(e,"http://unitsofmeasure.org")||e.text)}function BH(e){var t,n,r,o;return((n=(t=e.range)==null?void 0:t.low)==null?void 0:n.value)===void 0&&((o=(r=e.range)==null?void 0:r.high)==null?void 0:o.value)===void 0}function UH(e){var u;const t=se(),n=wt(e.value),[r,o]=p.useState(!1),[i,a]=p.useState();if(p.useEffect(()=>{n&&!r&&(t.executeBatch(l(n)).then(a).catch(console.log),o(!0))},[t,n,r]),!n||!i)return null;return s.jsx(ur,{children:(u=n.action)==null?void 0:u.map((d,f)=>{var v,S,y,w,b,x;const h=d.resource&&c(d.resource),m=(S=(v=h==null?void 0:h.input)==null?void 0:v[0])==null?void 0:S.valueReference,g=(w=(y=h==null?void 0:h.output)==null?void 0:y[0])==null?void 0:w.valueReference;return s.jsxs(p.Fragment,{children:[s.jsx(ur.Col,{span:1,p:"md",children:(h==null?void 0:h.status)==="completed"?s.jsx(az,{}):s.jsx(Iz,{color:"gray"})}),s.jsxs(ur.Col,{span:9,p:"xs",children:[s.jsx(fe,{fw:500,children:d.title}),d.description&&s.jsx("div",{children:d.description}),s.jsxs("div",{children:["Last edited by ",s.jsx(Cl,{value:(b=h==null?void 0:h.meta)==null?void 0:b.author})," on ",Fn((x=h==null?void 0:h.meta)==null?void 0:x.lastUpdated)]}),s.jsxs("div",{children:["Status: ",s.jsx(n0,{status:(h==null?void 0:h.status)||"unknown"})]})]}),s.jsxs(ur.Col,{span:2,p:"md",children:[m&&!g&&s.jsx(oe,{onClick:()=>e.onStart(h,m),children:"Start"}),m&&g&&s.jsx(oe,{onClick:()=>e.onEdit(h,m,g),children:"Edit"})]})]},`action-${f}`)})});function l(d){var h;const f=[];if(d.action)for(const m of d.action)(h=m.resource)!=null&&h.reference&&f.push({request:{method:"GET",url:m.resource.reference}});return{resourceType:"Bundle",type:"batch",entry:f}}function c(d){for(const f of i==null?void 0:i.entry)if(f.resource&&d.reference===st(f.resource))return f.resource}}function HR(e,t){const n=VH(e,t);return WH(n,e,t)}function VH(e,t){const n=e.length,r=t.length,o=n+r+1,i=1+2*o,a=i/2|0,l=new Array(i);l[a+1]={i:0,j:-1,prev:void 0,snake:!0};for(let c=0;c<o;c++){for(let u=-c;u<=c;u+=2){const d=a+u,f=d+1,h=d-1,m=l[f],g=l[h];let v,S=0;u===-c||u!==c&&g.i<m.i?(S=m.i,v=m):(S=g.i+1,v=g),l[h]=void 0;let y=S-u,w={i:S,j:y,prev:HH(v),snake:!1};for(;S<n&&y<r&&e[S]===t[y];)S++,y++;if(S>w.i&&(w={i:S,j:y,prev:w,snake:!0}),l[d]=w,S>=n&&y>=r)return l[d]}l[a+c-1]=void 0}}function WH(e,t,n){const r=[];let o=e;for(o.snake&&(o=o.prev);o!=null&&o.prev&&o.prev.j>=0;){const i=o.i,a=o.j;o=o.prev;const l=o.i,c=o.j,u={position:l,lines:t.slice(l,i)},d={position:c,lines:n.slice(c,a)};let f;u.lines.length===0&&d.lines.length>0?f="insert":u.lines.length>0&&d.lines.length===0?f="delete":f="change",r.push({original:u,revised:d,type:f}),o.snake&&(o=o.prev)}return r}function HH(e){return e&&!e.snake&&e.prev?e.prev:e}function qH(e){const t=e.entry.filter(r=>!!r.resource).map(r=>{var o;return{meta:(o=r.resource)==null?void 0:o.meta,lines:pr(r.resource,!0).match(/[^\r\n]+/g)}}).sort((r,o)=>r.meta.lastUpdated.localeCompare(o.meta.lastUpdated)),n=t[0].lines.map(r=>({id:t[0].meta.versionId,meta:t[0].meta,value:r,span:1}));return GH(n,t),QH(n),n}function GH(e,t){for(let n=1;n<t.length;n++){const r=HR(t[n-1].lines,t[n].lines);for(const o of r){const i=o.original.position,a=o.original.lines,l=o.revised.lines;if((o.type==="delete"||o.type==="change")&&e.splice(i,a.length),o.type==="insert"||o.type==="change")for(let c=0;c<o.revised.lines.length;c++)e.splice(i+c,0,{id:t[n].meta.versionId,meta:t[n].meta,value:l[c],span:1})}}}function QH(e){let t=0;for(;t<e.length;){let n=t;for(;n<e.length&&e[n].id===e[t].id;)e[n].span=-1,n++;e[t].span=n-t,t=n}}const KH="_container_1oj0p_1",YH="_root_1oj0p_5",XH="_startRow_1oj0p_20",JH="_normalRow_1oj0p_24",ZH="_author_1oj0p_28",eq="_dateTime_1oj0p_32",tq="_lineNumber_1oj0p_37",nq="_line_1oj0p_37",rq="_pre_1oj0p_52",Co={container:KH,root:YH,startRow:XH,normalRow:JH,author:ZH,dateTime:eq,lineNumber:tq,line:nq,pre:rq};function oq(e,t){return`/${e.resourceType}/${e.id}/_history/${t}`}function iq(e){const t=Math.floor((Date.now()-Date.parse(e))/1e3),n=Math.floor(t/31536e3);if(n>0)return fa(n,"year");const r=Math.floor(t/2592e3);if(r>0)return fa(r,"month");const o=Math.floor(t/86400);if(o>0)return fa(o,"day");const i=Math.floor(t/3600);if(i>0)return fa(i,"hour");const a=Math.floor(t/60);return a>0?fa(a,"minute"):fa(t,"second")}function fa(e,t){return`${e} ${e===1?t:t+"s"} ago`}function sq(e){var a,l;const t=se(),[n,r]=p.useState(e.history);if(p.useEffect(()=>{!e.history&&e.resourceType&&e.id&&t.readHistory(e.resourceType,e.id).then(r).catch(console.log)},[t,e.history,e.resourceType,e.id]),!n)return s.jsx("div",{children:"Loading..."});const o=(l=(a=n.entry)==null?void 0:a[0])==null?void 0:l.resource;if(!o)return null;const i=qH(n);return s.jsx("div",{className:Co.container,children:s.jsx("table",{className:Co.root,children:s.jsx("tbody",{children:i.map((c,u)=>s.jsxs("tr",{className:c.span>0?Co.startRow:Co.normalRow,children:[c.span>0&&s.jsxs(s.Fragment,{children:[s.jsx("td",{className:Co.author,rowSpan:c.span,children:s.jsx(Ua,{value:c.meta.author,link:!0})}),s.jsx("td",{className:Co.dateTime,rowSpan:c.span,children:s.jsx(Ge,{to:oq(o,c.meta.versionId),children:iq(c.meta.lastUpdated)})})]}),s.jsx("td",{className:Co.lineNumber,children:u+1}),s.jsx("td",{className:Co.line,children:s.jsx("pre",{className:Co.pre,children:c.value})})]},"row-"+u))})})})}const aq="_removed_mgz0k_2",lq="_added_mgz0k_7",Bw={removed:aq,added:lq};function cq(e){let t=e.original,n=e.revised;e.ignoreMeta&&(t={...t,meta:void 0},n={...n,meta:void 0});const r=pr(t,!0).match(/[^\r\n]+/g),o=pr(n,!0).match(/[^\r\n]+/g),i=HR(r,o);return s.jsx("pre",{style:{color:"gray"},children:i.map((a,l)=>s.jsx(uq,{delta:a},"delta"+l))})}function uq(e){return s.jsxs(s.Fragment,{children:["...",s.jsx("br",{}),e.delta.original.lines.length>0&&s.jsx("div",{className:Bw.removed,children:e.delta.original.lines.join(`
542
542
  `)}),e.delta.revised.lines.length>0&&s.jsx("div",{className:Bw.added,children:e.delta.revised.lines.join(`
543
- `)}),"...",s.jsx("br",{})]})}const uq="_splitButton_1i0gi_1",dq="_menuControl_1i0gi_6",Uw={splitButton:uq,menuControl:dq};function jf(e){const{outcome:t}=e,n=se(),r=wt(e.defaultValue),o=r==null?void 0:r.resourceType,[i,a]=p.useState(!1),[l,c]=p.useState(),u=n.getAccessPolicy(),d=At();p.useEffect(()=>{if(r)if(e.profileUrl){const m=e.profileUrl;n.requestProfileSchema(e.profileUrl,{expandProfile:!0}).then(()=>{const g=yl(m);if(g){a(!0);const v=L8(r,g);c(v)}else console.error(`Schema not found for ${m}`)}).catch(g=>{console.error("Error in requestProfileSchema",g)})}else n.requestSchema(o).then(()=>{c(r),a(!0)}).catch(console.log)},[n,r,o,e.profileUrl]);const f=p.useMemo(()=>r&&gk(r,Ox.READ,u),[u,r]),h=p.useMemo(()=>n.isSuperAdmin()||!u||!Bt(l==null?void 0:l.resourceType)?!0:WF(u,l==null?void 0:l.resourceType),[n,u,l==null?void 0:l.resourceType]);return!i||!l?s.jsx("div",{children:"Loading..."}):h?s.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:m=>{m.preventDefault(),e.onSubmit&&e.onSubmit(l)},children:[s.jsxs(Oe,{mb:"xl",children:[s.jsx(vt,{title:"Resource Type",htmlFor:"resourceType",outcome:t,children:s.jsx(ve,{name:"resourceType",defaultValue:l.resourceType,disabled:!0})}),s.jsx(vt,{title:"ID",htmlFor:"id",outcome:t,children:s.jsx(ve,{name:"id",defaultValue:l.id,disabled:!0})})]}),s.jsx(t0,{path:l.resourceType,valuePath:l.resourceType,typeName:o,defaultValue:l,outcome:t,onChange:c,profileUrl:e.profileUrl,accessPolicyResource:f}),s.jsxs(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",gap:0,children:[s.jsx(oe,{type:"submit",className:rt((e.onPatch||e.onDelete)&&Uw.splitButton),children:r!=null&&r.id?"Update":"Create"}),(e.onPatch||e.onDelete)&&s.jsxs(J,{transitionProps:{transition:"pop"},position:"bottom-end",withinPortal:!0,children:[s.jsx(J.Target,{children:s.jsx(tn,{variant:"filled",color:d.primaryColor,size:36,className:Uw.menuControl,"aria-label":"More actions",children:s.jsx(Bx,{size:14,stroke:1.5})})}),s.jsxs(J.Dropdown,{children:[e.onPatch&&s.jsx(J.Item,{leftSection:s.jsx(Nk,{size:14,stroke:1.5}),onClick:()=>{e.onPatch(l)},children:"Patch"}),e.onDelete&&s.jsx(J.Item,{color:"red",leftSection:s.jsx(Hx,{size:14,stroke:1.5,color:"red"}),onClick:()=>{e.onDelete(l)},children:"Delete"})]})]})]})]}):s.jsxs(Vi,{color:"red",title:"Permission denied",icon:s.jsx(Sl,{}),children:["Your access level prevents you from editing and creating ",l.resourceType," resources."]})}function fq(e){var o;const t=se(),[n,r]=p.useState(e.history);return p.useEffect(()=>{!e.history&&e.resourceType&&e.id&&t.readHistory(e.resourceType,e.id).then(r).catch(console.log)},[t,e.history,e.resourceType,e.id]),n?s.jsxs(de,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[s.jsx(de.Thead,{children:s.jsxs(de.Tr,{children:[s.jsx(de.Th,{children:"Author"}),s.jsx(de.Th,{children:"Date"}),s.jsx(de.Th,{children:"Version"})]})}),s.jsx(de.Tbody,{children:(o=n.entry)==null?void 0:o.map((i,a)=>s.jsx(hq,{entry:i},"entry-"+a))})]}):s.jsx("div",{children:"Loading..."})}function hq(e){var r,o,i;const{response:t,resource:n}=e.entry;return n?s.jsxs(de.Tr,{children:[s.jsx(de.Td,{children:s.jsx(Ua,{value:(r=n.meta)==null?void 0:r.author,link:!0})}),s.jsx(de.Td,{children:Fn((o=n.meta)==null?void 0:o.lastUpdated)}),s.jsx(de.Td,{children:s.jsx(Ge,{to:pq(n),children:(i=n.meta)==null?void 0:i.versionId})})]}):s.jsx(de.Tr,{children:s.jsx(de.Td,{colSpan:3,children:De(t==null?void 0:t.outcome)})})}function pq(e){var t;return`/${e.resourceType}/${e.id}/_history/${(t=e.meta)==null?void 0:t.versionId}`}function mq(e){const{serviceRequest:t,...n}=e;return s.jsx(Uh,{value:t,loadTimelineResources:async(r,o,i)=>{const a=`${o}/${i}`,l=100;return Promise.allSettled([r.readHistory("ServiceRequest",i),r.search("Communication",{"based-on":a,_count:l}),r.search("DiagnosticReport",{"based-on":a,_count:l}),r.search("Media",{"based-on":a,_count:l}),r.search("DocumentReference",{related:a,_count:l}),r.search("Task",{_filter:`based-on eq ${a} or focus eq ${a} or subject eq ${a}`,_count:l})])},createCommunication:(r,o,i)=>({resourceType:"Communication",status:"completed",basedOn:[Et(r)],subject:r.subject,sender:Et(o),sent:new Date().toISOString(),payload:[{contentString:i}]}),createMedia:(r,o,i)=>({resourceType:"Media",status:"completed",basedOn:[Et(r)],subject:r.subject,operator:Et(o),issued:new Date().toISOString(),content:i}),...n})}function gq(e){const t=se(),{client:n,patient:r,encounter:o,children:i,...a}=e;function l(){t.createResource({resourceType:"SmartAppLaunch",patient:r,encounter:o}).then(c=>{const u=new URL(n.launchUri);u.searchParams.set("iss",t.getBaseUrl()+"fhir/R4"),u.searchParams.set("launch",c.id),window.location.assign(u.toString())}).catch(c=>he({color:"red",message:De(c),autoClose:!1}))}return s.jsx(Ze,{onClick:()=>l(),...a,children:i})}function qR(e){const t=se(),[n,r]=p.useState();return s.jsxs(Ke,{onSubmit:async o=>{try{e.handleAuthResponse(await t.startNewProject({login:e.login,projectName:o.projectName}))}catch(i){r(ht(i))}},children:[s.jsxs(mn,{style:{flexDirection:"column"},children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Create project"})]}),s.jsxs(Oe,{gap:"xl",children:[s.jsx(ve,{name:"projectName",label:"Project Name",placeholder:"My Project",required:!0,autoFocus:!0,error:Je(n,"projectName")}),s.jsxs(fe,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",s.jsx(Ze,{href:"https://www.medplum.com/privacy",children:"Privacy Policy"})," and ",s.jsx(Ze,{href:"https://www.medplum.com/terms",children:"Terms of Service"}),"."]})]}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(oe,{type:"submit",children:"Create project"})})]})}function GR(e,t){const n=document.getElementsByTagName("head")[0],r=document.createElement("script");r.async=!0,r.src=e,r.onload=t??null,n.appendChild(r)}function QR(e){const t=se(),{googleClientId:n,handleGoogleCredential:r}=e,o=p.useRef(null),[i,a]=p.useState(typeof google<"u"),[l,c]=p.useState(!1),[u,d]=p.useState(!1);return p.useEffect(()=>{if(typeof google>"u"){GR("https://accounts.google.com/gsi/client",()=>a(!0));return}l||(google.accounts.id.initialize({client_id:n,callback:r}),c(!0)),o.current&&!u&&(google.accounts.id.renderButton(o.current,{}),d(!0))},[t,n,l,i,o,u,r]),n?s.jsx("div",{ref:o}):null}function KR(e){if(e)return e;if(typeof window<"u"){const t=window.location.protocol+"//"+window.location.host;if([].includes(t))return"__GOOGLE_CLIENT_ID__"}}function YR(e){typeof grecaptcha>"u"&&GR("https://www.google.com/recaptcha/api.js?render="+e)}function XR(e){return new Promise((t,n)=>{grecaptcha.ready(async()=>{try{t(await grecaptcha.execute(e,{action:"submit"}))}catch(r){n(r)}})})}function vq(e){const t=KR(e.googleClientId),n=e.recaptchaSiteKey,r=se(),[o,i]=p.useState(),a=vu(o,void 0);return p.useEffect(()=>{n&&YR(n)},[n]),s.jsxs(Ke,{onSubmit:async l=>{try{let c="";n&&(c=await XR(n)),e.handleAuthResponse(await r.startNewUser({projectId:e.projectId,clientId:e.clientId,firstName:l.firstName,lastName:l.lastName,email:l.email,password:l.password,remember:l.remember==="true",recaptchaSiteKey:n,recaptchaToken:c}))}catch(c){i(ht(c))}},children:[s.jsx(mn,{style:{flexDirection:"column"},children:e.children}),s.jsx(Mr,{issues:a}),t&&s.jsxs(s.Fragment,{children:[s.jsx(te,{justify:"center",p:"xl",style:{height:70},children:s.jsx(QR,{googleClientId:t,handleGoogleCredential:async l=>{try{e.handleAuthResponse(await r.startGoogleLogin({googleClientId:l.clientId,googleCredential:l.credential,projectId:e.projectId,createUser:!0}))}catch(c){i(ht(c))}}})}),s.jsx(cn,{label:"or",labelPosition:"center",my:"lg"})]}),s.jsxs(Oe,{gap:"xl",children:[s.jsx(ve,{name:"firstName",type:"text",label:"First name",placeholder:"First name",required:!0,autoFocus:!0,error:Je(o,"firstName")}),s.jsx(ve,{name:"lastName",type:"text",label:"Last name",placeholder:"Last name",required:!0,error:Je(o,"lastName")}),s.jsx(ve,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,error:Je(o,"email")}),s.jsx(Qr,{name:"password",label:"Password",autoComplete:"off",required:!0,error:Je(o,"password")}),s.jsxs(fe,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",s.jsx(Ze,{href:"https://www.medplum.com/privacy",children:"Privacy Policy"})," and ",s.jsx(Ze,{href:"https://www.medplum.com/terms",children:"Terms of Service"}),"."]}),s.jsxs(fe,{c:"dimmed",size:"xs",children:["This site is protected by reCAPTCHA and the Google"," ",s.jsx(Ze,{href:"https://policies.google.com/privacy",children:"Privacy Policy"})," and ",s.jsx(Ze,{href:"https://policies.google.com/terms",children:"Terms of Service"})," apply."]})]}),s.jsxs(te,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[s.jsx(_n,{name:"remember",label:"Remember me",size:"xs"}),s.jsx(oe,{type:"submit",children:"Create account"})]})]})}function yq(e){const{type:t,projectId:n,clientId:r,googleClientId:o,recaptchaSiteKey:i,onSuccess:a}=e,l=se(),[c,u]=p.useState(),[d,f]=p.useState();p.useEffect(()=>{t==="patient"&&c&&l.startNewPatient({login:c,projectId:n}).then(m=>l.processCode(m.code)).then(()=>a()).catch(m=>f(ht(m)))},[l,t,n,c,a]);function h(m){m.code?l.processCode(m.code).then(()=>a()).catch(console.log):m.login&&u(m.login)}return s.jsxs(Ne,{width:450,children:[d&&s.jsx("pre",{children:JSON.stringify(d,null,2)}),!c&&s.jsx(vq,{projectId:n,clientId:r,googleClientId:o,recaptchaSiteKey:i,handleAuthResponse:h,children:e.children}),c&&t==="project"&&s.jsx(qR,{login:c,handleAuthResponse:h})]})}function xq(e){const[t,n]=p.useState();return t?s.jsx(wq,{email:t,...e}):s.jsx(bq,{setEmail:n,...e})}function bq(e){const{setEmail:t,onRegister:n,handleAuthResponse:r,children:o,disableEmailAuth:i,...a}=e,l=se(),c=!e.disableGoogleAuth&&KR(e.googleClientId),[u,d]=p.useState(),f=vu(u,void 0),h=p.useCallback(async v=>{if(!v.authorizeUrl)return!1;const S=JSON.stringify({...await l.ensureCodeChallenge(a),domain:v.domain}),y=new URL(v.authorizeUrl);return y.searchParams.set("state",S),window.location.assign(y.toString()),!0},[l,a]),m=p.useCallback(async v=>{const S=await l.post("auth/method",{email:v.email});await h(S)||t(v.email)},[l,h,t]),g=p.useCallback(async v=>{try{const S=await l.startGoogleLogin({...a,googleCredential:v.credential});await h(S)||r(S)}catch(S){d(ht(S))}},[l,a,h,r]);return s.jsxs(Ke,{onSubmit:m,children:[s.jsx(mn,{style:{flexDirection:"column"},children:o}),s.jsx(Mr,{issues:f}),c&&s.jsxs(s.Fragment,{children:[s.jsx(te,{justify:"center",p:"xl",style:{height:70},children:s.jsx(QR,{googleClientId:c,handleGoogleCredential:g})}),!i&&s.jsx(cn,{label:"or",labelPosition:"center",my:"lg"})]}),!i&&s.jsx(ve,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:Je(u,"email")}),s.jsxs(te,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[s.jsx("div",{children:n&&s.jsx(Ze,{component:"button",type:"button",color:"dimmed",onClick:n,size:"xs",children:"Register"})}),!i&&s.jsx(oe,{type:"submit",children:"Next"})]})]})}function wq(e){const{onForgotPassword:t,handleAuthResponse:n,children:r,...o}=e,i=se(),[a,l]=p.useState(),c=vu(a,void 0),u=p.useCallback(d=>{i.startLogin({...o,password:d.password,remember:d.remember==="on"}).then(n).catch(f=>l(ht(f)))},[i,o,n]);return s.jsxs(Ke,{onSubmit:u,children:[s.jsx(mn,{style:{flexDirection:"column"},children:r}),s.jsx(Mr,{issues:c}),s.jsx(Oe,{gap:"xl",children:s.jsx(Qr,{name:"password",label:"Password",autoComplete:"off",required:!0,autoFocus:!0,error:Je(a,"password")})}),s.jsxs(te,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[t&&s.jsx(Ze,{component:"button",type:"button",c:"dimmed",onClick:t,size:"xs",children:"Forgot password"}),s.jsx(_n,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1}}),s.jsx(oe,{type:"submit",children:"Sign in"})]})]})}function Sq(e){const t=se(),n=nu(),[r,o]=p.useState(""),[i,a]=p.useState();function l(f){var h;return!!((h=f==null?void 0:f.toLowerCase())!=null&&h.includes(r.toLowerCase()))}function c(f){var h,m;return l((h=f.profile)==null?void 0:h.display)||l((m=f.project)==null?void 0:m.display)}function u(f){t.post("auth/profile",{login:e.login,profile:f}).then(e.handleAuthResponse).catch(h=>a(ht(h)))}const d=e.memberships.filter(c).slice(0,10).map(f=>s.jsx(Me.Option,{value:f.id,children:s.jsx(jq,{...f})},f.id));return s.jsxs(Oe,{children:[s.jsxs(Es,{gap:"md",mb:"md",justify:"center",align:"center",direction:"column",wrap:"nowrap",children:[s.jsx(ro,{size:32}),s.jsx(ge,{order:3,children:"Choose profile"})]}),s.jsx(Mr,{outcome:i}),s.jsxs(Me,{store:n,onOptionSubmit:u,children:[s.jsx(Me.EventsTarget,{children:s.jsx(ve,{placeholder:"Search",value:r,onChange:f=>{o(f.currentTarget.value),n.updateSelectedOptionIndex()}})}),s.jsx("div",{children:s.jsx(Me.Options,{children:d.length>0?d:s.jsx(Me.Empty,{children:"Nothing found..."})})})]})]})}function jq(e){var t,n;return s.jsxs(te,{children:[s.jsx(Ts,{radius:"xl"}),s.jsxs("div",{children:[s.jsx(fe,{fz:"sm",fw:500,children:(t=e.profile)==null?void 0:t.display}),s.jsx(fe,{fz:"xs",opacity:.6,children:(n=e.project)==null?void 0:n.display})]})]})}function Cq(e){const t=se();return s.jsx(Ke,{onSubmit:n=>{t.post("auth/scope",{login:e.login,scope:Object.keys(n).join(" ")}).then(e.handleAuthResponse).catch(console.log)},children:s.jsxs(Oe,{children:[s.jsxs(mn,{style:{flexDirection:"column"},children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Choose scope"})]}),s.jsx(Oe,{children:(e.scope??"openid").split(" ").map(n=>s.jsx(_n,{id:n,name:n,label:n,defaultChecked:!0},n))}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{type:"submit",children:"Set scope"})})]})})}function Eq(e){const t=se(),[n,r]=p.useState();return s.jsx(Ke,{onSubmit:o=>{r(void 0),t.post("auth/mfa/verify",{login:e.login,token:o.token}).then(e.handleAuthResponse).catch(i=>r(De(i)))},children:s.jsxs(Oe,{children:[s.jsxs(mn,{style:{flexDirection:"column"},children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Enter MFA code"})]}),n&&s.jsx(Vi,{icon:s.jsx(Sl,{size:16}),title:"Error",color:"red",children:n}),s.jsx(Oe,{children:s.jsx(ve,{name:"token",label:"MFA code",required:!0,autoFocus:!0})}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{type:"submit",children:"Submit code"})})]})})}function JR(e){const{login:t,chooseScopes:n,onSuccess:r,onForgotPassword:o,onRegister:i,onCode:a,...l}=e,c=se(),[u,d]=p.useState(),f=p.useRef(!1),[h,m]=p.useState(!1),[g,v]=p.useState(),S=p.useCallback(b=>{a?a(b):c.processCode(b).then(()=>{r&&r()}).catch(x=>he({color:"red",message:De(x)}))},[c,a,r]),y=p.useCallback(b=>{m(!!b.mfaRequired),b.login&&d(b.login),b.memberships&&v(b.memberships),b.code&&(n?v(void 0):S(b.code))},[n,S]),w=p.useCallback(b=>{S(b.code)},[S]);return p.useEffect(()=>{t&&!f.current&&!u&&(f.current=!0,c.get("auth/login/"+t).then(y).catch(b=>he({color:"red",message:De(b)})))},[c,t,f,u,y]),s.jsx(Ne,{width:450,px:"sm",py:"md",children:u?h?s.jsx(Eq,{login:u,handleAuthResponse:y}):g?s.jsx(Sq,{login:u,memberships:g,handleAuthResponse:y}):e.projectId==="new"?s.jsx(qR,{login:u,handleAuthResponse:y}):e.chooseScopes?s.jsx(Cq,{login:u,scope:e.scope,handleAuthResponse:w}):s.jsx("div",{children:"Success"}):s.jsx(xq,{onForgotPassword:o,onRegister:i,handleAuthResponse:y,disableGoogleAuth:e.disableGoogleAuth,disableEmailAuth:e.disableEmailAuth,...l,children:e.children})})}var ZR,Vw=Xc;ZR=Vw.createRoot,Vw.hydrateRoot;/**
543
+ `)}),"...",s.jsx("br",{})]})}const dq="_splitButton_1i0gi_1",fq="_menuControl_1i0gi_6",Uw={splitButton:dq,menuControl:fq};function jf(e){const{outcome:t}=e,n=se(),r=wt(e.defaultValue),o=r==null?void 0:r.resourceType,[i,a]=p.useState(!1),[l,c]=p.useState(),u=n.getAccessPolicy(),d=At();p.useEffect(()=>{if(r)if(e.profileUrl){const m=e.profileUrl;n.requestProfileSchema(e.profileUrl,{expandProfile:!0}).then(()=>{const g=yl(m);if(g){a(!0);const v=$8(r,g);c(v)}else console.error(`Schema not found for ${m}`)}).catch(g=>{console.error("Error in requestProfileSchema",g)})}else n.requestSchema(o).then(()=>{c(r),a(!0)}).catch(console.log)},[n,r,o,e.profileUrl]);const f=p.useMemo(()=>r&&gk(r,Ox.READ,u),[u,r]),h=p.useMemo(()=>n.isSuperAdmin()||!u||!Bt(l==null?void 0:l.resourceType)?!0:WF(u,l==null?void 0:l.resourceType),[n,u,l==null?void 0:l.resourceType]);return!i||!l?s.jsx("div",{children:"Loading..."}):h?s.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:m=>{m.preventDefault(),e.onSubmit&&e.onSubmit(l)},children:[s.jsxs(Oe,{mb:"xl",children:[s.jsx(vt,{title:"Resource Type",htmlFor:"resourceType",outcome:t,children:s.jsx(ve,{name:"resourceType",defaultValue:l.resourceType,disabled:!0})}),s.jsx(vt,{title:"ID",htmlFor:"id",outcome:t,children:s.jsx(ve,{name:"id",defaultValue:l.id,disabled:!0})})]}),s.jsx(t0,{path:l.resourceType,valuePath:l.resourceType,typeName:o,defaultValue:l,outcome:t,onChange:c,profileUrl:e.profileUrl,accessPolicyResource:f}),s.jsxs(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",gap:0,children:[s.jsx(oe,{type:"submit",className:rt((e.onPatch||e.onDelete)&&Uw.splitButton),children:r!=null&&r.id?"Update":"Create"}),(e.onPatch||e.onDelete)&&s.jsxs(J,{transitionProps:{transition:"pop"},position:"bottom-end",withinPortal:!0,children:[s.jsx(J.Target,{children:s.jsx(tn,{variant:"filled",color:d.primaryColor,size:36,className:Uw.menuControl,"aria-label":"More actions",children:s.jsx(Bx,{size:14,stroke:1.5})})}),s.jsxs(J.Dropdown,{children:[e.onPatch&&s.jsx(J.Item,{leftSection:s.jsx(Nk,{size:14,stroke:1.5}),onClick:()=>{e.onPatch(l)},children:"Patch"}),e.onDelete&&s.jsx(J.Item,{color:"red",leftSection:s.jsx(Hx,{size:14,stroke:1.5,color:"red"}),onClick:()=>{e.onDelete(l)},children:"Delete"})]})]})]})]}):s.jsxs(Vi,{color:"red",title:"Permission denied",icon:s.jsx(Sl,{}),children:["Your access level prevents you from editing and creating ",l.resourceType," resources."]})}function hq(e){var o;const t=se(),[n,r]=p.useState(e.history);return p.useEffect(()=>{!e.history&&e.resourceType&&e.id&&t.readHistory(e.resourceType,e.id).then(r).catch(console.log)},[t,e.history,e.resourceType,e.id]),n?s.jsxs(de,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[s.jsx(de.Thead,{children:s.jsxs(de.Tr,{children:[s.jsx(de.Th,{children:"Author"}),s.jsx(de.Th,{children:"Date"}),s.jsx(de.Th,{children:"Version"})]})}),s.jsx(de.Tbody,{children:(o=n.entry)==null?void 0:o.map((i,a)=>s.jsx(pq,{entry:i},"entry-"+a))})]}):s.jsx("div",{children:"Loading..."})}function pq(e){var r,o,i;const{response:t,resource:n}=e.entry;return n?s.jsxs(de.Tr,{children:[s.jsx(de.Td,{children:s.jsx(Ua,{value:(r=n.meta)==null?void 0:r.author,link:!0})}),s.jsx(de.Td,{children:Fn((o=n.meta)==null?void 0:o.lastUpdated)}),s.jsx(de.Td,{children:s.jsx(Ge,{to:mq(n),children:(i=n.meta)==null?void 0:i.versionId})})]}):s.jsx(de.Tr,{children:s.jsx(de.Td,{colSpan:3,children:De(t==null?void 0:t.outcome)})})}function mq(e){var t;return`/${e.resourceType}/${e.id}/_history/${(t=e.meta)==null?void 0:t.versionId}`}function gq(e){const{serviceRequest:t,...n}=e;return s.jsx(Uh,{value:t,loadTimelineResources:async(r,o,i)=>{const a=`${o}/${i}`,l=100;return Promise.allSettled([r.readHistory("ServiceRequest",i),r.search("Communication",{"based-on":a,_count:l}),r.search("DiagnosticReport",{"based-on":a,_count:l}),r.search("Media",{"based-on":a,_count:l}),r.search("DocumentReference",{related:a,_count:l}),r.search("Task",{_filter:`based-on eq ${a} or focus eq ${a} or subject eq ${a}`,_count:l})])},createCommunication:(r,o,i)=>({resourceType:"Communication",status:"completed",basedOn:[Et(r)],subject:r.subject,sender:Et(o),sent:new Date().toISOString(),payload:[{contentString:i}]}),createMedia:(r,o,i)=>({resourceType:"Media",status:"completed",basedOn:[Et(r)],subject:r.subject,operator:Et(o),issued:new Date().toISOString(),content:i}),...n})}function vq(e){const t=se(),{client:n,patient:r,encounter:o,children:i,...a}=e;function l(){t.createResource({resourceType:"SmartAppLaunch",patient:r,encounter:o}).then(c=>{const u=new URL(n.launchUri);u.searchParams.set("iss",t.getBaseUrl()+"fhir/R4"),u.searchParams.set("launch",c.id),window.location.assign(u.toString())}).catch(c=>he({color:"red",message:De(c),autoClose:!1}))}return s.jsx(Ze,{onClick:()=>l(),...a,children:i})}function qR(e){const t=se(),[n,r]=p.useState();return s.jsxs(Ke,{onSubmit:async o=>{try{e.handleAuthResponse(await t.startNewProject({login:e.login,projectName:o.projectName}))}catch(i){r(ht(i))}},children:[s.jsxs(mn,{style:{flexDirection:"column"},children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Create project"})]}),s.jsxs(Oe,{gap:"xl",children:[s.jsx(ve,{name:"projectName",label:"Project Name",placeholder:"My Project",required:!0,autoFocus:!0,error:Je(n,"projectName")}),s.jsxs(fe,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",s.jsx(Ze,{href:"https://www.medplum.com/privacy",children:"Privacy Policy"})," and ",s.jsx(Ze,{href:"https://www.medplum.com/terms",children:"Terms of Service"}),"."]})]}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(oe,{type:"submit",children:"Create project"})})]})}function GR(e,t){const n=document.getElementsByTagName("head")[0],r=document.createElement("script");r.async=!0,r.src=e,r.onload=t??null,n.appendChild(r)}function QR(e){const t=se(),{googleClientId:n,handleGoogleCredential:r}=e,o=p.useRef(null),[i,a]=p.useState(typeof google<"u"),[l,c]=p.useState(!1),[u,d]=p.useState(!1);return p.useEffect(()=>{if(typeof google>"u"){GR("https://accounts.google.com/gsi/client",()=>a(!0));return}l||(google.accounts.id.initialize({client_id:n,callback:r}),c(!0)),o.current&&!u&&(google.accounts.id.renderButton(o.current,{}),d(!0))},[t,n,l,i,o,u,r]),n?s.jsx("div",{ref:o}):null}function KR(e){if(e)return e;if(typeof window<"u"){const t=window.location.protocol+"//"+window.location.host;if([].includes(t))return"__GOOGLE_CLIENT_ID__"}}function YR(e){typeof grecaptcha>"u"&&GR("https://www.google.com/recaptcha/api.js?render="+e)}function XR(e){return new Promise((t,n)=>{grecaptcha.ready(async()=>{try{t(await grecaptcha.execute(e,{action:"submit"}))}catch(r){n(r)}})})}function yq(e){const t=KR(e.googleClientId),n=e.recaptchaSiteKey,r=se(),[o,i]=p.useState(),a=vu(o,void 0);return p.useEffect(()=>{n&&YR(n)},[n]),s.jsxs(Ke,{onSubmit:async l=>{try{let c="";n&&(c=await XR(n)),e.handleAuthResponse(await r.startNewUser({projectId:e.projectId,clientId:e.clientId,firstName:l.firstName,lastName:l.lastName,email:l.email,password:l.password,remember:l.remember==="true",recaptchaSiteKey:n,recaptchaToken:c}))}catch(c){i(ht(c))}},children:[s.jsx(mn,{style:{flexDirection:"column"},children:e.children}),s.jsx(Mr,{issues:a}),t&&s.jsxs(s.Fragment,{children:[s.jsx(te,{justify:"center",p:"xl",style:{height:70},children:s.jsx(QR,{googleClientId:t,handleGoogleCredential:async l=>{try{e.handleAuthResponse(await r.startGoogleLogin({googleClientId:l.clientId,googleCredential:l.credential,projectId:e.projectId,createUser:!0}))}catch(c){i(ht(c))}}})}),s.jsx(cn,{label:"or",labelPosition:"center",my:"lg"})]}),s.jsxs(Oe,{gap:"xl",children:[s.jsx(ve,{name:"firstName",type:"text",label:"First name",placeholder:"First name",required:!0,autoFocus:!0,error:Je(o,"firstName")}),s.jsx(ve,{name:"lastName",type:"text",label:"Last name",placeholder:"Last name",required:!0,error:Je(o,"lastName")}),s.jsx(ve,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,error:Je(o,"email")}),s.jsx(Qr,{name:"password",label:"Password",autoComplete:"off",required:!0,error:Je(o,"password")}),s.jsxs(fe,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",s.jsx(Ze,{href:"https://www.medplum.com/privacy",children:"Privacy Policy"})," and ",s.jsx(Ze,{href:"https://www.medplum.com/terms",children:"Terms of Service"}),"."]}),s.jsxs(fe,{c:"dimmed",size:"xs",children:["This site is protected by reCAPTCHA and the Google"," ",s.jsx(Ze,{href:"https://policies.google.com/privacy",children:"Privacy Policy"})," and ",s.jsx(Ze,{href:"https://policies.google.com/terms",children:"Terms of Service"})," apply."]})]}),s.jsxs(te,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[s.jsx(_n,{name:"remember",label:"Remember me",size:"xs"}),s.jsx(oe,{type:"submit",children:"Create account"})]})]})}function xq(e){const{type:t,projectId:n,clientId:r,googleClientId:o,recaptchaSiteKey:i,onSuccess:a}=e,l=se(),[c,u]=p.useState(),[d,f]=p.useState();p.useEffect(()=>{t==="patient"&&c&&l.startNewPatient({login:c,projectId:n}).then(m=>l.processCode(m.code)).then(()=>a()).catch(m=>f(ht(m)))},[l,t,n,c,a]);function h(m){m.code?l.processCode(m.code).then(()=>a()).catch(console.log):m.login&&u(m.login)}return s.jsxs(Ne,{width:450,children:[d&&s.jsx("pre",{children:JSON.stringify(d,null,2)}),!c&&s.jsx(yq,{projectId:n,clientId:r,googleClientId:o,recaptchaSiteKey:i,handleAuthResponse:h,children:e.children}),c&&t==="project"&&s.jsx(qR,{login:c,handleAuthResponse:h})]})}function bq(e){const[t,n]=p.useState();return t?s.jsx(Sq,{email:t,...e}):s.jsx(wq,{setEmail:n,...e})}function wq(e){const{setEmail:t,onRegister:n,handleAuthResponse:r,children:o,disableEmailAuth:i,...a}=e,l=se(),c=!e.disableGoogleAuth&&KR(e.googleClientId),[u,d]=p.useState(),f=vu(u,void 0),h=p.useCallback(async v=>{if(!v.authorizeUrl)return!1;const S=JSON.stringify({...await l.ensureCodeChallenge(a),domain:v.domain}),y=new URL(v.authorizeUrl);return y.searchParams.set("state",S),window.location.assign(y.toString()),!0},[l,a]),m=p.useCallback(async v=>{const S=await l.post("auth/method",{email:v.email});await h(S)||t(v.email)},[l,h,t]),g=p.useCallback(async v=>{try{const S=await l.startGoogleLogin({...a,googleCredential:v.credential});await h(S)||r(S)}catch(S){d(ht(S))}},[l,a,h,r]);return s.jsxs(Ke,{onSubmit:m,children:[s.jsx(mn,{style:{flexDirection:"column"},children:o}),s.jsx(Mr,{issues:f}),c&&s.jsxs(s.Fragment,{children:[s.jsx(te,{justify:"center",p:"xl",style:{height:70},children:s.jsx(QR,{googleClientId:c,handleGoogleCredential:g})}),!i&&s.jsx(cn,{label:"or",labelPosition:"center",my:"lg"})]}),!i&&s.jsx(ve,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:Je(u,"email")}),s.jsxs(te,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[s.jsx("div",{children:n&&s.jsx(Ze,{component:"button",type:"button",color:"dimmed",onClick:n,size:"xs",children:"Register"})}),!i&&s.jsx(oe,{type:"submit",children:"Next"})]})]})}function Sq(e){const{onForgotPassword:t,handleAuthResponse:n,children:r,...o}=e,i=se(),[a,l]=p.useState(),c=vu(a,void 0),u=p.useCallback(d=>{i.startLogin({...o,password:d.password,remember:d.remember==="on"}).then(n).catch(f=>l(ht(f)))},[i,o,n]);return s.jsxs(Ke,{onSubmit:u,children:[s.jsx(mn,{style:{flexDirection:"column"},children:r}),s.jsx(Mr,{issues:c}),s.jsx(Oe,{gap:"xl",children:s.jsx(Qr,{name:"password",label:"Password",autoComplete:"off",required:!0,autoFocus:!0,error:Je(a,"password")})}),s.jsxs(te,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[t&&s.jsx(Ze,{component:"button",type:"button",c:"dimmed",onClick:t,size:"xs",children:"Forgot password"}),s.jsx(_n,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1}}),s.jsx(oe,{type:"submit",children:"Sign in"})]})]})}function jq(e){const t=se(),n=nu(),[r,o]=p.useState(""),[i,a]=p.useState();function l(f){var h;return!!((h=f==null?void 0:f.toLowerCase())!=null&&h.includes(r.toLowerCase()))}function c(f){var h,m;return l((h=f.profile)==null?void 0:h.display)||l((m=f.project)==null?void 0:m.display)}function u(f){t.post("auth/profile",{login:e.login,profile:f}).then(e.handleAuthResponse).catch(h=>a(ht(h)))}const d=e.memberships.filter(c).slice(0,10).map(f=>s.jsx(Me.Option,{value:f.id,children:s.jsx(Cq,{...f})},f.id));return s.jsxs(Oe,{children:[s.jsxs(Es,{gap:"md",mb:"md",justify:"center",align:"center",direction:"column",wrap:"nowrap",children:[s.jsx(ro,{size:32}),s.jsx(ge,{order:3,children:"Choose profile"})]}),s.jsx(Mr,{outcome:i}),s.jsxs(Me,{store:n,onOptionSubmit:u,children:[s.jsx(Me.EventsTarget,{children:s.jsx(ve,{placeholder:"Search",value:r,onChange:f=>{o(f.currentTarget.value),n.updateSelectedOptionIndex()}})}),s.jsx("div",{children:s.jsx(Me.Options,{children:d.length>0?d:s.jsx(Me.Empty,{children:"Nothing found..."})})})]})]})}function Cq(e){var t,n;return s.jsxs(te,{children:[s.jsx(Ts,{radius:"xl"}),s.jsxs("div",{children:[s.jsx(fe,{fz:"sm",fw:500,children:(t=e.profile)==null?void 0:t.display}),s.jsx(fe,{fz:"xs",opacity:.6,children:(n=e.project)==null?void 0:n.display})]})]})}function Eq(e){const t=se();return s.jsx(Ke,{onSubmit:n=>{t.post("auth/scope",{login:e.login,scope:Object.keys(n).join(" ")}).then(e.handleAuthResponse).catch(console.log)},children:s.jsxs(Oe,{children:[s.jsxs(mn,{style:{flexDirection:"column"},children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Choose scope"})]}),s.jsx(Oe,{children:(e.scope??"openid").split(" ").map(n=>s.jsx(_n,{id:n,name:n,label:n,defaultChecked:!0},n))}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{type:"submit",children:"Set scope"})})]})})}function Tq(e){const t=se(),[n,r]=p.useState();return s.jsx(Ke,{onSubmit:o=>{r(void 0),t.post("auth/mfa/verify",{login:e.login,token:o.token}).then(e.handleAuthResponse).catch(i=>r(De(i)))},children:s.jsxs(Oe,{children:[s.jsxs(mn,{style:{flexDirection:"column"},children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Enter MFA code"})]}),n&&s.jsx(Vi,{icon:s.jsx(Sl,{size:16}),title:"Error",color:"red",children:n}),s.jsx(Oe,{children:s.jsx(ve,{name:"token",label:"MFA code",required:!0,autoFocus:!0})}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{type:"submit",children:"Submit code"})})]})})}function JR(e){const{login:t,chooseScopes:n,onSuccess:r,onForgotPassword:o,onRegister:i,onCode:a,...l}=e,c=se(),[u,d]=p.useState(),f=p.useRef(!1),[h,m]=p.useState(!1),[g,v]=p.useState(),S=p.useCallback(b=>{a?a(b):c.processCode(b).then(()=>{r&&r()}).catch(x=>he({color:"red",message:De(x)}))},[c,a,r]),y=p.useCallback(b=>{m(!!b.mfaRequired),b.login&&d(b.login),b.memberships&&v(b.memberships),b.code&&(n?v(void 0):S(b.code))},[n,S]),w=p.useCallback(b=>{S(b.code)},[S]);return p.useEffect(()=>{t&&!f.current&&!u&&(f.current=!0,c.get("auth/login/"+t).then(y).catch(b=>he({color:"red",message:De(b)})))},[c,t,f,u,y]),s.jsx(Ne,{width:450,px:"sm",py:"md",children:u?h?s.jsx(Tq,{login:u,handleAuthResponse:y}):g?s.jsx(jq,{login:u,memberships:g,handleAuthResponse:y}):e.projectId==="new"?s.jsx(qR,{login:u,handleAuthResponse:y}):e.chooseScopes?s.jsx(Eq,{login:u,scope:e.scope,handleAuthResponse:w}):s.jsx("div",{children:"Success"}):s.jsx(bq,{onForgotPassword:o,onRegister:i,handleAuthResponse:y,disableGoogleAuth:e.disableGoogleAuth,disableEmailAuth:e.disableEmailAuth,...l,children:e.children})})}var ZR,Vw=Xc;ZR=Vw.createRoot,Vw.hydrateRoot;/**
544
544
  * @remix-run/router v1.19.0
545
545
  *
546
546
  * Copyright (c) Remix Software Inc.
@@ -549,9 +549,9 @@ Error generating stack: `+i.message+`
549
549
  * LICENSE.md file in the root directory of this source tree.
550
550
  *
551
551
  * @license MIT
552
- */function Ft(){return Ft=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},Ft.apply(this,arguments)}var Yt;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Yt||(Yt={}));const Ww="popstate";function Tq(e){e===void 0&&(e={});function t(r,o){let{pathname:i,search:a,hash:l}=r.location;return zc("",{pathname:i,search:a,hash:l},o.state&&o.state.usr||null,o.state&&o.state.key||"default")}function n(r,o){return typeof o=="string"?o:Su(o)}return kq(t,n,null,e)}function Ue(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function il(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Pq(){return Math.random().toString(36).substr(2,8)}function Hw(e,t){return{usr:e.state,key:e.key,idx:t}}function zc(e,t,n,r){return n===void 0&&(n=null),Ft({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?ri(t):t,{state:n,key:t&&t.key||r||Pq()})}function Su(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function ri(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function kq(e,t,n,r){r===void 0&&(r={});let{window:o=document.defaultView,v5Compat:i=!1}=r,a=o.history,l=Yt.Pop,c=null,u=d();u==null&&(u=0,a.replaceState(Ft({},a.state,{idx:u}),""));function d(){return(a.state||{idx:null}).idx}function f(){l=Yt.Pop;let S=d(),y=S==null?null:S-u;u=S,c&&c({action:l,location:v.location,delta:y})}function h(S,y){l=Yt.Push;let w=zc(v.location,S,y);u=d()+1;let b=Hw(w,u),x=v.createHref(w);try{a.pushState(b,"",x)}catch(C){if(C instanceof DOMException&&C.name==="DataCloneError")throw C;o.location.assign(x)}i&&c&&c({action:l,location:v.location,delta:1})}function m(S,y){l=Yt.Replace;let w=zc(v.location,S,y);u=d();let b=Hw(w,u),x=v.createHref(w);a.replaceState(b,"",x),i&&c&&c({action:l,location:v.location,delta:0})}function g(S){let y=o.location.origin!=="null"?o.location.origin:o.location.href,w=typeof S=="string"?S:Su(S);return w=w.replace(/ $/,"%20"),Ue(y,"No window.location.(origin|href) available to create URL for href: "+w),new URL(w,y)}let v={get action(){return l},get location(){return e(o,a)},listen(S){if(c)throw new Error("A history only accepts one active listener");return o.addEventListener(Ww,f),c=S,()=>{o.removeEventListener(Ww,f),c=null}},createHref(S){return t(o,S)},createURL:g,encodeLocation(S){let y=g(S);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:h,replace:m,go(S){return a.go(S)}};return v}var pt;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(pt||(pt={}));const Rq=new Set(["lazy","caseSensitive","path","id","index","children"]);function _q(e){return e.index===!0}function Bc(e,t,n,r){return n===void 0&&(n=[]),r===void 0&&(r={}),e.map((o,i)=>{let a=[...n,String(i)],l=typeof o.id=="string"?o.id:a.join("-");if(Ue(o.index!==!0||!o.children,"Cannot specify children on an index route"),Ue(!r[l],'Found a route id collision on id "'+l+`". Route id's must be globally unique within Data Router usages`),_q(o)){let c=Ft({},o,t(o),{id:l});return r[l]=c,c}else{let c=Ft({},o,t(o),{id:l,children:void 0});return r[l]=c,o.children&&(c.children=Bc(o.children,t,a,r)),c}})}function as(e,t,n){return n===void 0&&(n="/"),_d(e,t,n,!1)}function _d(e,t,n,r){let o=typeof t=="string"?ri(t):t,i=ju(o.pathname||"/",n);if(i==null)return null;let a=e2(e);Iq(a);let l=null;for(let c=0;l==null&&c<a.length;++c){let u=Vq(i);l=Bq(a[c],u,r)}return l}function Dq(e,t){let{route:n,pathname:r,params:o}=e;return{id:n.id,pathname:r,params:o,data:t[n.id],handle:n.handle}}function e2(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let o=(i,a,l)=>{let c={relativePath:l===void 0?i.path||"":l,caseSensitive:i.caseSensitive===!0,childrenIndex:a,route:i};c.relativePath.startsWith("/")&&(Ue(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let u=_i([r,c.relativePath]),d=n.concat(c);i.children&&i.children.length>0&&(Ue(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+u+'".')),e2(i.children,t,d,u)),!(i.path==null&&!i.index)&&t.push({path:u,score:Fq(u,i.index),routesMeta:d})};return e.forEach((i,a)=>{var l;if(i.path===""||!((l=i.path)!=null&&l.includes("?")))o(i,a);else for(let c of t2(i.path))o(i,a,c)}),t}function t2(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,o=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return o?[i,""]:[i];let a=t2(r.join("/")),l=[];return l.push(...a.map(c=>c===""?i:[i,c].join("/"))),o&&l.push(...a),l.map(c=>e.startsWith("/")&&c===""?"/":c)}function Iq(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:zq(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Aq=/^:[\w-]+$/,Nq=3,Mq=2,Oq=1,Lq=10,$q=-2,qw=e=>e==="*";function Fq(e,t){let n=e.split("/"),r=n.length;return n.some(qw)&&(r+=$q),t&&(r+=Mq),n.filter(o=>!qw(o)).reduce((o,i)=>o+(Aq.test(i)?Nq:i===""?Oq:Lq),r)}function zq(e,t){return e.length===t.length&&e.slice(0,-1).every((r,o)=>r===t[o])?e[e.length-1]-t[t.length-1]:0}function Bq(e,t,n){n===void 0&&(n=!1);let{routesMeta:r}=e,o={},i="/",a=[];for(let l=0;l<r.length;++l){let c=r[l],u=l===r.length-1,d=i==="/"?t:t.slice(i.length)||"/",f=Gw({path:c.relativePath,caseSensitive:c.caseSensitive,end:u},d),h=c.route;if(!f&&u&&n&&!r[r.length-1].route.index&&(f=Gw({path:c.relativePath,caseSensitive:c.caseSensitive,end:!1},d)),!f)return null;Object.assign(o,f.params),a.push({params:o,pathname:_i([i,f.pathname]),pathnameBase:qq(_i([i,f.pathnameBase])),route:h}),f.pathnameBase!=="/"&&(i=_i([i,f.pathnameBase]))}return a}function Gw(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Uq(e.path,e.caseSensitive,e.end),o=t.match(n);if(!o)return null;let i=o[0],a=i.replace(/(.)\/+$/,"$1"),l=o.slice(1);return{params:r.reduce((u,d,f)=>{let{paramName:h,isOptional:m}=d;if(h==="*"){let v=l[f]||"";a=i.slice(0,i.length-v.length).replace(/(.)\/+$/,"$1")}const g=l[f];return m&&!g?u[h]=void 0:u[h]=(g||"").replace(/%2F/g,"/"),u},{}),pathname:i,pathnameBase:a,pattern:e}}function Uq(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),il(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],o="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,l,c)=>(r.push({paramName:l,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),o+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?o+="\\/*$":e!==""&&e!=="/"&&(o+="(?:(?=\\/|$))"),[new RegExp(o,t?void 0:"i"),r]}function Vq(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return il(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function ju(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function Wq(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:o=""}=typeof e=="string"?ri(e):e;return{pathname:n?n.startsWith("/")?n:Hq(n,t):t,search:Gq(r),hash:Qq(o)}}function Hq(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(o=>{o===".."?n.length>1&&n.pop():o!=="."&&n.push(o)}),n.length>1?n.join("/"):"/"}function Zp(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function n2(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function r2(e,t){let n=n2(e);return t?n.map((r,o)=>o===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function o2(e,t,n,r){r===void 0&&(r=!1);let o;typeof e=="string"?o=ri(e):(o=Ft({},e),Ue(!o.pathname||!o.pathname.includes("?"),Zp("?","pathname","search",o)),Ue(!o.pathname||!o.pathname.includes("#"),Zp("#","pathname","hash",o)),Ue(!o.search||!o.search.includes("#"),Zp("#","search","hash",o)));let i=e===""||o.pathname==="",a=i?"/":o.pathname,l;if(a==null)l=n;else{let f=t.length-1;if(!r&&a.startsWith("..")){let h=a.split("/");for(;h[0]==="..";)h.shift(),f-=1;o.pathname=h.join("/")}l=f>=0?t[f]:"/"}let c=Wq(o,l),u=a&&a!=="/"&&a.endsWith("/"),d=(i||a===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(u||d)&&(c.pathname+="/"),c}const _i=e=>e.join("/").replace(/\/\/+/g,"/"),qq=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Gq=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Qq=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class Cf{constructor(t,n,r,o){o===void 0&&(o=!1),this.status=t,this.statusText=n||"",this.internal=o,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function Wh(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const i2=["post","put","patch","delete"],Kq=new Set(i2),Yq=["get",...i2],Xq=new Set(Yq),Jq=new Set([301,302,303,307,308]),Zq=new Set([307,308]),em={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},eG={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Ul={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},v0=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,tG=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),s2="remix-router-transitions";function nG(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u",r=!n;Ue(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let o;if(e.mapRouteProperties)o=e.mapRouteProperties;else if(e.detectErrorBoundary){let I=e.detectErrorBoundary;o=M=>({hasErrorBoundary:I(M)})}else o=tG;let i={},a=Bc(e.routes,o,void 0,i),l,c=e.basename||"/",u=e.unstable_dataStrategy||aG,d=e.unstable_patchRoutesOnMiss,f=Ft({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),h=null,m=new Set,g=null,v=null,S=null,y=e.hydrationData!=null,w=as(a,e.history.location,c),b=null;if(w==null&&!d){let I=An(404,{pathname:e.history.location.pathname}),{matches:M,route:z}=rS(a);w=M,b={[z.id]:I}}w&&!e.hydrationData&&Kt(w,a,e.history.location.pathname).active&&(w=null);let x;if(w)if(w.some(I=>I.route.lazy))x=!1;else if(!w.some(I=>I.route.loader))x=!0;else if(f.v7_partialHydration){let I=e.hydrationData?e.hydrationData.loaderData:null,M=e.hydrationData?e.hydrationData.errors:null,z=G=>G.route.loader?typeof G.route.loader=="function"&&G.route.loader.hydrate===!0?!1:I&&I[G.route.id]!==void 0||M&&M[G.route.id]!==void 0:!0;if(M){let G=w.findIndex(le=>M[le.route.id]!==void 0);x=w.slice(0,G+1).every(z)}else x=w.every(z)}else x=e.hydrationData!=null;else if(x=!1,w=[],f.v7_partialHydration){let I=Kt(null,a,e.history.location.pathname);I.active&&I.matches&&(w=I.matches)}let C,j={historyAction:e.history.action,location:e.history.location,matches:w,initialized:x,navigation:em,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||b,fetchers:new Map,blockers:new Map},T=Yt.Pop,E=!1,_,k=!1,A=new Map,O=null,U=!1,N=!1,F=[],D=new Set,R=new Map,P=0,$=-1,L=new Map,V=new Set,K=new Map,ie=new Map,Re=new Set,ae=new Map,Ee=new Map,Fe=new Map,me=!1;function Le(){if(h=e.history.listen(I=>{let{action:M,location:z,delta:G}=I;if(me){me=!1;return}il(Ee.size===0||G!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let le=Js({currentLocation:j.location,nextLocation:z,historyAction:M});if(le&&G!=null){me=!0,e.history.go(G*-1),Yi(le,{state:"blocked",location:z,proceed(){Yi(le,{state:"proceeding",proceed:void 0,reset:void 0,location:z}),e.history.go(G)},reset(){let je=new Map(j.blockers);je.set(le,Ul),Ve({blockers:je})}});return}return Qe(M,z)}),n){bG(t,A);let I=()=>wG(t,A);t.addEventListener("pagehide",I),O=()=>t.removeEventListener("pagehide",I)}return j.initialized||Qe(Yt.Pop,j.location,{initialHydration:!0}),C}function nt(){h&&h(),O&&O(),m.clear(),_&&_.abort(),j.fetchers.forEach((I,M)=>rr(M)),j.blockers.forEach((I,M)=>ku(M))}function Tt(I){return m.add(I),()=>m.delete(I)}function Ve(I,M){M===void 0&&(M={}),j=Ft({},j,I);let z=[],G=[];f.v7_fetcherPersist&&j.fetchers.forEach((le,je)=>{le.state==="idle"&&(Re.has(je)?G.push(je):z.push(je))}),[...m].forEach(le=>le(j,{deletedFetchers:G,unstable_viewTransitionOpts:M.viewTransitionOpts,unstable_flushSync:M.flushSync===!0})),f.v7_fetcherPersist&&(z.forEach(le=>j.fetchers.delete(le)),G.forEach(le=>rr(le)))}function Te(I,M,z){var G,le;let{flushSync:je}=z===void 0?{}:z,Ie=j.actionData!=null&&j.navigation.formMethod!=null&&Ur(j.navigation.formMethod)&&j.navigation.state==="loading"&&((G=I.state)==null?void 0:G._isRedirect)!==!0,Y;M.actionData?Object.keys(M.actionData).length>0?Y=M.actionData:Y=null:Ie?Y=j.actionData:Y=null;let $e=M.loaderData?tS(j.loaderData,M.loaderData,M.matches||[],M.errors):j.loaderData,ke=j.blockers;ke.size>0&&(ke=new Map(ke),ke.forEach((ut,mt)=>ke.set(mt,Ul)));let _e=E===!0||j.navigation.formMethod!=null&&Ur(j.navigation.formMethod)&&((le=I.state)==null?void 0:le._isRedirect)!==!0;l&&(a=l,l=void 0),U||T===Yt.Pop||(T===Yt.Push?e.history.push(I,I.state):T===Yt.Replace&&e.history.replace(I,I.state));let ot;if(T===Yt.Pop){let ut=A.get(j.location.pathname);ut&&ut.has(I.pathname)?ot={currentLocation:j.location,nextLocation:I}:A.has(I.pathname)&&(ot={currentLocation:I,nextLocation:j.location})}else if(k){let ut=A.get(j.location.pathname);ut?ut.add(I.pathname):(ut=new Set([I.pathname]),A.set(j.location.pathname,ut)),ot={currentLocation:j.location,nextLocation:I}}Ve(Ft({},M,{actionData:Y,loaderData:$e,historyAction:T,location:I,initialized:!0,navigation:em,revalidation:"idle",restoreScrollPosition:Ru(I,M.matches||j.matches),preventScrollReset:_e,blockers:ke}),{viewTransitionOpts:ot,flushSync:je===!0}),T=Yt.Pop,E=!1,k=!1,U=!1,N=!1,F=[]}async function Pe(I,M){if(typeof I=="number"){e.history.go(I);return}let z=Ng(j.location,j.matches,c,f.v7_prependBasename,I,f.v7_relativeSplatPath,M==null?void 0:M.fromRouteId,M==null?void 0:M.relative),{path:G,submission:le,error:je}=Qw(f.v7_normalizeFormMethod,!1,z,M),Ie=j.location,Y=zc(j.location,G,M&&M.state);Y=Ft({},Y,e.history.encodeLocation(Y));let $e=M&&M.replace!=null?M.replace:void 0,ke=Yt.Push;$e===!0?ke=Yt.Replace:$e===!1||le!=null&&Ur(le.formMethod)&&le.formAction===j.location.pathname+j.location.search&&(ke=Yt.Replace);let _e=M&&"preventScrollReset"in M?M.preventScrollReset===!0:void 0,ot=(M&&M.unstable_flushSync)===!0,ut=Js({currentLocation:Ie,nextLocation:Y,historyAction:ke});if(ut){Yi(ut,{state:"blocked",location:Y,proceed(){Yi(ut,{state:"proceeding",proceed:void 0,reset:void 0,location:Y}),Pe(I,M)},reset(){let mt=new Map(j.blockers);mt.set(ut,Ul),Ve({blockers:mt})}});return}return await Qe(ke,Y,{submission:le,pendingError:je,preventScrollReset:_e,replace:M&&M.replace,enableViewTransition:M&&M.unstable_viewTransition,flushSync:ot})}function Xe(){if(Pt(),Ve({revalidation:"loading"}),j.navigation.state!=="submitting"){if(j.navigation.state==="idle"){Qe(j.historyAction,j.location,{startUninterruptedRevalidation:!0});return}Qe(T||j.historyAction,j.navigation.location,{overrideNavigation:j.navigation})}}async function Qe(I,M,z){_&&_.abort(),_=null,T=I,U=(z&&z.startUninterruptedRevalidation)===!0,ep(j.location,j.matches),E=(z&&z.preventScrollReset)===!0,k=(z&&z.enableViewTransition)===!0;let G=l||a,le=z&&z.overrideNavigation,je=as(G,M,c),Ie=(z&&z.flushSync)===!0,Y=Kt(je,G,M.pathname);if(Y.active&&Y.matches&&(je=Y.matches),!je){let{error:it,notFoundMatches:hn,route:Zt}=Xi(M.pathname);Te(M,{matches:hn,loaderData:{},errors:{[Zt.id]:it}},{flushSync:Ie});return}if(j.initialized&&!N&&hG(j.location,M)&&!(z&&z.submission&&Ur(z.submission.formMethod))){Te(M,{matches:je},{flushSync:Ie});return}_=new AbortController;let $e=ha(e.history,M,_.signal,z&&z.submission),ke;if(z&&z.pendingError)ke=[Da(je).route.id,{type:pt.error,error:z.pendingError}];else if(z&&z.submission&&Ur(z.submission.formMethod)){let it=await Z($e,M,z.submission,je,Y.active,{replace:z.replace,flushSync:Ie});if(it.shortCircuited)return;if(it.pendingActionResult){let[hn,Zt]=it.pendingActionResult;if(sr(Zt)&&Wh(Zt.error)&&Zt.error.status===404){_=null,Te(M,{matches:it.matches,loaderData:{},errors:{[hn]:Zt.error}});return}}je=it.matches||je,ke=it.pendingActionResult,le=tm(M,z.submission),Ie=!1,Y.active=!1,$e=ha(e.history,$e.url,$e.signal)}let{shortCircuited:_e,matches:ot,loaderData:ut,errors:mt}=await ue($e,M,je,Y.active,le,z&&z.submission,z&&z.fetcherSubmission,z&&z.replace,z&&z.initialHydration===!0,Ie,ke);_e||(_=null,Te(M,Ft({matches:ot||je},nS(ke),{loaderData:ut,errors:mt})))}async function Z(I,M,z,G,le,je){je===void 0&&(je={}),Pt();let Ie=yG(M,z);if(Ve({navigation:Ie},{flushSync:je.flushSync===!0}),le){let ke=await oo(G,M.pathname,I.signal);if(ke.type==="aborted")return{shortCircuited:!0};if(ke.type==="error"){let{boundaryId:_e,error:ot}=Or(M.pathname,ke);return{matches:ke.partialMatches,pendingActionResult:[_e,{type:pt.error,error:ot}]}}else if(ke.matches)G=ke.matches;else{let{notFoundMatches:_e,error:ot,route:ut}=Xi(M.pathname);return{matches:_e,pendingActionResult:[ut.id,{type:pt.error,error:ot}]}}}let Y,$e=Xl(G,M);if(!$e.route.action&&!$e.route.lazy)Y={type:pt.error,error:An(405,{method:I.method,pathname:M.pathname,routeId:$e.route.id})};else if(Y=(await Be("action",I,[$e],G))[0],I.signal.aborted)return{shortCircuited:!0};if(ms(Y)){let ke;return je&&je.replace!=null?ke=je.replace:ke=Jw(Y.response.headers.get("Location"),new URL(I.url),c)===j.location.pathname+j.location.search,await xe(I,Y,{submission:z,replace:ke}),{shortCircuited:!0}}if(ps(Y))throw An(400,{type:"defer-action"});if(sr(Y)){let ke=Da(G,$e.route.id);return(je&&je.replace)!==!0&&(T=Yt.Push),{matches:G,pendingActionResult:[ke.route.id,Y]}}return{matches:G,pendingActionResult:[$e.route.id,Y]}}async function ue(I,M,z,G,le,je,Ie,Y,$e,ke,_e){let ot=le||tm(M,je),ut=je||Ie||aS(ot),mt=!U&&(!f.v7_partialHydration||!$e);if(G){if(mt){let Wt=Se(_e);Ve(Ft({navigation:ot},Wt!==void 0?{actionData:Wt}:{}),{flushSync:ke})}let We=await oo(z,M.pathname,I.signal);if(We.type==="aborted")return{shortCircuited:!0};if(We.type==="error"){let{boundaryId:Wt,error:or}=Or(M.pathname,We);return{matches:We.partialMatches,loaderData:{},errors:{[Wt]:or}}}else if(We.matches)z=We.matches;else{let{error:Wt,notFoundMatches:or,route:Mt}=Xi(M.pathname);return{matches:or,loaderData:{},errors:{[Mt.id]:Wt}}}}let it=l||a,[hn,Zt]=Kw(e.history,j,z,ut,M,f.v7_partialHydration&&$e===!0,f.v7_skipActionErrorRevalidation,N,F,D,Re,K,V,it,c,_e);if(jn(We=>!(z&&z.some(Wt=>Wt.route.id===We))||hn&&hn.some(Wt=>Wt.route.id===We)),$=++P,hn.length===0&&Zt.length===0){let We=Pu();return Te(M,Ft({matches:z,loaderData:{},errors:_e&&sr(_e[1])?{[_e[0]]:_e[1].error}:null},nS(_e),We?{fetchers:new Map(j.fetchers)}:{}),{flushSync:ke}),{shortCircuited:!0}}if(mt){let We={};if(!G){We.navigation=ot;let Wt=Se(_e);Wt!==void 0&&(We.actionData=Wt)}Zt.length>0&&(We.fetchers=He(Zt)),Ve(We,{flushSync:ke})}Zt.forEach(We=>{R.has(We.key)&&vr(We.key),We.controller&&R.set(We.key,We.controller)});let kl=()=>Zt.forEach(We=>vr(We.key));_&&_.signal.addEventListener("abort",kl);let{loaderResults:ii,fetcherResults:ea}=await Nt(j.matches,z,hn,Zt,I);if(I.signal.aborted)return{shortCircuited:!0};_&&_.signal.removeEventListener("abort",kl),Zt.forEach(We=>R.delete(We.key));let ta=oS([...ii,...ea]);if(ta){if(ta.idx>=hn.length){let We=Zt[ta.idx-hn.length].key;V.add(We)}return await xe(I,ta.result,{replace:Y}),{shortCircuited:!0}}let{loaderData:na,errors:io}=eS(j,z,hn,ii,_e,Zt,ea,ae);ae.forEach((We,Wt)=>{We.subscribe(or=>{(or||We.done)&&ae.delete(Wt)})}),f.v7_partialHydration&&$e&&j.errors&&Object.entries(j.errors).filter(We=>{let[Wt]=We;return!hn.some(or=>or.route.id===Wt)}).forEach(We=>{let[Wt,or]=We;io=Object.assign(io||{},{[Wt]:or})});let _u=Pu(),Du=yr($),Iu=_u||Du||Zt.length>0;return Ft({matches:z,loaderData:na,errors:io},Iu?{fetchers:new Map(j.fetchers)}:{})}function Se(I){if(I&&!sr(I[1]))return{[I[0]]:I[1].data};if(j.actionData)return Object.keys(j.actionData).length===0?null:j.actionData}function He(I){return I.forEach(M=>{let z=j.fetchers.get(M.key),G=Vl(void 0,z?z.data:void 0);j.fetchers.set(M.key,G)}),new Map(j.fetchers)}function ne(I,M,z,G){if(r)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");R.has(I)&&vr(I);let le=(G&&G.unstable_flushSync)===!0,je=l||a,Ie=Ng(j.location,j.matches,c,f.v7_prependBasename,z,f.v7_relativeSplatPath,M,G==null?void 0:G.relative),Y=as(je,Ie,c),$e=Kt(Y,je,Ie);if($e.active&&$e.matches&&(Y=$e.matches),!Y){St(I,M,An(404,{pathname:Ie}),{flushSync:le});return}let{path:ke,submission:_e,error:ot}=Qw(f.v7_normalizeFormMethod,!0,Ie,G);if(ot){St(I,M,ot,{flushSync:le});return}let ut=Xl(Y,ke);if(E=(G&&G.preventScrollReset)===!0,_e&&Ur(_e.formMethod)){pe(I,M,ke,ut,Y,$e.active,le,_e);return}K.set(I,{routeId:M,path:ke}),Q(I,M,ke,ut,Y,$e.active,le,_e)}async function pe(I,M,z,G,le,je,Ie,Y){Pt(),K.delete(I);function $e(Mt){if(!Mt.route.action&&!Mt.route.lazy){let So=An(405,{method:Y.formMethod,pathname:z,routeId:M});return St(I,M,So,{flushSync:Ie}),!0}return!1}if(!je&&$e(G))return;let ke=j.fetchers.get(I);$t(I,xG(Y,ke),{flushSync:Ie});let _e=new AbortController,ot=ha(e.history,z,_e.signal,Y);if(je){let Mt=await oo(le,z,ot.signal);if(Mt.type==="aborted")return;if(Mt.type==="error"){let{error:So}=Or(z,Mt);St(I,M,So,{flushSync:Ie});return}else if(Mt.matches){if(le=Mt.matches,G=Xl(le,z),$e(G))return}else{St(I,M,An(404,{pathname:z}),{flushSync:Ie});return}}R.set(I,_e);let ut=P,it=(await Be("action",ot,[G],le))[0];if(ot.signal.aborted){R.get(I)===_e&&R.delete(I);return}if(f.v7_fetcherPersist&&Re.has(I)){if(ms(it)||sr(it)){$t(I,li(void 0));return}}else{if(ms(it))if(R.delete(I),$>ut){$t(I,li(void 0));return}else return V.add(I),$t(I,Vl(Y)),xe(ot,it,{fetcherSubmission:Y});if(sr(it)){St(I,M,it.error);return}}if(ps(it))throw An(400,{type:"defer-action"});let hn=j.navigation.location||j.location,Zt=ha(e.history,hn,_e.signal),kl=l||a,ii=j.navigation.state!=="idle"?as(kl,j.navigation.location,c):j.matches;Ue(ii,"Didn't find any matches after fetcher action");let ea=++P;L.set(I,ea);let ta=Vl(Y,it.data);j.fetchers.set(I,ta);let[na,io]=Kw(e.history,j,ii,Y,hn,!1,f.v7_skipActionErrorRevalidation,N,F,D,Re,K,V,kl,c,[G.route.id,it]);io.filter(Mt=>Mt.key!==I).forEach(Mt=>{let So=Mt.key,T0=j.fetchers.get(So),L2=Vl(void 0,T0?T0.data:void 0);j.fetchers.set(So,L2),R.has(So)&&vr(So),Mt.controller&&R.set(So,Mt.controller)}),Ve({fetchers:new Map(j.fetchers)});let _u=()=>io.forEach(Mt=>vr(Mt.key));_e.signal.addEventListener("abort",_u);let{loaderResults:Du,fetcherResults:Iu}=await Nt(j.matches,ii,na,io,Zt);if(_e.signal.aborted)return;_e.signal.removeEventListener("abort",_u),L.delete(I),R.delete(I),io.forEach(Mt=>R.delete(Mt.key));let We=oS([...Du,...Iu]);if(We){if(We.idx>=na.length){let Mt=io[We.idx-na.length].key;V.add(Mt)}return xe(Zt,We.result)}let{loaderData:Wt,errors:or}=eS(j,j.matches,na,Du,void 0,io,Iu,ae);if(j.fetchers.has(I)){let Mt=li(it.data);j.fetchers.set(I,Mt)}yr(ea),j.navigation.state==="loading"&&ea>$?(Ue(T,"Expected pending action"),_&&_.abort(),Te(j.navigation.location,{matches:ii,loaderData:Wt,errors:or,fetchers:new Map(j.fetchers)})):(Ve({errors:or,loaderData:tS(j.loaderData,Wt,ii,or),fetchers:new Map(j.fetchers)}),N=!1)}async function Q(I,M,z,G,le,je,Ie,Y){let $e=j.fetchers.get(I);$t(I,Vl(Y,$e?$e.data:void 0),{flushSync:Ie});let ke=new AbortController,_e=ha(e.history,z,ke.signal);if(je){let it=await oo(le,z,_e.signal);if(it.type==="aborted")return;if(it.type==="error"){let{error:hn}=Or(z,it);St(I,M,hn,{flushSync:Ie});return}else if(it.matches)le=it.matches,G=Xl(le,z);else{St(I,M,An(404,{pathname:z}),{flushSync:Ie});return}}R.set(I,ke);let ot=P,mt=(await Be("loader",_e,[G],le))[0];if(ps(mt)&&(mt=await d2(mt,_e.signal,!0)||mt),R.get(I)===ke&&R.delete(I),!_e.signal.aborted){if(Re.has(I)){$t(I,li(void 0));return}if(ms(mt))if($>ot){$t(I,li(void 0));return}else{V.add(I),await xe(_e,mt);return}if(sr(mt)){St(I,M,mt.error);return}Ue(!ps(mt),"Unhandled fetcher deferred data"),$t(I,li(mt.data))}}async function xe(I,M,z){let{submission:G,fetcherSubmission:le,replace:je}=z===void 0?{}:z;M.response.headers.has("X-Remix-Revalidate")&&(N=!0);let Ie=M.response.headers.get("Location");Ue(Ie,"Expected a Location header on the redirect Response"),Ie=Jw(Ie,new URL(I.url),c);let Y=zc(j.location,Ie,{_isRedirect:!0});if(n){let mt=!1;if(M.response.headers.has("X-Remix-Reload-Document"))mt=!0;else if(v0.test(Ie)){const it=e.history.createURL(Ie);mt=it.origin!==t.location.origin||ju(it.pathname,c)==null}if(mt){je?t.location.replace(Ie):t.location.assign(Ie);return}}_=null;let $e=je===!0||M.response.headers.has("X-Remix-Replace")?Yt.Replace:Yt.Push,{formMethod:ke,formAction:_e,formEncType:ot}=j.navigation;!G&&!le&&ke&&_e&&ot&&(G=aS(j.navigation));let ut=G||le;if(Zq.has(M.response.status)&&ut&&Ur(ut.formMethod))await Qe($e,Y,{submission:Ft({},ut,{formAction:Ie}),preventScrollReset:E});else{let mt=tm(Y,G);await Qe($e,Y,{overrideNavigation:mt,fetcherSubmission:le,preventScrollReset:E})}}async function Be(I,M,z,G){try{let le=await lG(u,I,M,z,G,i,o);return await Promise.all(le.map((je,Ie)=>{if(mG(je)){let Y=je.result;return{type:pt.redirect,response:dG(Y,M,z[Ie].route.id,G,c,f.v7_relativeSplatPath)}}return uG(je)}))}catch(le){return z.map(()=>({type:pt.error,error:le}))}}async function Nt(I,M,z,G,le){let[je,...Ie]=await Promise.all([z.length?Be("loader",le,z,M):[],...G.map(Y=>{if(Y.matches&&Y.match&&Y.controller){let $e=ha(e.history,Y.path,Y.controller.signal);return Be("loader",$e,[Y.match],Y.matches).then(ke=>ke[0])}else return Promise.resolve({type:pt.error,error:An(404,{pathname:Y.path})})})]);return await Promise.all([sS(I,z,je,je.map(()=>le.signal),!1,j.loaderData),sS(I,G.map(Y=>Y.match),Ie,G.map(Y=>Y.controller?Y.controller.signal:null),!0)]),{loaderResults:je,fetcherResults:Ie}}function Pt(){N=!0,F.push(...jn()),K.forEach((I,M)=>{R.has(M)&&(D.add(M),vr(M))})}function $t(I,M,z){z===void 0&&(z={}),j.fetchers.set(I,M),Ve({fetchers:new Map(j.fetchers)},{flushSync:(z&&z.flushSync)===!0})}function St(I,M,z,G){G===void 0&&(G={});let le=Da(j.matches,M);rr(I),Ve({errors:{[le.route.id]:z},fetchers:new Map(j.fetchers)},{flushSync:(G&&G.flushSync)===!0})}function Sn(I){return f.v7_fetcherPersist&&(ie.set(I,(ie.get(I)||0)+1),Re.has(I)&&Re.delete(I)),j.fetchers.get(I)||eG}function rr(I){let M=j.fetchers.get(I);R.has(I)&&!(M&&M.state==="loading"&&L.has(I))&&vr(I),K.delete(I),L.delete(I),V.delete(I),Re.delete(I),D.delete(I),j.fetchers.delete(I)}function Ki(I){if(f.v7_fetcherPersist){let M=(ie.get(I)||0)-1;M<=0?(ie.delete(I),Re.add(I)):ie.set(I,M)}else rr(I);Ve({fetchers:new Map(j.fetchers)})}function vr(I){let M=R.get(I);Ue(M,"Expected fetch controller: "+I),M.abort(),R.delete(I)}function Tu(I){for(let M of I){let z=Sn(M),G=li(z.data);j.fetchers.set(M,G)}}function Pu(){let I=[],M=!1;for(let z of V){let G=j.fetchers.get(z);Ue(G,"Expected fetcher: "+z),G.state==="loading"&&(V.delete(z),I.push(z),M=!0)}return Tu(I),M}function yr(I){let M=[];for(let[z,G]of L)if(G<I){let le=j.fetchers.get(z);Ue(le,"Expected fetcher: "+z),le.state==="loading"&&(vr(z),L.delete(z),M.push(z))}return Tu(M),M.length>0}function Tl(I,M){let z=j.blockers.get(I)||Ul;return Ee.get(I)!==M&&Ee.set(I,M),z}function ku(I){j.blockers.delete(I),Ee.delete(I)}function Yi(I,M){let z=j.blockers.get(I)||Ul;Ue(z.state==="unblocked"&&M.state==="blocked"||z.state==="blocked"&&M.state==="blocked"||z.state==="blocked"&&M.state==="proceeding"||z.state==="blocked"&&M.state==="unblocked"||z.state==="proceeding"&&M.state==="unblocked","Invalid blocker state transition: "+z.state+" -> "+M.state);let G=new Map(j.blockers);G.set(I,M),Ve({blockers:G})}function Js(I){let{currentLocation:M,nextLocation:z,historyAction:G}=I;if(Ee.size===0)return;Ee.size>1&&il(!1,"A router only supports one blocker at a time");let le=Array.from(Ee.entries()),[je,Ie]=le[le.length-1],Y=j.blockers.get(je);if(!(Y&&Y.state==="proceeding")&&Ie({currentLocation:M,nextLocation:z,historyAction:G}))return je}function Xi(I){let M=An(404,{pathname:I}),z=l||a,{matches:G,route:le}=rS(z);return jn(),{notFoundMatches:G,route:le,error:M}}function Or(I,M){return{boundaryId:Da(M.partialMatches).route.id,error:An(400,{type:"route-discovery",pathname:I,message:M.error!=null&&"message"in M.error?M.error:String(M.error)})}}function jn(I){let M=[];return ae.forEach((z,G)=>{(!I||I(G))&&(z.cancel(),M.push(G),ae.delete(G))}),M}function Jh(I,M,z){if(g=I,S=M,v=z||null,!y&&j.navigation===em){y=!0;let G=Ru(j.location,j.matches);G!=null&&Ve({restoreScrollPosition:G})}return()=>{g=null,S=null,v=null}}function Zh(I,M){return v&&v(I,M.map(G=>Dq(G,j.loaderData)))||I.key}function ep(I,M){if(g&&S){let z=Zh(I,M);g[z]=S()}}function Ru(I,M){if(g){let z=Zh(I,M),G=g[z];if(typeof G=="number")return G}return null}function Kt(I,M,z){if(d)if(I){let G=I[I.length-1].route;if(G.path&&(G.path==="*"||G.path.endsWith("/*")))return{active:!0,matches:_d(M,z,c,!0)}}else return{active:!0,matches:_d(M,z,c,!0)||[]};return{active:!1,matches:null}}async function oo(I,M,z){let G=I,le=G.length>0?G[G.length-1].route:null;for(;;){let je=l==null,Ie=l||a;try{await sG(d,M,G,Ie,i,o,Fe,z)}catch(_e){return{type:"error",error:_e,partialMatches:G}}finally{je&&(a=[...a])}if(z.aborted)return{type:"aborted"};let Y=as(Ie,M,c),$e=!1;if(Y){let _e=Y[Y.length-1].route;if(_e.index)return{type:"success",matches:Y};if(_e.path&&_e.path.length>0)if(_e.path==="*")$e=!0;else return{type:"success",matches:Y}}let ke=_d(Ie,M,c,!0);if(!ke||G.map(_e=>_e.route.id).join("-")===ke.map(_e=>_e.route.id).join("-"))return{type:"success",matches:$e?Y:null};if(G=ke,le=G[G.length-1].route,le.path==="*")return{type:"success",matches:G}}}function Pl(I){i={},l=Bc(I,o,void 0,i)}function Zs(I,M){let z=l==null;l2(I,M,l||a,i,o),z&&(a=[...a],Ve({}))}return C={get basename(){return c},get future(){return f},get state(){return j},get routes(){return a},get window(){return t},initialize:Le,subscribe:Tt,enableScrollRestoration:Jh,navigate:Pe,fetch:ne,revalidate:Xe,createHref:I=>e.history.createHref(I),encodeLocation:I=>e.history.encodeLocation(I),getFetcher:Sn,deleteFetcher:Ki,dispose:nt,getBlocker:Tl,deleteBlocker:ku,patchRoutes:Zs,_internalFetchControllers:R,_internalActiveDeferreds:ae,_internalSetRoutes:Pl},C}function rG(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function Ng(e,t,n,r,o,i,a,l){let c,u;if(a){c=[];for(let f of t)if(c.push(f),f.route.id===a){u=f;break}}else c=t,u=t[t.length-1];let d=o2(o||".",r2(c,i),ju(e.pathname,n)||e.pathname,l==="path");return o==null&&(d.search=e.search,d.hash=e.hash),(o==null||o===""||o===".")&&u&&u.route.index&&!y0(d.search)&&(d.search=d.search?d.search.replace(/^\?/,"?index&"):"?index"),r&&n!=="/"&&(d.pathname=d.pathname==="/"?n:_i([n,d.pathname])),Su(d)}function Qw(e,t,n,r){if(!r||!rG(r))return{path:n};if(r.formMethod&&!vG(r.formMethod))return{path:n,error:An(405,{method:r.formMethod})};let o=()=>({path:n,error:An(400,{type:"invalid-body"})}),i=r.formMethod||"get",a=e?i.toUpperCase():i.toLowerCase(),l=c2(n);if(r.body!==void 0){if(r.formEncType==="text/plain"){if(!Ur(a))return o();let h=typeof r.body=="string"?r.body:r.body instanceof FormData||r.body instanceof URLSearchParams?Array.from(r.body.entries()).reduce((m,g)=>{let[v,S]=g;return""+m+v+"="+S+`
553
- `},""):String(r.body);return{path:n,submission:{formMethod:a,formAction:l,formEncType:r.formEncType,formData:void 0,json:void 0,text:h}}}else if(r.formEncType==="application/json"){if(!Ur(a))return o();try{let h=typeof r.body=="string"?JSON.parse(r.body):r.body;return{path:n,submission:{formMethod:a,formAction:l,formEncType:r.formEncType,formData:void 0,json:h,text:void 0}}}catch{return o()}}}Ue(typeof FormData=="function","FormData is not available in this environment");let c,u;if(r.formData)c=Mg(r.formData),u=r.formData;else if(r.body instanceof FormData)c=Mg(r.body),u=r.body;else if(r.body instanceof URLSearchParams)c=r.body,u=Zw(c);else if(r.body==null)c=new URLSearchParams,u=new FormData;else try{c=new URLSearchParams(r.body),u=Zw(c)}catch{return o()}let d={formMethod:a,formAction:l,formEncType:r&&r.formEncType||"application/x-www-form-urlencoded",formData:u,json:void 0,text:void 0};if(Ur(d.formMethod))return{path:n,submission:d};let f=ri(n);return t&&f.search&&y0(f.search)&&c.append("index",""),f.search="?"+c,{path:Su(f),submission:d}}function oG(e,t){let n=e;if(t){let r=e.findIndex(o=>o.route.id===t);r>=0&&(n=e.slice(0,r))}return n}function Kw(e,t,n,r,o,i,a,l,c,u,d,f,h,m,g,v){let S=v?sr(v[1])?v[1].error:v[1].data:void 0,y=e.createURL(t.location),w=e.createURL(o),b=v&&sr(v[1])?v[0]:void 0,x=b?oG(n,b):n,C=v?v[1].statusCode:void 0,j=a&&C&&C>=400,T=x.filter((_,k)=>{let{route:A}=_;if(A.lazy)return!0;if(A.loader==null)return!1;if(i)return typeof A.loader!="function"||A.loader.hydrate?!0:t.loaderData[A.id]===void 0&&(!t.errors||t.errors[A.id]===void 0);if(iG(t.loaderData,t.matches[k],_)||c.some(N=>N===_.route.id))return!0;let O=t.matches[k],U=_;return Yw(_,Ft({currentUrl:y,currentParams:O.params,nextUrl:w,nextParams:U.params},r,{actionResult:S,actionStatus:C,defaultShouldRevalidate:j?!1:l||y.pathname+y.search===w.pathname+w.search||y.search!==w.search||a2(O,U)}))}),E=[];return f.forEach((_,k)=>{if(i||!n.some(F=>F.route.id===_.routeId)||d.has(k))return;let A=as(m,_.path,g);if(!A){E.push({key:k,routeId:_.routeId,path:_.path,matches:null,match:null,controller:null});return}let O=t.fetchers.get(k),U=Xl(A,_.path),N=!1;h.has(k)?N=!1:u.has(k)?(u.delete(k),N=!0):O&&O.state!=="idle"&&O.data===void 0?N=l:N=Yw(U,Ft({currentUrl:y,currentParams:t.matches[t.matches.length-1].params,nextUrl:w,nextParams:n[n.length-1].params},r,{actionResult:S,actionStatus:C,defaultShouldRevalidate:j?!1:l})),N&&E.push({key:k,routeId:_.routeId,path:_.path,matches:A,match:U,controller:new AbortController})}),[T,E]}function iG(e,t,n){let r=!t||n.route.id!==t.route.id,o=e[n.route.id]===void 0;return r||o}function a2(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function Yw(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}async function sG(e,t,n,r,o,i,a,l){let c=[t,...n.map(u=>u.route.id)].join("-");try{let u=a.get(c);u||(u=e({path:t,matches:n,patch:(d,f)=>{l.aborted||l2(d,f,r,o,i)}}),a.set(c,u)),u&&pG(u)&&await u}finally{a.delete(c)}}function l2(e,t,n,r,o){if(e){var i;let a=r[e];Ue(a,"No route found to patch children into: routeId = "+e);let l=Bc(t,o,[e,"patch",String(((i=a.children)==null?void 0:i.length)||"0")],r);a.children?a.children.push(...l):a.children=l}else{let a=Bc(t,o,["patch",String(n.length||"0")],r);n.push(...a)}}async function Xw(e,t,n){if(!e.lazy)return;let r=await e.lazy();if(!e.lazy)return;let o=n[e.id];Ue(o,"No route found in manifest");let i={};for(let a in r){let c=o[a]!==void 0&&a!=="hasErrorBoundary";il(!c,'Route "'+o.id+'" has a static property "'+a+'" defined but its lazy function is also returning a value for this property. '+('The lazy route property "'+a+'" will be ignored.')),!c&&!Rq.has(a)&&(i[a]=r[a])}Object.assign(o,i),Object.assign(o,Ft({},t(o),{lazy:void 0}))}function aG(e){return Promise.all(e.matches.map(t=>t.resolve()))}async function lG(e,t,n,r,o,i,a,l){let c=r.reduce((f,h)=>f.add(h.route.id),new Set),u=new Set,d=await e({matches:o.map(f=>{let h=c.has(f.route.id);return Ft({},f,{shouldLoad:h,resolve:g=>(u.add(f.route.id),h?cG(t,n,f,i,a,g,l):Promise.resolve({type:pt.data,result:void 0}))})}),request:n,params:o[0].params,context:l});return o.forEach(f=>Ue(u.has(f.route.id),'`match.resolve()` was not called for route id "'+f.route.id+'". You must call `match.resolve()` on every match passed to `dataStrategy` to ensure all routes are properly loaded.')),d.filter((f,h)=>c.has(o[h].route.id))}async function cG(e,t,n,r,o,i,a){let l,c,u=d=>{let f,h=new Promise((v,S)=>f=S);c=()=>f(),t.signal.addEventListener("abort",c);let m=v=>typeof d!="function"?Promise.reject(new Error("You cannot call the handler for a route which defines a boolean "+('"'+e+'" [routeId: '+n.route.id+"]"))):d({request:t,params:n.params,context:a},...v!==void 0?[v]:[]),g;return i?g=i(v=>m(v)):g=(async()=>{try{return{type:"data",result:await m()}}catch(v){return{type:"error",result:v}}})(),Promise.race([g,h])};try{let d=n.route[e];if(n.route.lazy)if(d){let f,[h]=await Promise.all([u(d).catch(m=>{f=m}),Xw(n.route,o,r)]);if(f!==void 0)throw f;l=h}else if(await Xw(n.route,o,r),d=n.route[e],d)l=await u(d);else if(e==="action"){let f=new URL(t.url),h=f.pathname+f.search;throw An(405,{method:t.method,pathname:h,routeId:n.route.id})}else return{type:pt.data,result:void 0};else if(d)l=await u(d);else{let f=new URL(t.url),h=f.pathname+f.search;throw An(404,{pathname:h})}Ue(l.result!==void 0,"You defined "+(e==="action"?"an action":"a loader")+" for route "+('"'+n.route.id+"\" but didn't return anything from your `"+e+"` ")+"function. Please return a value or `null`.")}catch(d){return{type:pt.error,result:d}}finally{c&&t.signal.removeEventListener("abort",c)}return l}async function uG(e){let{result:t,type:n}=e;if(u2(t)){let u;try{let d=t.headers.get("Content-Type");d&&/\bapplication\/json\b/.test(d)?t.body==null?u=null:u=await t.json():u=await t.text()}catch(d){return{type:pt.error,error:d}}return n===pt.error?{type:pt.error,error:new Cf(t.status,t.statusText,u),statusCode:t.status,headers:t.headers}:{type:pt.data,data:u,statusCode:t.status,headers:t.headers}}if(n===pt.error){if(iS(t)){var r;if(t.data instanceof Error){var o;return{type:pt.error,error:t.data,statusCode:(o=t.init)==null?void 0:o.status}}t=new Cf(((r=t.init)==null?void 0:r.status)||500,void 0,t.data)}return{type:pt.error,error:t,statusCode:Wh(t)?t.status:void 0}}if(gG(t)){var i,a;return{type:pt.deferred,deferredData:t,statusCode:(i=t.init)==null?void 0:i.status,headers:((a=t.init)==null?void 0:a.headers)&&new Headers(t.init.headers)}}if(iS(t)){var l,c;return{type:pt.data,data:t.data,statusCode:(l=t.init)==null?void 0:l.status,headers:(c=t.init)!=null&&c.headers?new Headers(t.init.headers):void 0}}return{type:pt.data,data:t}}function dG(e,t,n,r,o,i){let a=e.headers.get("Location");if(Ue(a,"Redirects returned/thrown from loaders/actions must have a Location header"),!v0.test(a)){let l=r.slice(0,r.findIndex(c=>c.route.id===n)+1);a=Ng(new URL(t.url),l,o,!0,a,i),e.headers.set("Location",a)}return e}function Jw(e,t,n){if(v0.test(e)){let r=e,o=r.startsWith("//")?new URL(t.protocol+r):new URL(r),i=ju(o.pathname,n)!=null;if(o.origin===t.origin&&i)return o.pathname+o.search+o.hash}return e}function ha(e,t,n,r){let o=e.createURL(c2(t)).toString(),i={signal:n};if(r&&Ur(r.formMethod)){let{formMethod:a,formEncType:l}=r;i.method=a.toUpperCase(),l==="application/json"?(i.headers=new Headers({"Content-Type":l}),i.body=JSON.stringify(r.json)):l==="text/plain"?i.body=r.text:l==="application/x-www-form-urlencoded"&&r.formData?i.body=Mg(r.formData):i.body=r.formData}return new Request(o,i)}function Mg(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function Zw(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function fG(e,t,n,r,o,i){let a={},l=null,c,u=!1,d={},f=r&&sr(r[1])?r[1].error:void 0;return n.forEach((h,m)=>{let g=t[m].route.id;if(Ue(!ms(h),"Cannot handle redirect results in processLoaderData"),sr(h)){let v=h.error;f!==void 0&&(v=f,f=void 0),l=l||{};{let S=Da(e,g);l[S.route.id]==null&&(l[S.route.id]=v)}a[g]=void 0,u||(u=!0,c=Wh(h.error)?h.error.status:500),h.headers&&(d[g]=h.headers)}else ps(h)?(o.set(g,h.deferredData),a[g]=h.deferredData.data,h.statusCode!=null&&h.statusCode!==200&&!u&&(c=h.statusCode),h.headers&&(d[g]=h.headers)):(a[g]=h.data,h.statusCode&&h.statusCode!==200&&!u&&(c=h.statusCode),h.headers&&(d[g]=h.headers))}),f!==void 0&&r&&(l={[r[0]]:f},a[r[0]]=void 0),{loaderData:a,errors:l,statusCode:c||200,loaderHeaders:d}}function eS(e,t,n,r,o,i,a,l){let{loaderData:c,errors:u}=fG(t,n,r,o,l);for(let d=0;d<i.length;d++){let{key:f,match:h,controller:m}=i[d];Ue(a!==void 0&&a[d]!==void 0,"Did not find corresponding fetcher result");let g=a[d];if(!(m&&m.signal.aborted))if(sr(g)){let v=Da(e.matches,h==null?void 0:h.route.id);u&&u[v.route.id]||(u=Ft({},u,{[v.route.id]:g.error})),e.fetchers.delete(f)}else if(ms(g))Ue(!1,"Unhandled fetcher revalidation redirect");else if(ps(g))Ue(!1,"Unhandled fetcher deferred data");else{let v=li(g.data);e.fetchers.set(f,v)}}return{loaderData:c,errors:u}}function tS(e,t,n,r){let o=Ft({},t);for(let i of n){let a=i.route.id;if(t.hasOwnProperty(a)?t[a]!==void 0&&(o[a]=t[a]):e[a]!==void 0&&i.route.loader&&(o[a]=e[a]),r&&r.hasOwnProperty(a))break}return o}function nS(e){return e?sr(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function Da(e,t){return(t?e.slice(0,e.findIndex(r=>r.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function rS(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function An(e,t){let{pathname:n,routeId:r,method:o,type:i,message:a}=t===void 0?{}:t,l="Unknown Server Error",c="Unknown @remix-run/router error";return e===400?(l="Bad Request",i==="route-discovery"?c='Unable to match URL "'+n+'" - the `unstable_patchRoutesOnMiss()` '+(`function threw the following error:
554
- `+a):o&&n&&r?c="You made a "+o+' request to "'+n+'" but '+('did not provide a `loader` for route "'+r+'", ')+"so there is no way to handle the request.":i==="defer-action"?c="defer() is not supported in actions":i==="invalid-body"&&(c="Unable to encode submission body")):e===403?(l="Forbidden",c='Route "'+r+'" does not match URL "'+n+'"'):e===404?(l="Not Found",c='No route matches URL "'+n+'"'):e===405&&(l="Method Not Allowed",o&&n&&r?c="You made a "+o.toUpperCase()+' request to "'+n+'" but '+('did not provide an `action` for route "'+r+'", ')+"so there is no way to handle the request.":o&&(c='Invalid request method "'+o.toUpperCase()+'"')),new Cf(e||500,l,new Error(c),!0)}function oS(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(ms(n))return{result:n,idx:t}}}function c2(e){let t=typeof e=="string"?ri(e):e;return Su(Ft({},t,{hash:""}))}function hG(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function pG(e){return typeof e=="object"&&e!=null&&"then"in e}function mG(e){return u2(e.result)&&Jq.has(e.result.status)}function ps(e){return e.type===pt.deferred}function sr(e){return e.type===pt.error}function ms(e){return(e&&e.type)===pt.redirect}function iS(e){return typeof e=="object"&&e!=null&&"type"in e&&"data"in e&&"init"in e&&e.type==="DataWithResponseInit"}function gG(e){let t=e;return t&&typeof t=="object"&&typeof t.data=="object"&&typeof t.subscribe=="function"&&typeof t.cancel=="function"&&typeof t.resolveData=="function"}function u2(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function vG(e){return Xq.has(e.toLowerCase())}function Ur(e){return Kq.has(e.toLowerCase())}async function sS(e,t,n,r,o,i){for(let a=0;a<n.length;a++){let l=n[a],c=t[a];if(!c)continue;let u=e.find(f=>f.route.id===c.route.id),d=u!=null&&!a2(u,c)&&(i&&i[c.route.id])!==void 0;if(ps(l)&&(o||d)){let f=r[a];Ue(f,"Expected an AbortSignal for revalidating fetcher deferred result"),await d2(l,f,o).then(h=>{h&&(n[a]=h||n[a])})}}}async function d2(e,t,n){if(n===void 0&&(n=!1),!await e.deferredData.resolveData(t)){if(n)try{return{type:pt.data,data:e.deferredData.unwrappedData}}catch(o){return{type:pt.error,error:o}}return{type:pt.data,data:e.deferredData.data}}}function y0(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function Xl(e,t){let n=typeof t=="string"?ri(t).search:t.search;if(e[e.length-1].route.index&&y0(n||""))return e[e.length-1];let r=n2(e);return r[r.length-1]}function aS(e){let{formMethod:t,formAction:n,formEncType:r,text:o,formData:i,json:a}=e;if(!(!t||!n||!r)){if(o!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:o};if(i!=null)return{formMethod:t,formAction:n,formEncType:r,formData:i,json:void 0,text:void 0};if(a!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:a,text:void 0}}}function tm(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function yG(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function Vl(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function xG(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function li(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function bG(e,t){try{let n=e.sessionStorage.getItem(s2);if(n){let r=JSON.parse(n);for(let[o,i]of Object.entries(r||{}))i&&Array.isArray(i)&&t.set(o,new Set(i||[]))}}catch{}}function wG(e,t){if(t.size>0){let n={};for(let[r,o]of t)n[r]=[...o];try{e.sessionStorage.setItem(s2,JSON.stringify(n))}catch(r){il(!1,"Failed to save applied view transitions in sessionStorage ("+r+").")}}}/**
552
+ */function Ft(){return Ft=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},Ft.apply(this,arguments)}var Yt;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Yt||(Yt={}));const Ww="popstate";function Pq(e){e===void 0&&(e={});function t(r,o){let{pathname:i,search:a,hash:l}=r.location;return zc("",{pathname:i,search:a,hash:l},o.state&&o.state.usr||null,o.state&&o.state.key||"default")}function n(r,o){return typeof o=="string"?o:Su(o)}return Rq(t,n,null,e)}function Ue(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function il(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function kq(){return Math.random().toString(36).substr(2,8)}function Hw(e,t){return{usr:e.state,key:e.key,idx:t}}function zc(e,t,n,r){return n===void 0&&(n=null),Ft({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?ri(t):t,{state:n,key:t&&t.key||r||kq()})}function Su(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function ri(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function Rq(e,t,n,r){r===void 0&&(r={});let{window:o=document.defaultView,v5Compat:i=!1}=r,a=o.history,l=Yt.Pop,c=null,u=d();u==null&&(u=0,a.replaceState(Ft({},a.state,{idx:u}),""));function d(){return(a.state||{idx:null}).idx}function f(){l=Yt.Pop;let S=d(),y=S==null?null:S-u;u=S,c&&c({action:l,location:v.location,delta:y})}function h(S,y){l=Yt.Push;let w=zc(v.location,S,y);u=d()+1;let b=Hw(w,u),x=v.createHref(w);try{a.pushState(b,"",x)}catch(C){if(C instanceof DOMException&&C.name==="DataCloneError")throw C;o.location.assign(x)}i&&c&&c({action:l,location:v.location,delta:1})}function m(S,y){l=Yt.Replace;let w=zc(v.location,S,y);u=d();let b=Hw(w,u),x=v.createHref(w);a.replaceState(b,"",x),i&&c&&c({action:l,location:v.location,delta:0})}function g(S){let y=o.location.origin!=="null"?o.location.origin:o.location.href,w=typeof S=="string"?S:Su(S);return w=w.replace(/ $/,"%20"),Ue(y,"No window.location.(origin|href) available to create URL for href: "+w),new URL(w,y)}let v={get action(){return l},get location(){return e(o,a)},listen(S){if(c)throw new Error("A history only accepts one active listener");return o.addEventListener(Ww,f),c=S,()=>{o.removeEventListener(Ww,f),c=null}},createHref(S){return t(o,S)},createURL:g,encodeLocation(S){let y=g(S);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:h,replace:m,go(S){return a.go(S)}};return v}var pt;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(pt||(pt={}));const _q=new Set(["lazy","caseSensitive","path","id","index","children"]);function Dq(e){return e.index===!0}function Bc(e,t,n,r){return n===void 0&&(n=[]),r===void 0&&(r={}),e.map((o,i)=>{let a=[...n,String(i)],l=typeof o.id=="string"?o.id:a.join("-");if(Ue(o.index!==!0||!o.children,"Cannot specify children on an index route"),Ue(!r[l],'Found a route id collision on id "'+l+`". Route id's must be globally unique within Data Router usages`),Dq(o)){let c=Ft({},o,t(o),{id:l});return r[l]=c,c}else{let c=Ft({},o,t(o),{id:l,children:void 0});return r[l]=c,o.children&&(c.children=Bc(o.children,t,a,r)),c}})}function as(e,t,n){return n===void 0&&(n="/"),_d(e,t,n,!1)}function _d(e,t,n,r){let o=typeof t=="string"?ri(t):t,i=ju(o.pathname||"/",n);if(i==null)return null;let a=e2(e);Aq(a);let l=null;for(let c=0;l==null&&c<a.length;++c){let u=Wq(i);l=Uq(a[c],u,r)}return l}function Iq(e,t){let{route:n,pathname:r,params:o}=e;return{id:n.id,pathname:r,params:o,data:t[n.id],handle:n.handle}}function e2(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let o=(i,a,l)=>{let c={relativePath:l===void 0?i.path||"":l,caseSensitive:i.caseSensitive===!0,childrenIndex:a,route:i};c.relativePath.startsWith("/")&&(Ue(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let u=_i([r,c.relativePath]),d=n.concat(c);i.children&&i.children.length>0&&(Ue(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+u+'".')),e2(i.children,t,d,u)),!(i.path==null&&!i.index)&&t.push({path:u,score:zq(u,i.index),routesMeta:d})};return e.forEach((i,a)=>{var l;if(i.path===""||!((l=i.path)!=null&&l.includes("?")))o(i,a);else for(let c of t2(i.path))o(i,a,c)}),t}function t2(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,o=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return o?[i,""]:[i];let a=t2(r.join("/")),l=[];return l.push(...a.map(c=>c===""?i:[i,c].join("/"))),o&&l.push(...a),l.map(c=>e.startsWith("/")&&c===""?"/":c)}function Aq(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:Bq(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Nq=/^:[\w-]+$/,Mq=3,Oq=2,Lq=1,$q=10,Fq=-2,qw=e=>e==="*";function zq(e,t){let n=e.split("/"),r=n.length;return n.some(qw)&&(r+=Fq),t&&(r+=Oq),n.filter(o=>!qw(o)).reduce((o,i)=>o+(Nq.test(i)?Mq:i===""?Lq:$q),r)}function Bq(e,t){return e.length===t.length&&e.slice(0,-1).every((r,o)=>r===t[o])?e[e.length-1]-t[t.length-1]:0}function Uq(e,t,n){n===void 0&&(n=!1);let{routesMeta:r}=e,o={},i="/",a=[];for(let l=0;l<r.length;++l){let c=r[l],u=l===r.length-1,d=i==="/"?t:t.slice(i.length)||"/",f=Gw({path:c.relativePath,caseSensitive:c.caseSensitive,end:u},d),h=c.route;if(!f&&u&&n&&!r[r.length-1].route.index&&(f=Gw({path:c.relativePath,caseSensitive:c.caseSensitive,end:!1},d)),!f)return null;Object.assign(o,f.params),a.push({params:o,pathname:_i([i,f.pathname]),pathnameBase:Gq(_i([i,f.pathnameBase])),route:h}),f.pathnameBase!=="/"&&(i=_i([i,f.pathnameBase]))}return a}function Gw(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Vq(e.path,e.caseSensitive,e.end),o=t.match(n);if(!o)return null;let i=o[0],a=i.replace(/(.)\/+$/,"$1"),l=o.slice(1);return{params:r.reduce((u,d,f)=>{let{paramName:h,isOptional:m}=d;if(h==="*"){let v=l[f]||"";a=i.slice(0,i.length-v.length).replace(/(.)\/+$/,"$1")}const g=l[f];return m&&!g?u[h]=void 0:u[h]=(g||"").replace(/%2F/g,"/"),u},{}),pathname:i,pathnameBase:a,pattern:e}}function Vq(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),il(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],o="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,l,c)=>(r.push({paramName:l,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),o+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?o+="\\/*$":e!==""&&e!=="/"&&(o+="(?:(?=\\/|$))"),[new RegExp(o,t?void 0:"i"),r]}function Wq(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return il(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function ju(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function Hq(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:o=""}=typeof e=="string"?ri(e):e;return{pathname:n?n.startsWith("/")?n:qq(n,t):t,search:Qq(r),hash:Kq(o)}}function qq(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(o=>{o===".."?n.length>1&&n.pop():o!=="."&&n.push(o)}),n.length>1?n.join("/"):"/"}function Zp(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function n2(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function r2(e,t){let n=n2(e);return t?n.map((r,o)=>o===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function o2(e,t,n,r){r===void 0&&(r=!1);let o;typeof e=="string"?o=ri(e):(o=Ft({},e),Ue(!o.pathname||!o.pathname.includes("?"),Zp("?","pathname","search",o)),Ue(!o.pathname||!o.pathname.includes("#"),Zp("#","pathname","hash",o)),Ue(!o.search||!o.search.includes("#"),Zp("#","search","hash",o)));let i=e===""||o.pathname==="",a=i?"/":o.pathname,l;if(a==null)l=n;else{let f=t.length-1;if(!r&&a.startsWith("..")){let h=a.split("/");for(;h[0]==="..";)h.shift(),f-=1;o.pathname=h.join("/")}l=f>=0?t[f]:"/"}let c=Hq(o,l),u=a&&a!=="/"&&a.endsWith("/"),d=(i||a===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(u||d)&&(c.pathname+="/"),c}const _i=e=>e.join("/").replace(/\/\/+/g,"/"),Gq=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Qq=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Kq=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class Cf{constructor(t,n,r,o){o===void 0&&(o=!1),this.status=t,this.statusText=n||"",this.internal=o,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function Wh(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const i2=["post","put","patch","delete"],Yq=new Set(i2),Xq=["get",...i2],Jq=new Set(Xq),Zq=new Set([301,302,303,307,308]),eG=new Set([307,308]),em={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},tG={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Ul={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},v0=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,nG=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),s2="remix-router-transitions";function rG(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u",r=!n;Ue(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let o;if(e.mapRouteProperties)o=e.mapRouteProperties;else if(e.detectErrorBoundary){let I=e.detectErrorBoundary;o=M=>({hasErrorBoundary:I(M)})}else o=nG;let i={},a=Bc(e.routes,o,void 0,i),l,c=e.basename||"/",u=e.unstable_dataStrategy||lG,d=e.unstable_patchRoutesOnMiss,f=Ft({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),h=null,m=new Set,g=null,v=null,S=null,y=e.hydrationData!=null,w=as(a,e.history.location,c),b=null;if(w==null&&!d){let I=An(404,{pathname:e.history.location.pathname}),{matches:M,route:z}=rS(a);w=M,b={[z.id]:I}}w&&!e.hydrationData&&Kt(w,a,e.history.location.pathname).active&&(w=null);let x;if(w)if(w.some(I=>I.route.lazy))x=!1;else if(!w.some(I=>I.route.loader))x=!0;else if(f.v7_partialHydration){let I=e.hydrationData?e.hydrationData.loaderData:null,M=e.hydrationData?e.hydrationData.errors:null,z=G=>G.route.loader?typeof G.route.loader=="function"&&G.route.loader.hydrate===!0?!1:I&&I[G.route.id]!==void 0||M&&M[G.route.id]!==void 0:!0;if(M){let G=w.findIndex(le=>M[le.route.id]!==void 0);x=w.slice(0,G+1).every(z)}else x=w.every(z)}else x=e.hydrationData!=null;else if(x=!1,w=[],f.v7_partialHydration){let I=Kt(null,a,e.history.location.pathname);I.active&&I.matches&&(w=I.matches)}let C,j={historyAction:e.history.action,location:e.history.location,matches:w,initialized:x,navigation:em,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||b,fetchers:new Map,blockers:new Map},T=Yt.Pop,E=!1,_,k=!1,A=new Map,O=null,U=!1,N=!1,F=[],D=new Set,R=new Map,P=0,$=-1,L=new Map,V=new Set,K=new Map,ie=new Map,Re=new Set,ae=new Map,Ee=new Map,Fe=new Map,me=!1;function Le(){if(h=e.history.listen(I=>{let{action:M,location:z,delta:G}=I;if(me){me=!1;return}il(Ee.size===0||G!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let le=Js({currentLocation:j.location,nextLocation:z,historyAction:M});if(le&&G!=null){me=!0,e.history.go(G*-1),Yi(le,{state:"blocked",location:z,proceed(){Yi(le,{state:"proceeding",proceed:void 0,reset:void 0,location:z}),e.history.go(G)},reset(){let je=new Map(j.blockers);je.set(le,Ul),Ve({blockers:je})}});return}return Qe(M,z)}),n){wG(t,A);let I=()=>SG(t,A);t.addEventListener("pagehide",I),O=()=>t.removeEventListener("pagehide",I)}return j.initialized||Qe(Yt.Pop,j.location,{initialHydration:!0}),C}function nt(){h&&h(),O&&O(),m.clear(),_&&_.abort(),j.fetchers.forEach((I,M)=>rr(M)),j.blockers.forEach((I,M)=>ku(M))}function Tt(I){return m.add(I),()=>m.delete(I)}function Ve(I,M){M===void 0&&(M={}),j=Ft({},j,I);let z=[],G=[];f.v7_fetcherPersist&&j.fetchers.forEach((le,je)=>{le.state==="idle"&&(Re.has(je)?G.push(je):z.push(je))}),[...m].forEach(le=>le(j,{deletedFetchers:G,unstable_viewTransitionOpts:M.viewTransitionOpts,unstable_flushSync:M.flushSync===!0})),f.v7_fetcherPersist&&(z.forEach(le=>j.fetchers.delete(le)),G.forEach(le=>rr(le)))}function Te(I,M,z){var G,le;let{flushSync:je}=z===void 0?{}:z,Ie=j.actionData!=null&&j.navigation.formMethod!=null&&Ur(j.navigation.formMethod)&&j.navigation.state==="loading"&&((G=I.state)==null?void 0:G._isRedirect)!==!0,Y;M.actionData?Object.keys(M.actionData).length>0?Y=M.actionData:Y=null:Ie?Y=j.actionData:Y=null;let $e=M.loaderData?tS(j.loaderData,M.loaderData,M.matches||[],M.errors):j.loaderData,ke=j.blockers;ke.size>0&&(ke=new Map(ke),ke.forEach((ut,mt)=>ke.set(mt,Ul)));let _e=E===!0||j.navigation.formMethod!=null&&Ur(j.navigation.formMethod)&&((le=I.state)==null?void 0:le._isRedirect)!==!0;l&&(a=l,l=void 0),U||T===Yt.Pop||(T===Yt.Push?e.history.push(I,I.state):T===Yt.Replace&&e.history.replace(I,I.state));let ot;if(T===Yt.Pop){let ut=A.get(j.location.pathname);ut&&ut.has(I.pathname)?ot={currentLocation:j.location,nextLocation:I}:A.has(I.pathname)&&(ot={currentLocation:I,nextLocation:j.location})}else if(k){let ut=A.get(j.location.pathname);ut?ut.add(I.pathname):(ut=new Set([I.pathname]),A.set(j.location.pathname,ut)),ot={currentLocation:j.location,nextLocation:I}}Ve(Ft({},M,{actionData:Y,loaderData:$e,historyAction:T,location:I,initialized:!0,navigation:em,revalidation:"idle",restoreScrollPosition:Ru(I,M.matches||j.matches),preventScrollReset:_e,blockers:ke}),{viewTransitionOpts:ot,flushSync:je===!0}),T=Yt.Pop,E=!1,k=!1,U=!1,N=!1,F=[]}async function Pe(I,M){if(typeof I=="number"){e.history.go(I);return}let z=Ng(j.location,j.matches,c,f.v7_prependBasename,I,f.v7_relativeSplatPath,M==null?void 0:M.fromRouteId,M==null?void 0:M.relative),{path:G,submission:le,error:je}=Qw(f.v7_normalizeFormMethod,!1,z,M),Ie=j.location,Y=zc(j.location,G,M&&M.state);Y=Ft({},Y,e.history.encodeLocation(Y));let $e=M&&M.replace!=null?M.replace:void 0,ke=Yt.Push;$e===!0?ke=Yt.Replace:$e===!1||le!=null&&Ur(le.formMethod)&&le.formAction===j.location.pathname+j.location.search&&(ke=Yt.Replace);let _e=M&&"preventScrollReset"in M?M.preventScrollReset===!0:void 0,ot=(M&&M.unstable_flushSync)===!0,ut=Js({currentLocation:Ie,nextLocation:Y,historyAction:ke});if(ut){Yi(ut,{state:"blocked",location:Y,proceed(){Yi(ut,{state:"proceeding",proceed:void 0,reset:void 0,location:Y}),Pe(I,M)},reset(){let mt=new Map(j.blockers);mt.set(ut,Ul),Ve({blockers:mt})}});return}return await Qe(ke,Y,{submission:le,pendingError:je,preventScrollReset:_e,replace:M&&M.replace,enableViewTransition:M&&M.unstable_viewTransition,flushSync:ot})}function Xe(){if(Pt(),Ve({revalidation:"loading"}),j.navigation.state!=="submitting"){if(j.navigation.state==="idle"){Qe(j.historyAction,j.location,{startUninterruptedRevalidation:!0});return}Qe(T||j.historyAction,j.navigation.location,{overrideNavigation:j.navigation})}}async function Qe(I,M,z){_&&_.abort(),_=null,T=I,U=(z&&z.startUninterruptedRevalidation)===!0,ep(j.location,j.matches),E=(z&&z.preventScrollReset)===!0,k=(z&&z.enableViewTransition)===!0;let G=l||a,le=z&&z.overrideNavigation,je=as(G,M,c),Ie=(z&&z.flushSync)===!0,Y=Kt(je,G,M.pathname);if(Y.active&&Y.matches&&(je=Y.matches),!je){let{error:it,notFoundMatches:hn,route:Zt}=Xi(M.pathname);Te(M,{matches:hn,loaderData:{},errors:{[Zt.id]:it}},{flushSync:Ie});return}if(j.initialized&&!N&&pG(j.location,M)&&!(z&&z.submission&&Ur(z.submission.formMethod))){Te(M,{matches:je},{flushSync:Ie});return}_=new AbortController;let $e=ha(e.history,M,_.signal,z&&z.submission),ke;if(z&&z.pendingError)ke=[Da(je).route.id,{type:pt.error,error:z.pendingError}];else if(z&&z.submission&&Ur(z.submission.formMethod)){let it=await Z($e,M,z.submission,je,Y.active,{replace:z.replace,flushSync:Ie});if(it.shortCircuited)return;if(it.pendingActionResult){let[hn,Zt]=it.pendingActionResult;if(sr(Zt)&&Wh(Zt.error)&&Zt.error.status===404){_=null,Te(M,{matches:it.matches,loaderData:{},errors:{[hn]:Zt.error}});return}}je=it.matches||je,ke=it.pendingActionResult,le=tm(M,z.submission),Ie=!1,Y.active=!1,$e=ha(e.history,$e.url,$e.signal)}let{shortCircuited:_e,matches:ot,loaderData:ut,errors:mt}=await ue($e,M,je,Y.active,le,z&&z.submission,z&&z.fetcherSubmission,z&&z.replace,z&&z.initialHydration===!0,Ie,ke);_e||(_=null,Te(M,Ft({matches:ot||je},nS(ke),{loaderData:ut,errors:mt})))}async function Z(I,M,z,G,le,je){je===void 0&&(je={}),Pt();let Ie=xG(M,z);if(Ve({navigation:Ie},{flushSync:je.flushSync===!0}),le){let ke=await oo(G,M.pathname,I.signal);if(ke.type==="aborted")return{shortCircuited:!0};if(ke.type==="error"){let{boundaryId:_e,error:ot}=Or(M.pathname,ke);return{matches:ke.partialMatches,pendingActionResult:[_e,{type:pt.error,error:ot}]}}else if(ke.matches)G=ke.matches;else{let{notFoundMatches:_e,error:ot,route:ut}=Xi(M.pathname);return{matches:_e,pendingActionResult:[ut.id,{type:pt.error,error:ot}]}}}let Y,$e=Xl(G,M);if(!$e.route.action&&!$e.route.lazy)Y={type:pt.error,error:An(405,{method:I.method,pathname:M.pathname,routeId:$e.route.id})};else if(Y=(await Be("action",I,[$e],G))[0],I.signal.aborted)return{shortCircuited:!0};if(ms(Y)){let ke;return je&&je.replace!=null?ke=je.replace:ke=Jw(Y.response.headers.get("Location"),new URL(I.url),c)===j.location.pathname+j.location.search,await xe(I,Y,{submission:z,replace:ke}),{shortCircuited:!0}}if(ps(Y))throw An(400,{type:"defer-action"});if(sr(Y)){let ke=Da(G,$e.route.id);return(je&&je.replace)!==!0&&(T=Yt.Push),{matches:G,pendingActionResult:[ke.route.id,Y]}}return{matches:G,pendingActionResult:[$e.route.id,Y]}}async function ue(I,M,z,G,le,je,Ie,Y,$e,ke,_e){let ot=le||tm(M,je),ut=je||Ie||aS(ot),mt=!U&&(!f.v7_partialHydration||!$e);if(G){if(mt){let Wt=Se(_e);Ve(Ft({navigation:ot},Wt!==void 0?{actionData:Wt}:{}),{flushSync:ke})}let We=await oo(z,M.pathname,I.signal);if(We.type==="aborted")return{shortCircuited:!0};if(We.type==="error"){let{boundaryId:Wt,error:or}=Or(M.pathname,We);return{matches:We.partialMatches,loaderData:{},errors:{[Wt]:or}}}else if(We.matches)z=We.matches;else{let{error:Wt,notFoundMatches:or,route:Mt}=Xi(M.pathname);return{matches:or,loaderData:{},errors:{[Mt.id]:Wt}}}}let it=l||a,[hn,Zt]=Kw(e.history,j,z,ut,M,f.v7_partialHydration&&$e===!0,f.v7_skipActionErrorRevalidation,N,F,D,Re,K,V,it,c,_e);if(jn(We=>!(z&&z.some(Wt=>Wt.route.id===We))||hn&&hn.some(Wt=>Wt.route.id===We)),$=++P,hn.length===0&&Zt.length===0){let We=Pu();return Te(M,Ft({matches:z,loaderData:{},errors:_e&&sr(_e[1])?{[_e[0]]:_e[1].error}:null},nS(_e),We?{fetchers:new Map(j.fetchers)}:{}),{flushSync:ke}),{shortCircuited:!0}}if(mt){let We={};if(!G){We.navigation=ot;let Wt=Se(_e);Wt!==void 0&&(We.actionData=Wt)}Zt.length>0&&(We.fetchers=He(Zt)),Ve(We,{flushSync:ke})}Zt.forEach(We=>{R.has(We.key)&&vr(We.key),We.controller&&R.set(We.key,We.controller)});let kl=()=>Zt.forEach(We=>vr(We.key));_&&_.signal.addEventListener("abort",kl);let{loaderResults:ii,fetcherResults:ea}=await Nt(j.matches,z,hn,Zt,I);if(I.signal.aborted)return{shortCircuited:!0};_&&_.signal.removeEventListener("abort",kl),Zt.forEach(We=>R.delete(We.key));let ta=oS([...ii,...ea]);if(ta){if(ta.idx>=hn.length){let We=Zt[ta.idx-hn.length].key;V.add(We)}return await xe(I,ta.result,{replace:Y}),{shortCircuited:!0}}let{loaderData:na,errors:io}=eS(j,z,hn,ii,_e,Zt,ea,ae);ae.forEach((We,Wt)=>{We.subscribe(or=>{(or||We.done)&&ae.delete(Wt)})}),f.v7_partialHydration&&$e&&j.errors&&Object.entries(j.errors).filter(We=>{let[Wt]=We;return!hn.some(or=>or.route.id===Wt)}).forEach(We=>{let[Wt,or]=We;io=Object.assign(io||{},{[Wt]:or})});let _u=Pu(),Du=yr($),Iu=_u||Du||Zt.length>0;return Ft({matches:z,loaderData:na,errors:io},Iu?{fetchers:new Map(j.fetchers)}:{})}function Se(I){if(I&&!sr(I[1]))return{[I[0]]:I[1].data};if(j.actionData)return Object.keys(j.actionData).length===0?null:j.actionData}function He(I){return I.forEach(M=>{let z=j.fetchers.get(M.key),G=Vl(void 0,z?z.data:void 0);j.fetchers.set(M.key,G)}),new Map(j.fetchers)}function ne(I,M,z,G){if(r)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");R.has(I)&&vr(I);let le=(G&&G.unstable_flushSync)===!0,je=l||a,Ie=Ng(j.location,j.matches,c,f.v7_prependBasename,z,f.v7_relativeSplatPath,M,G==null?void 0:G.relative),Y=as(je,Ie,c),$e=Kt(Y,je,Ie);if($e.active&&$e.matches&&(Y=$e.matches),!Y){St(I,M,An(404,{pathname:Ie}),{flushSync:le});return}let{path:ke,submission:_e,error:ot}=Qw(f.v7_normalizeFormMethod,!0,Ie,G);if(ot){St(I,M,ot,{flushSync:le});return}let ut=Xl(Y,ke);if(E=(G&&G.preventScrollReset)===!0,_e&&Ur(_e.formMethod)){pe(I,M,ke,ut,Y,$e.active,le,_e);return}K.set(I,{routeId:M,path:ke}),Q(I,M,ke,ut,Y,$e.active,le,_e)}async function pe(I,M,z,G,le,je,Ie,Y){Pt(),K.delete(I);function $e(Mt){if(!Mt.route.action&&!Mt.route.lazy){let So=An(405,{method:Y.formMethod,pathname:z,routeId:M});return St(I,M,So,{flushSync:Ie}),!0}return!1}if(!je&&$e(G))return;let ke=j.fetchers.get(I);$t(I,bG(Y,ke),{flushSync:Ie});let _e=new AbortController,ot=ha(e.history,z,_e.signal,Y);if(je){let Mt=await oo(le,z,ot.signal);if(Mt.type==="aborted")return;if(Mt.type==="error"){let{error:So}=Or(z,Mt);St(I,M,So,{flushSync:Ie});return}else if(Mt.matches){if(le=Mt.matches,G=Xl(le,z),$e(G))return}else{St(I,M,An(404,{pathname:z}),{flushSync:Ie});return}}R.set(I,_e);let ut=P,it=(await Be("action",ot,[G],le))[0];if(ot.signal.aborted){R.get(I)===_e&&R.delete(I);return}if(f.v7_fetcherPersist&&Re.has(I)){if(ms(it)||sr(it)){$t(I,li(void 0));return}}else{if(ms(it))if(R.delete(I),$>ut){$t(I,li(void 0));return}else return V.add(I),$t(I,Vl(Y)),xe(ot,it,{fetcherSubmission:Y});if(sr(it)){St(I,M,it.error);return}}if(ps(it))throw An(400,{type:"defer-action"});let hn=j.navigation.location||j.location,Zt=ha(e.history,hn,_e.signal),kl=l||a,ii=j.navigation.state!=="idle"?as(kl,j.navigation.location,c):j.matches;Ue(ii,"Didn't find any matches after fetcher action");let ea=++P;L.set(I,ea);let ta=Vl(Y,it.data);j.fetchers.set(I,ta);let[na,io]=Kw(e.history,j,ii,Y,hn,!1,f.v7_skipActionErrorRevalidation,N,F,D,Re,K,V,kl,c,[G.route.id,it]);io.filter(Mt=>Mt.key!==I).forEach(Mt=>{let So=Mt.key,T0=j.fetchers.get(So),L2=Vl(void 0,T0?T0.data:void 0);j.fetchers.set(So,L2),R.has(So)&&vr(So),Mt.controller&&R.set(So,Mt.controller)}),Ve({fetchers:new Map(j.fetchers)});let _u=()=>io.forEach(Mt=>vr(Mt.key));_e.signal.addEventListener("abort",_u);let{loaderResults:Du,fetcherResults:Iu}=await Nt(j.matches,ii,na,io,Zt);if(_e.signal.aborted)return;_e.signal.removeEventListener("abort",_u),L.delete(I),R.delete(I),io.forEach(Mt=>R.delete(Mt.key));let We=oS([...Du,...Iu]);if(We){if(We.idx>=na.length){let Mt=io[We.idx-na.length].key;V.add(Mt)}return xe(Zt,We.result)}let{loaderData:Wt,errors:or}=eS(j,j.matches,na,Du,void 0,io,Iu,ae);if(j.fetchers.has(I)){let Mt=li(it.data);j.fetchers.set(I,Mt)}yr(ea),j.navigation.state==="loading"&&ea>$?(Ue(T,"Expected pending action"),_&&_.abort(),Te(j.navigation.location,{matches:ii,loaderData:Wt,errors:or,fetchers:new Map(j.fetchers)})):(Ve({errors:or,loaderData:tS(j.loaderData,Wt,ii,or),fetchers:new Map(j.fetchers)}),N=!1)}async function Q(I,M,z,G,le,je,Ie,Y){let $e=j.fetchers.get(I);$t(I,Vl(Y,$e?$e.data:void 0),{flushSync:Ie});let ke=new AbortController,_e=ha(e.history,z,ke.signal);if(je){let it=await oo(le,z,_e.signal);if(it.type==="aborted")return;if(it.type==="error"){let{error:hn}=Or(z,it);St(I,M,hn,{flushSync:Ie});return}else if(it.matches)le=it.matches,G=Xl(le,z);else{St(I,M,An(404,{pathname:z}),{flushSync:Ie});return}}R.set(I,ke);let ot=P,mt=(await Be("loader",_e,[G],le))[0];if(ps(mt)&&(mt=await d2(mt,_e.signal,!0)||mt),R.get(I)===ke&&R.delete(I),!_e.signal.aborted){if(Re.has(I)){$t(I,li(void 0));return}if(ms(mt))if($>ot){$t(I,li(void 0));return}else{V.add(I),await xe(_e,mt);return}if(sr(mt)){St(I,M,mt.error);return}Ue(!ps(mt),"Unhandled fetcher deferred data"),$t(I,li(mt.data))}}async function xe(I,M,z){let{submission:G,fetcherSubmission:le,replace:je}=z===void 0?{}:z;M.response.headers.has("X-Remix-Revalidate")&&(N=!0);let Ie=M.response.headers.get("Location");Ue(Ie,"Expected a Location header on the redirect Response"),Ie=Jw(Ie,new URL(I.url),c);let Y=zc(j.location,Ie,{_isRedirect:!0});if(n){let mt=!1;if(M.response.headers.has("X-Remix-Reload-Document"))mt=!0;else if(v0.test(Ie)){const it=e.history.createURL(Ie);mt=it.origin!==t.location.origin||ju(it.pathname,c)==null}if(mt){je?t.location.replace(Ie):t.location.assign(Ie);return}}_=null;let $e=je===!0||M.response.headers.has("X-Remix-Replace")?Yt.Replace:Yt.Push,{formMethod:ke,formAction:_e,formEncType:ot}=j.navigation;!G&&!le&&ke&&_e&&ot&&(G=aS(j.navigation));let ut=G||le;if(eG.has(M.response.status)&&ut&&Ur(ut.formMethod))await Qe($e,Y,{submission:Ft({},ut,{formAction:Ie}),preventScrollReset:E});else{let mt=tm(Y,G);await Qe($e,Y,{overrideNavigation:mt,fetcherSubmission:le,preventScrollReset:E})}}async function Be(I,M,z,G){try{let le=await cG(u,I,M,z,G,i,o);return await Promise.all(le.map((je,Ie)=>{if(gG(je)){let Y=je.result;return{type:pt.redirect,response:fG(Y,M,z[Ie].route.id,G,c,f.v7_relativeSplatPath)}}return dG(je)}))}catch(le){return z.map(()=>({type:pt.error,error:le}))}}async function Nt(I,M,z,G,le){let[je,...Ie]=await Promise.all([z.length?Be("loader",le,z,M):[],...G.map(Y=>{if(Y.matches&&Y.match&&Y.controller){let $e=ha(e.history,Y.path,Y.controller.signal);return Be("loader",$e,[Y.match],Y.matches).then(ke=>ke[0])}else return Promise.resolve({type:pt.error,error:An(404,{pathname:Y.path})})})]);return await Promise.all([sS(I,z,je,je.map(()=>le.signal),!1,j.loaderData),sS(I,G.map(Y=>Y.match),Ie,G.map(Y=>Y.controller?Y.controller.signal:null),!0)]),{loaderResults:je,fetcherResults:Ie}}function Pt(){N=!0,F.push(...jn()),K.forEach((I,M)=>{R.has(M)&&(D.add(M),vr(M))})}function $t(I,M,z){z===void 0&&(z={}),j.fetchers.set(I,M),Ve({fetchers:new Map(j.fetchers)},{flushSync:(z&&z.flushSync)===!0})}function St(I,M,z,G){G===void 0&&(G={});let le=Da(j.matches,M);rr(I),Ve({errors:{[le.route.id]:z},fetchers:new Map(j.fetchers)},{flushSync:(G&&G.flushSync)===!0})}function Sn(I){return f.v7_fetcherPersist&&(ie.set(I,(ie.get(I)||0)+1),Re.has(I)&&Re.delete(I)),j.fetchers.get(I)||tG}function rr(I){let M=j.fetchers.get(I);R.has(I)&&!(M&&M.state==="loading"&&L.has(I))&&vr(I),K.delete(I),L.delete(I),V.delete(I),Re.delete(I),D.delete(I),j.fetchers.delete(I)}function Ki(I){if(f.v7_fetcherPersist){let M=(ie.get(I)||0)-1;M<=0?(ie.delete(I),Re.add(I)):ie.set(I,M)}else rr(I);Ve({fetchers:new Map(j.fetchers)})}function vr(I){let M=R.get(I);Ue(M,"Expected fetch controller: "+I),M.abort(),R.delete(I)}function Tu(I){for(let M of I){let z=Sn(M),G=li(z.data);j.fetchers.set(M,G)}}function Pu(){let I=[],M=!1;for(let z of V){let G=j.fetchers.get(z);Ue(G,"Expected fetcher: "+z),G.state==="loading"&&(V.delete(z),I.push(z),M=!0)}return Tu(I),M}function yr(I){let M=[];for(let[z,G]of L)if(G<I){let le=j.fetchers.get(z);Ue(le,"Expected fetcher: "+z),le.state==="loading"&&(vr(z),L.delete(z),M.push(z))}return Tu(M),M.length>0}function Tl(I,M){let z=j.blockers.get(I)||Ul;return Ee.get(I)!==M&&Ee.set(I,M),z}function ku(I){j.blockers.delete(I),Ee.delete(I)}function Yi(I,M){let z=j.blockers.get(I)||Ul;Ue(z.state==="unblocked"&&M.state==="blocked"||z.state==="blocked"&&M.state==="blocked"||z.state==="blocked"&&M.state==="proceeding"||z.state==="blocked"&&M.state==="unblocked"||z.state==="proceeding"&&M.state==="unblocked","Invalid blocker state transition: "+z.state+" -> "+M.state);let G=new Map(j.blockers);G.set(I,M),Ve({blockers:G})}function Js(I){let{currentLocation:M,nextLocation:z,historyAction:G}=I;if(Ee.size===0)return;Ee.size>1&&il(!1,"A router only supports one blocker at a time");let le=Array.from(Ee.entries()),[je,Ie]=le[le.length-1],Y=j.blockers.get(je);if(!(Y&&Y.state==="proceeding")&&Ie({currentLocation:M,nextLocation:z,historyAction:G}))return je}function Xi(I){let M=An(404,{pathname:I}),z=l||a,{matches:G,route:le}=rS(z);return jn(),{notFoundMatches:G,route:le,error:M}}function Or(I,M){return{boundaryId:Da(M.partialMatches).route.id,error:An(400,{type:"route-discovery",pathname:I,message:M.error!=null&&"message"in M.error?M.error:String(M.error)})}}function jn(I){let M=[];return ae.forEach((z,G)=>{(!I||I(G))&&(z.cancel(),M.push(G),ae.delete(G))}),M}function Jh(I,M,z){if(g=I,S=M,v=z||null,!y&&j.navigation===em){y=!0;let G=Ru(j.location,j.matches);G!=null&&Ve({restoreScrollPosition:G})}return()=>{g=null,S=null,v=null}}function Zh(I,M){return v&&v(I,M.map(G=>Iq(G,j.loaderData)))||I.key}function ep(I,M){if(g&&S){let z=Zh(I,M);g[z]=S()}}function Ru(I,M){if(g){let z=Zh(I,M),G=g[z];if(typeof G=="number")return G}return null}function Kt(I,M,z){if(d)if(I){let G=I[I.length-1].route;if(G.path&&(G.path==="*"||G.path.endsWith("/*")))return{active:!0,matches:_d(M,z,c,!0)}}else return{active:!0,matches:_d(M,z,c,!0)||[]};return{active:!1,matches:null}}async function oo(I,M,z){let G=I,le=G.length>0?G[G.length-1].route:null;for(;;){let je=l==null,Ie=l||a;try{await aG(d,M,G,Ie,i,o,Fe,z)}catch(_e){return{type:"error",error:_e,partialMatches:G}}finally{je&&(a=[...a])}if(z.aborted)return{type:"aborted"};let Y=as(Ie,M,c),$e=!1;if(Y){let _e=Y[Y.length-1].route;if(_e.index)return{type:"success",matches:Y};if(_e.path&&_e.path.length>0)if(_e.path==="*")$e=!0;else return{type:"success",matches:Y}}let ke=_d(Ie,M,c,!0);if(!ke||G.map(_e=>_e.route.id).join("-")===ke.map(_e=>_e.route.id).join("-"))return{type:"success",matches:$e?Y:null};if(G=ke,le=G[G.length-1].route,le.path==="*")return{type:"success",matches:G}}}function Pl(I){i={},l=Bc(I,o,void 0,i)}function Zs(I,M){let z=l==null;l2(I,M,l||a,i,o),z&&(a=[...a],Ve({}))}return C={get basename(){return c},get future(){return f},get state(){return j},get routes(){return a},get window(){return t},initialize:Le,subscribe:Tt,enableScrollRestoration:Jh,navigate:Pe,fetch:ne,revalidate:Xe,createHref:I=>e.history.createHref(I),encodeLocation:I=>e.history.encodeLocation(I),getFetcher:Sn,deleteFetcher:Ki,dispose:nt,getBlocker:Tl,deleteBlocker:ku,patchRoutes:Zs,_internalFetchControllers:R,_internalActiveDeferreds:ae,_internalSetRoutes:Pl},C}function oG(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function Ng(e,t,n,r,o,i,a,l){let c,u;if(a){c=[];for(let f of t)if(c.push(f),f.route.id===a){u=f;break}}else c=t,u=t[t.length-1];let d=o2(o||".",r2(c,i),ju(e.pathname,n)||e.pathname,l==="path");return o==null&&(d.search=e.search,d.hash=e.hash),(o==null||o===""||o===".")&&u&&u.route.index&&!y0(d.search)&&(d.search=d.search?d.search.replace(/^\?/,"?index&"):"?index"),r&&n!=="/"&&(d.pathname=d.pathname==="/"?n:_i([n,d.pathname])),Su(d)}function Qw(e,t,n,r){if(!r||!oG(r))return{path:n};if(r.formMethod&&!yG(r.formMethod))return{path:n,error:An(405,{method:r.formMethod})};let o=()=>({path:n,error:An(400,{type:"invalid-body"})}),i=r.formMethod||"get",a=e?i.toUpperCase():i.toLowerCase(),l=c2(n);if(r.body!==void 0){if(r.formEncType==="text/plain"){if(!Ur(a))return o();let h=typeof r.body=="string"?r.body:r.body instanceof FormData||r.body instanceof URLSearchParams?Array.from(r.body.entries()).reduce((m,g)=>{let[v,S]=g;return""+m+v+"="+S+`
553
+ `},""):String(r.body);return{path:n,submission:{formMethod:a,formAction:l,formEncType:r.formEncType,formData:void 0,json:void 0,text:h}}}else if(r.formEncType==="application/json"){if(!Ur(a))return o();try{let h=typeof r.body=="string"?JSON.parse(r.body):r.body;return{path:n,submission:{formMethod:a,formAction:l,formEncType:r.formEncType,formData:void 0,json:h,text:void 0}}}catch{return o()}}}Ue(typeof FormData=="function","FormData is not available in this environment");let c,u;if(r.formData)c=Mg(r.formData),u=r.formData;else if(r.body instanceof FormData)c=Mg(r.body),u=r.body;else if(r.body instanceof URLSearchParams)c=r.body,u=Zw(c);else if(r.body==null)c=new URLSearchParams,u=new FormData;else try{c=new URLSearchParams(r.body),u=Zw(c)}catch{return o()}let d={formMethod:a,formAction:l,formEncType:r&&r.formEncType||"application/x-www-form-urlencoded",formData:u,json:void 0,text:void 0};if(Ur(d.formMethod))return{path:n,submission:d};let f=ri(n);return t&&f.search&&y0(f.search)&&c.append("index",""),f.search="?"+c,{path:Su(f),submission:d}}function iG(e,t){let n=e;if(t){let r=e.findIndex(o=>o.route.id===t);r>=0&&(n=e.slice(0,r))}return n}function Kw(e,t,n,r,o,i,a,l,c,u,d,f,h,m,g,v){let S=v?sr(v[1])?v[1].error:v[1].data:void 0,y=e.createURL(t.location),w=e.createURL(o),b=v&&sr(v[1])?v[0]:void 0,x=b?iG(n,b):n,C=v?v[1].statusCode:void 0,j=a&&C&&C>=400,T=x.filter((_,k)=>{let{route:A}=_;if(A.lazy)return!0;if(A.loader==null)return!1;if(i)return typeof A.loader!="function"||A.loader.hydrate?!0:t.loaderData[A.id]===void 0&&(!t.errors||t.errors[A.id]===void 0);if(sG(t.loaderData,t.matches[k],_)||c.some(N=>N===_.route.id))return!0;let O=t.matches[k],U=_;return Yw(_,Ft({currentUrl:y,currentParams:O.params,nextUrl:w,nextParams:U.params},r,{actionResult:S,actionStatus:C,defaultShouldRevalidate:j?!1:l||y.pathname+y.search===w.pathname+w.search||y.search!==w.search||a2(O,U)}))}),E=[];return f.forEach((_,k)=>{if(i||!n.some(F=>F.route.id===_.routeId)||d.has(k))return;let A=as(m,_.path,g);if(!A){E.push({key:k,routeId:_.routeId,path:_.path,matches:null,match:null,controller:null});return}let O=t.fetchers.get(k),U=Xl(A,_.path),N=!1;h.has(k)?N=!1:u.has(k)?(u.delete(k),N=!0):O&&O.state!=="idle"&&O.data===void 0?N=l:N=Yw(U,Ft({currentUrl:y,currentParams:t.matches[t.matches.length-1].params,nextUrl:w,nextParams:n[n.length-1].params},r,{actionResult:S,actionStatus:C,defaultShouldRevalidate:j?!1:l})),N&&E.push({key:k,routeId:_.routeId,path:_.path,matches:A,match:U,controller:new AbortController})}),[T,E]}function sG(e,t,n){let r=!t||n.route.id!==t.route.id,o=e[n.route.id]===void 0;return r||o}function a2(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function Yw(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}async function aG(e,t,n,r,o,i,a,l){let c=[t,...n.map(u=>u.route.id)].join("-");try{let u=a.get(c);u||(u=e({path:t,matches:n,patch:(d,f)=>{l.aborted||l2(d,f,r,o,i)}}),a.set(c,u)),u&&mG(u)&&await u}finally{a.delete(c)}}function l2(e,t,n,r,o){if(e){var i;let a=r[e];Ue(a,"No route found to patch children into: routeId = "+e);let l=Bc(t,o,[e,"patch",String(((i=a.children)==null?void 0:i.length)||"0")],r);a.children?a.children.push(...l):a.children=l}else{let a=Bc(t,o,["patch",String(n.length||"0")],r);n.push(...a)}}async function Xw(e,t,n){if(!e.lazy)return;let r=await e.lazy();if(!e.lazy)return;let o=n[e.id];Ue(o,"No route found in manifest");let i={};for(let a in r){let c=o[a]!==void 0&&a!=="hasErrorBoundary";il(!c,'Route "'+o.id+'" has a static property "'+a+'" defined but its lazy function is also returning a value for this property. '+('The lazy route property "'+a+'" will be ignored.')),!c&&!_q.has(a)&&(i[a]=r[a])}Object.assign(o,i),Object.assign(o,Ft({},t(o),{lazy:void 0}))}function lG(e){return Promise.all(e.matches.map(t=>t.resolve()))}async function cG(e,t,n,r,o,i,a,l){let c=r.reduce((f,h)=>f.add(h.route.id),new Set),u=new Set,d=await e({matches:o.map(f=>{let h=c.has(f.route.id);return Ft({},f,{shouldLoad:h,resolve:g=>(u.add(f.route.id),h?uG(t,n,f,i,a,g,l):Promise.resolve({type:pt.data,result:void 0}))})}),request:n,params:o[0].params,context:l});return o.forEach(f=>Ue(u.has(f.route.id),'`match.resolve()` was not called for route id "'+f.route.id+'". You must call `match.resolve()` on every match passed to `dataStrategy` to ensure all routes are properly loaded.')),d.filter((f,h)=>c.has(o[h].route.id))}async function uG(e,t,n,r,o,i,a){let l,c,u=d=>{let f,h=new Promise((v,S)=>f=S);c=()=>f(),t.signal.addEventListener("abort",c);let m=v=>typeof d!="function"?Promise.reject(new Error("You cannot call the handler for a route which defines a boolean "+('"'+e+'" [routeId: '+n.route.id+"]"))):d({request:t,params:n.params,context:a},...v!==void 0?[v]:[]),g;return i?g=i(v=>m(v)):g=(async()=>{try{return{type:"data",result:await m()}}catch(v){return{type:"error",result:v}}})(),Promise.race([g,h])};try{let d=n.route[e];if(n.route.lazy)if(d){let f,[h]=await Promise.all([u(d).catch(m=>{f=m}),Xw(n.route,o,r)]);if(f!==void 0)throw f;l=h}else if(await Xw(n.route,o,r),d=n.route[e],d)l=await u(d);else if(e==="action"){let f=new URL(t.url),h=f.pathname+f.search;throw An(405,{method:t.method,pathname:h,routeId:n.route.id})}else return{type:pt.data,result:void 0};else if(d)l=await u(d);else{let f=new URL(t.url),h=f.pathname+f.search;throw An(404,{pathname:h})}Ue(l.result!==void 0,"You defined "+(e==="action"?"an action":"a loader")+" for route "+('"'+n.route.id+"\" but didn't return anything from your `"+e+"` ")+"function. Please return a value or `null`.")}catch(d){return{type:pt.error,result:d}}finally{c&&t.signal.removeEventListener("abort",c)}return l}async function dG(e){let{result:t,type:n}=e;if(u2(t)){let u;try{let d=t.headers.get("Content-Type");d&&/\bapplication\/json\b/.test(d)?t.body==null?u=null:u=await t.json():u=await t.text()}catch(d){return{type:pt.error,error:d}}return n===pt.error?{type:pt.error,error:new Cf(t.status,t.statusText,u),statusCode:t.status,headers:t.headers}:{type:pt.data,data:u,statusCode:t.status,headers:t.headers}}if(n===pt.error){if(iS(t)){var r;if(t.data instanceof Error){var o;return{type:pt.error,error:t.data,statusCode:(o=t.init)==null?void 0:o.status}}t=new Cf(((r=t.init)==null?void 0:r.status)||500,void 0,t.data)}return{type:pt.error,error:t,statusCode:Wh(t)?t.status:void 0}}if(vG(t)){var i,a;return{type:pt.deferred,deferredData:t,statusCode:(i=t.init)==null?void 0:i.status,headers:((a=t.init)==null?void 0:a.headers)&&new Headers(t.init.headers)}}if(iS(t)){var l,c;return{type:pt.data,data:t.data,statusCode:(l=t.init)==null?void 0:l.status,headers:(c=t.init)!=null&&c.headers?new Headers(t.init.headers):void 0}}return{type:pt.data,data:t}}function fG(e,t,n,r,o,i){let a=e.headers.get("Location");if(Ue(a,"Redirects returned/thrown from loaders/actions must have a Location header"),!v0.test(a)){let l=r.slice(0,r.findIndex(c=>c.route.id===n)+1);a=Ng(new URL(t.url),l,o,!0,a,i),e.headers.set("Location",a)}return e}function Jw(e,t,n){if(v0.test(e)){let r=e,o=r.startsWith("//")?new URL(t.protocol+r):new URL(r),i=ju(o.pathname,n)!=null;if(o.origin===t.origin&&i)return o.pathname+o.search+o.hash}return e}function ha(e,t,n,r){let o=e.createURL(c2(t)).toString(),i={signal:n};if(r&&Ur(r.formMethod)){let{formMethod:a,formEncType:l}=r;i.method=a.toUpperCase(),l==="application/json"?(i.headers=new Headers({"Content-Type":l}),i.body=JSON.stringify(r.json)):l==="text/plain"?i.body=r.text:l==="application/x-www-form-urlencoded"&&r.formData?i.body=Mg(r.formData):i.body=r.formData}return new Request(o,i)}function Mg(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function Zw(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function hG(e,t,n,r,o,i){let a={},l=null,c,u=!1,d={},f=r&&sr(r[1])?r[1].error:void 0;return n.forEach((h,m)=>{let g=t[m].route.id;if(Ue(!ms(h),"Cannot handle redirect results in processLoaderData"),sr(h)){let v=h.error;f!==void 0&&(v=f,f=void 0),l=l||{};{let S=Da(e,g);l[S.route.id]==null&&(l[S.route.id]=v)}a[g]=void 0,u||(u=!0,c=Wh(h.error)?h.error.status:500),h.headers&&(d[g]=h.headers)}else ps(h)?(o.set(g,h.deferredData),a[g]=h.deferredData.data,h.statusCode!=null&&h.statusCode!==200&&!u&&(c=h.statusCode),h.headers&&(d[g]=h.headers)):(a[g]=h.data,h.statusCode&&h.statusCode!==200&&!u&&(c=h.statusCode),h.headers&&(d[g]=h.headers))}),f!==void 0&&r&&(l={[r[0]]:f},a[r[0]]=void 0),{loaderData:a,errors:l,statusCode:c||200,loaderHeaders:d}}function eS(e,t,n,r,o,i,a,l){let{loaderData:c,errors:u}=hG(t,n,r,o,l);for(let d=0;d<i.length;d++){let{key:f,match:h,controller:m}=i[d];Ue(a!==void 0&&a[d]!==void 0,"Did not find corresponding fetcher result");let g=a[d];if(!(m&&m.signal.aborted))if(sr(g)){let v=Da(e.matches,h==null?void 0:h.route.id);u&&u[v.route.id]||(u=Ft({},u,{[v.route.id]:g.error})),e.fetchers.delete(f)}else if(ms(g))Ue(!1,"Unhandled fetcher revalidation redirect");else if(ps(g))Ue(!1,"Unhandled fetcher deferred data");else{let v=li(g.data);e.fetchers.set(f,v)}}return{loaderData:c,errors:u}}function tS(e,t,n,r){let o=Ft({},t);for(let i of n){let a=i.route.id;if(t.hasOwnProperty(a)?t[a]!==void 0&&(o[a]=t[a]):e[a]!==void 0&&i.route.loader&&(o[a]=e[a]),r&&r.hasOwnProperty(a))break}return o}function nS(e){return e?sr(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function Da(e,t){return(t?e.slice(0,e.findIndex(r=>r.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function rS(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function An(e,t){let{pathname:n,routeId:r,method:o,type:i,message:a}=t===void 0?{}:t,l="Unknown Server Error",c="Unknown @remix-run/router error";return e===400?(l="Bad Request",i==="route-discovery"?c='Unable to match URL "'+n+'" - the `unstable_patchRoutesOnMiss()` '+(`function threw the following error:
554
+ `+a):o&&n&&r?c="You made a "+o+' request to "'+n+'" but '+('did not provide a `loader` for route "'+r+'", ')+"so there is no way to handle the request.":i==="defer-action"?c="defer() is not supported in actions":i==="invalid-body"&&(c="Unable to encode submission body")):e===403?(l="Forbidden",c='Route "'+r+'" does not match URL "'+n+'"'):e===404?(l="Not Found",c='No route matches URL "'+n+'"'):e===405&&(l="Method Not Allowed",o&&n&&r?c="You made a "+o.toUpperCase()+' request to "'+n+'" but '+('did not provide an `action` for route "'+r+'", ')+"so there is no way to handle the request.":o&&(c='Invalid request method "'+o.toUpperCase()+'"')),new Cf(e||500,l,new Error(c),!0)}function oS(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(ms(n))return{result:n,idx:t}}}function c2(e){let t=typeof e=="string"?ri(e):e;return Su(Ft({},t,{hash:""}))}function pG(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function mG(e){return typeof e=="object"&&e!=null&&"then"in e}function gG(e){return u2(e.result)&&Zq.has(e.result.status)}function ps(e){return e.type===pt.deferred}function sr(e){return e.type===pt.error}function ms(e){return(e&&e.type)===pt.redirect}function iS(e){return typeof e=="object"&&e!=null&&"type"in e&&"data"in e&&"init"in e&&e.type==="DataWithResponseInit"}function vG(e){let t=e;return t&&typeof t=="object"&&typeof t.data=="object"&&typeof t.subscribe=="function"&&typeof t.cancel=="function"&&typeof t.resolveData=="function"}function u2(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function yG(e){return Jq.has(e.toLowerCase())}function Ur(e){return Yq.has(e.toLowerCase())}async function sS(e,t,n,r,o,i){for(let a=0;a<n.length;a++){let l=n[a],c=t[a];if(!c)continue;let u=e.find(f=>f.route.id===c.route.id),d=u!=null&&!a2(u,c)&&(i&&i[c.route.id])!==void 0;if(ps(l)&&(o||d)){let f=r[a];Ue(f,"Expected an AbortSignal for revalidating fetcher deferred result"),await d2(l,f,o).then(h=>{h&&(n[a]=h||n[a])})}}}async function d2(e,t,n){if(n===void 0&&(n=!1),!await e.deferredData.resolveData(t)){if(n)try{return{type:pt.data,data:e.deferredData.unwrappedData}}catch(o){return{type:pt.error,error:o}}return{type:pt.data,data:e.deferredData.data}}}function y0(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function Xl(e,t){let n=typeof t=="string"?ri(t).search:t.search;if(e[e.length-1].route.index&&y0(n||""))return e[e.length-1];let r=n2(e);return r[r.length-1]}function aS(e){let{formMethod:t,formAction:n,formEncType:r,text:o,formData:i,json:a}=e;if(!(!t||!n||!r)){if(o!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:o};if(i!=null)return{formMethod:t,formAction:n,formEncType:r,formData:i,json:void 0,text:void 0};if(a!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:a,text:void 0}}}function tm(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function xG(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function Vl(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function bG(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function li(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function wG(e,t){try{let n=e.sessionStorage.getItem(s2);if(n){let r=JSON.parse(n);for(let[o,i]of Object.entries(r||{}))i&&Array.isArray(i)&&t.set(o,new Set(i||[]))}}catch{}}function SG(e,t){if(t.size>0){let n={};for(let[r,o]of t)n[r]=[...o];try{e.sessionStorage.setItem(s2,JSON.stringify(n))}catch(r){il(!1,"Failed to save applied view transitions in sessionStorage ("+r+").")}}}/**
555
555
  * React Router v6.26.0
556
556
  *
557
557
  * Copyright (c) Remix Software Inc.
@@ -560,7 +560,7 @@ Error generating stack: `+i.message+`
560
560
  * LICENSE.md file in the root directory of this source tree.
561
561
  *
562
562
  * @license MIT
563
- */function Uc(){return Uc=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},Uc.apply(this,arguments)}const Hh=p.createContext(null),f2=p.createContext(null),qh=p.createContext(null),Gh=p.createContext(null),qi=p.createContext({outlet:null,matches:[],isDataRoute:!1}),h2=p.createContext(null);function Qh(){return p.useContext(Gh)!=null}function oi(){return Qh()||Ue(!1),p.useContext(Gh).location}function p2(e){p.useContext(qh).static||p.useLayoutEffect(e)}function Qt(){let{isDataRoute:e}=p.useContext(qi);return e?MG():SG()}function SG(){Qh()||Ue(!1);let e=p.useContext(Hh),{basename:t,future:n,navigator:r}=p.useContext(qh),{matches:o}=p.useContext(qi),{pathname:i}=oi(),a=JSON.stringify(r2(o,n.v7_relativeSplatPath)),l=p.useRef(!1);return p2(()=>{l.current=!0}),p.useCallback(function(u,d){if(d===void 0&&(d={}),!l.current)return;if(typeof u=="number"){r.go(u);return}let f=o2(u,JSON.parse(a),i,d.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:_i([t,f.pathname])),(d.replace?r.replace:r.push)(f,d.state,d)},[t,r,a,i,e])}const jG=p.createContext(null);function CG(e){let t=p.useContext(qi).outlet;return t&&p.createElement(jG.Provider,{value:e},t)}function ct(){let{matches:e}=p.useContext(qi),t=e[e.length-1];return t?t.params:{}}function EG(e,t){return m2(e,t)}function m2(e,t,n,r){Qh()||Ue(!1);let{navigator:o}=p.useContext(qh),{matches:i}=p.useContext(qi),a=i[i.length-1],l=a?a.params:{};a&&a.pathname;let c=a?a.pathnameBase:"/";a&&a.route;let u=oi(),d;if(t){var f;let S=typeof t=="string"?ri(t):t;c==="/"||(f=S.pathname)!=null&&f.startsWith(c)||Ue(!1),d=S}else d=u;let h=d.pathname||"/",m=h;if(c!=="/"){let S=c.replace(/^\//,"").split("/");m="/"+h.replace(/^\//,"").split("/").slice(S.length).join("/")}let g=as(e,{pathname:m}),v=_G(g&&g.map(S=>Object.assign({},S,{params:Object.assign({},l,S.params),pathname:_i([c,o.encodeLocation?o.encodeLocation(S.pathname).pathname:S.pathname]),pathnameBase:S.pathnameBase==="/"?c:_i([c,o.encodeLocation?o.encodeLocation(S.pathnameBase).pathname:S.pathnameBase])})),i,n,r);return t&&v?p.createElement(Gh.Provider,{value:{location:Uc({pathname:"/",search:"",hash:"",state:null,key:"default"},d),navigationType:Yt.Pop}},v):v}function TG(){let e=NG(),t=Wh(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,o={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return p.createElement(p.Fragment,null,p.createElement("h2",null,"Unexpected Application Error!"),p.createElement("h3",{style:{fontStyle:"italic"}},t),n?p.createElement("pre",{style:o},n):null,null)}const PG=p.createElement(TG,null);class kG extends p.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?p.createElement(qi.Provider,{value:this.props.routeContext},p.createElement(h2.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function RG(e){let{routeContext:t,match:n,children:r}=e,o=p.useContext(Hh);return o&&o.static&&o.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=n.route.id),p.createElement(qi.Provider,{value:t},r)}function _G(e,t,n,r){var o;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var i;if(!n)return null;if(n.errors)e=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,l=(o=n)==null?void 0:o.errors;if(l!=null){let d=a.findIndex(f=>f.route.id&&(l==null?void 0:l[f.route.id])!==void 0);d>=0||Ue(!1),a=a.slice(0,Math.min(a.length,d+1))}let c=!1,u=-1;if(n&&r&&r.v7_partialHydration)for(let d=0;d<a.length;d++){let f=a[d];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(u=d),f.route.id){let{loaderData:h,errors:m}=n,g=f.route.loader&&h[f.route.id]===void 0&&(!m||m[f.route.id]===void 0);if(f.route.lazy||g){c=!0,u>=0?a=a.slice(0,u+1):a=[a[0]];break}}}return a.reduceRight((d,f,h)=>{let m,g=!1,v=null,S=null;n&&(m=l&&f.route.id?l[f.route.id]:void 0,v=f.route.errorElement||PG,c&&(u<0&&h===0?(OG("route-fallback"),g=!0,S=null):u===h&&(g=!0,S=f.route.hydrateFallbackElement||null)));let y=t.concat(a.slice(0,h+1)),w=()=>{let b;return m?b=v:g?b=S:f.route.Component?b=p.createElement(f.route.Component,null):f.route.element?b=f.route.element:b=d,p.createElement(RG,{match:f,routeContext:{outlet:d,matches:y,isDataRoute:n!=null},children:b})};return n&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?p.createElement(kG,{location:n.location,revalidation:n.revalidation,component:v,error:m,children:w(),routeContext:{outlet:null,matches:y,isDataRoute:!0}}):w()},null)}var g2=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(g2||{}),Ef=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(Ef||{});function DG(e){let t=p.useContext(Hh);return t||Ue(!1),t}function IG(e){let t=p.useContext(f2);return t||Ue(!1),t}function AG(e){let t=p.useContext(qi);return t||Ue(!1),t}function v2(e){let t=AG(),n=t.matches[t.matches.length-1];return n.route.id||Ue(!1),n.route.id}function NG(){var e;let t=p.useContext(h2),n=IG(Ef.UseRouteError),r=v2(Ef.UseRouteError);return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function MG(){let{router:e}=DG(g2.UseNavigateStable),t=v2(Ef.UseNavigateStable),n=p.useRef(!1);return p2(()=>{n.current=!0}),p.useCallback(function(o,i){i===void 0&&(i={}),n.current&&(typeof o=="number"?e.navigate(o):e.navigate(o,Uc({fromRouteId:t},i)))},[e,t])}const lS={};function OG(e,t,n){lS[e]||(lS[e]=!0)}function x0(e){return CG(e.context)}function we(e){Ue(!1)}function LG(e){let{basename:t="/",children:n=null,location:r,navigationType:o=Yt.Pop,navigator:i,static:a=!1,future:l}=e;Qh()&&Ue(!1);let c=t.replace(/^\/*/,"/"),u=p.useMemo(()=>({basename:c,navigator:i,static:a,future:Uc({v7_relativeSplatPath:!1},l)}),[c,l,i,a]);typeof r=="string"&&(r=ri(r));let{pathname:d="/",search:f="",hash:h="",state:m=null,key:g="default"}=r,v=p.useMemo(()=>{let S=ju(d,c);return S==null?null:{location:{pathname:S,search:f,hash:h,state:m,key:g},navigationType:o}},[c,d,f,h,m,g,o]);return v==null?null:p.createElement(qh.Provider,{value:u},p.createElement(Gh.Provider,{children:n,value:v}))}function $G(e){let{children:t,location:n}=e;return EG(Og(t),n)}new Promise(()=>{});function Og(e,t){t===void 0&&(t=[]);let n=[];return p.Children.forEach(e,(r,o)=>{if(!p.isValidElement(r))return;let i=[...t,o];if(r.type===p.Fragment){n.push.apply(n,Og(r.props.children,i));return}r.type!==we&&Ue(!1),!r.props.index||!r.props.children||Ue(!1);let a={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=Og(r.props.children,i)),n.push(a)}),n}function FG(e){let t={hasErrorBoundary:e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&Object.assign(t,{element:p.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:p.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:p.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}/**
563
+ */function Uc(){return Uc=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},Uc.apply(this,arguments)}const Hh=p.createContext(null),f2=p.createContext(null),qh=p.createContext(null),Gh=p.createContext(null),qi=p.createContext({outlet:null,matches:[],isDataRoute:!1}),h2=p.createContext(null);function Qh(){return p.useContext(Gh)!=null}function oi(){return Qh()||Ue(!1),p.useContext(Gh).location}function p2(e){p.useContext(qh).static||p.useLayoutEffect(e)}function Qt(){let{isDataRoute:e}=p.useContext(qi);return e?OG():jG()}function jG(){Qh()||Ue(!1);let e=p.useContext(Hh),{basename:t,future:n,navigator:r}=p.useContext(qh),{matches:o}=p.useContext(qi),{pathname:i}=oi(),a=JSON.stringify(r2(o,n.v7_relativeSplatPath)),l=p.useRef(!1);return p2(()=>{l.current=!0}),p.useCallback(function(u,d){if(d===void 0&&(d={}),!l.current)return;if(typeof u=="number"){r.go(u);return}let f=o2(u,JSON.parse(a),i,d.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:_i([t,f.pathname])),(d.replace?r.replace:r.push)(f,d.state,d)},[t,r,a,i,e])}const CG=p.createContext(null);function EG(e){let t=p.useContext(qi).outlet;return t&&p.createElement(CG.Provider,{value:e},t)}function ct(){let{matches:e}=p.useContext(qi),t=e[e.length-1];return t?t.params:{}}function TG(e,t){return m2(e,t)}function m2(e,t,n,r){Qh()||Ue(!1);let{navigator:o}=p.useContext(qh),{matches:i}=p.useContext(qi),a=i[i.length-1],l=a?a.params:{};a&&a.pathname;let c=a?a.pathnameBase:"/";a&&a.route;let u=oi(),d;if(t){var f;let S=typeof t=="string"?ri(t):t;c==="/"||(f=S.pathname)!=null&&f.startsWith(c)||Ue(!1),d=S}else d=u;let h=d.pathname||"/",m=h;if(c!=="/"){let S=c.replace(/^\//,"").split("/");m="/"+h.replace(/^\//,"").split("/").slice(S.length).join("/")}let g=as(e,{pathname:m}),v=DG(g&&g.map(S=>Object.assign({},S,{params:Object.assign({},l,S.params),pathname:_i([c,o.encodeLocation?o.encodeLocation(S.pathname).pathname:S.pathname]),pathnameBase:S.pathnameBase==="/"?c:_i([c,o.encodeLocation?o.encodeLocation(S.pathnameBase).pathname:S.pathnameBase])})),i,n,r);return t&&v?p.createElement(Gh.Provider,{value:{location:Uc({pathname:"/",search:"",hash:"",state:null,key:"default"},d),navigationType:Yt.Pop}},v):v}function PG(){let e=MG(),t=Wh(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,o={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return p.createElement(p.Fragment,null,p.createElement("h2",null,"Unexpected Application Error!"),p.createElement("h3",{style:{fontStyle:"italic"}},t),n?p.createElement("pre",{style:o},n):null,null)}const kG=p.createElement(PG,null);class RG extends p.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?p.createElement(qi.Provider,{value:this.props.routeContext},p.createElement(h2.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function _G(e){let{routeContext:t,match:n,children:r}=e,o=p.useContext(Hh);return o&&o.static&&o.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=n.route.id),p.createElement(qi.Provider,{value:t},r)}function DG(e,t,n,r){var o;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var i;if(!n)return null;if(n.errors)e=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,l=(o=n)==null?void 0:o.errors;if(l!=null){let d=a.findIndex(f=>f.route.id&&(l==null?void 0:l[f.route.id])!==void 0);d>=0||Ue(!1),a=a.slice(0,Math.min(a.length,d+1))}let c=!1,u=-1;if(n&&r&&r.v7_partialHydration)for(let d=0;d<a.length;d++){let f=a[d];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(u=d),f.route.id){let{loaderData:h,errors:m}=n,g=f.route.loader&&h[f.route.id]===void 0&&(!m||m[f.route.id]===void 0);if(f.route.lazy||g){c=!0,u>=0?a=a.slice(0,u+1):a=[a[0]];break}}}return a.reduceRight((d,f,h)=>{let m,g=!1,v=null,S=null;n&&(m=l&&f.route.id?l[f.route.id]:void 0,v=f.route.errorElement||kG,c&&(u<0&&h===0?(LG("route-fallback"),g=!0,S=null):u===h&&(g=!0,S=f.route.hydrateFallbackElement||null)));let y=t.concat(a.slice(0,h+1)),w=()=>{let b;return m?b=v:g?b=S:f.route.Component?b=p.createElement(f.route.Component,null):f.route.element?b=f.route.element:b=d,p.createElement(_G,{match:f,routeContext:{outlet:d,matches:y,isDataRoute:n!=null},children:b})};return n&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?p.createElement(RG,{location:n.location,revalidation:n.revalidation,component:v,error:m,children:w(),routeContext:{outlet:null,matches:y,isDataRoute:!0}}):w()},null)}var g2=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(g2||{}),Ef=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(Ef||{});function IG(e){let t=p.useContext(Hh);return t||Ue(!1),t}function AG(e){let t=p.useContext(f2);return t||Ue(!1),t}function NG(e){let t=p.useContext(qi);return t||Ue(!1),t}function v2(e){let t=NG(),n=t.matches[t.matches.length-1];return n.route.id||Ue(!1),n.route.id}function MG(){var e;let t=p.useContext(h2),n=AG(Ef.UseRouteError),r=v2(Ef.UseRouteError);return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function OG(){let{router:e}=IG(g2.UseNavigateStable),t=v2(Ef.UseNavigateStable),n=p.useRef(!1);return p2(()=>{n.current=!0}),p.useCallback(function(o,i){i===void 0&&(i={}),n.current&&(typeof o=="number"?e.navigate(o):e.navigate(o,Uc({fromRouteId:t},i)))},[e,t])}const lS={};function LG(e,t,n){lS[e]||(lS[e]=!0)}function x0(e){return EG(e.context)}function we(e){Ue(!1)}function $G(e){let{basename:t="/",children:n=null,location:r,navigationType:o=Yt.Pop,navigator:i,static:a=!1,future:l}=e;Qh()&&Ue(!1);let c=t.replace(/^\/*/,"/"),u=p.useMemo(()=>({basename:c,navigator:i,static:a,future:Uc({v7_relativeSplatPath:!1},l)}),[c,l,i,a]);typeof r=="string"&&(r=ri(r));let{pathname:d="/",search:f="",hash:h="",state:m=null,key:g="default"}=r,v=p.useMemo(()=>{let S=ju(d,c);return S==null?null:{location:{pathname:S,search:f,hash:h,state:m,key:g},navigationType:o}},[c,d,f,h,m,g,o]);return v==null?null:p.createElement(qh.Provider,{value:u},p.createElement(Gh.Provider,{children:n,value:v}))}function FG(e){let{children:t,location:n}=e;return TG(Og(t),n)}new Promise(()=>{});function Og(e,t){t===void 0&&(t=[]);let n=[];return p.Children.forEach(e,(r,o)=>{if(!p.isValidElement(r))return;let i=[...t,o];if(r.type===p.Fragment){n.push.apply(n,Og(r.props.children,i));return}r.type!==we&&Ue(!1),!r.props.index||!r.props.children||Ue(!1);let a={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=Og(r.props.children,i)),n.push(a)}),n}function zG(e){let t={hasErrorBoundary:e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&Object.assign(t,{element:p.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:p.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:p.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}/**
564
564
  * React Router DOM v6.26.0
565
565
  *
566
566
  * Copyright (c) Remix Software Inc.
@@ -569,7 +569,7 @@ Error generating stack: `+i.message+`
569
569
  * LICENSE.md file in the root directory of this source tree.
570
570
  *
571
571
  * @license MIT
572
- */function Tf(){return Tf=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},Tf.apply(this,arguments)}function Lg(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 zG(e,t){let n=Lg(e);return t&&t.forEach((r,o)=>{n.has(o)||t.getAll(o).forEach(i=>{n.append(o,i)})}),n}const BG="6";try{window.__reactRouterVersion=BG}catch{}function UG(e,t){return nG({basename:void 0,future:Tf({},void 0,{v7_prependBasename:!0}),history:Tq({window:void 0}),hydrationData:VG(),routes:e,mapRouteProperties:FG,unstable_dataStrategy:void 0,unstable_patchRoutesOnMiss:void 0,window:void 0}).initialize()}function VG(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=Tf({},t,{errors:WG(t.errors)})),t}function WG(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 Cf(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 HG=p.createContext({isTransitioning:!1}),qG=p.createContext(new Map),GG="startTransition",cS=zS[GG],QG="flushSync",uS=DN[QG];function KG(e){cS?cS(e):e()}function Wl(e){uS?uS(e):e()}class YG{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 XG(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:y}=r||{},w=p.useCallback(E=>{y?KG(E):E()},[y]),b=p.useCallback((E,_)=>{let{deletedFetchers:k,unstable_flushSync:A,unstable_viewTransitionOpts:O}=_;k.forEach(N=>S.current.delete(N)),E.fetchers.forEach((N,F)=>{N.data!==void 0&&S.current.set(F,N.data)});let U=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!O||U){A?Wl(()=>i(E)):w(()=>i(E));return}if(A){Wl(()=>{h&&(d&&d.resolve(),h.skipTransition()),u({isTransitioning:!0,flushSync:!0,currentLocation:O.currentLocation,nextLocation:O.nextLocation})});let N=n.window.document.startViewTransition(()=>{Wl(()=>i(E))});N.finished.finally(()=>{Wl(()=>{f(void 0),m(void 0),l(void 0),u({isTransitioning:!1})})}),Wl(()=>m(N));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,w]);p.useLayoutEffect(()=>n.subscribe(b),[n,b]),p.useEffect(()=>{c.isTransitioning&&!c.flushSync&&f(new YG)},[c]),p.useEffect(()=>{if(d&&a&&n.window){let E=a,_=d.promise,k=n.window.document.startViewTransition(async()=>{w(()=>i(E)),await _});k.finished.finally(()=>{f(void 0),m(void 0),l(void 0),u({isTransitioning:!1})}),m(k)}},[w,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 x=p.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:E=>n.navigate(E),push:(E,_,k)=>n.navigate(E,{state:_,preventScrollReset:k==null?void 0:k.preventScrollReset}),replace:(E,_,k)=>n.navigate(E,{replace:!0,state:_,preventScrollReset:k==null?void 0:k.preventScrollReset})}),[n]),C=n.basename||"/",j=p.useMemo(()=>({router:n,navigator:x,static:!1,basename:C}),[n,x,C]),T=p.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return p.createElement(p.Fragment,null,p.createElement(Hh.Provider,{value:j},p.createElement(f2.Provider,{value:o},p.createElement(qG.Provider,{value:S.current},p.createElement(HG.Provider,{value:c},p.createElement(LG,{basename:C,location:o.location,navigationType:o.historyAction,navigator:x,future:T},o.initialized||n.future.v7_partialHydration?p.createElement(JG,{routes:n.routes,future:n.future,state:o}):t))))),null)}const JG=p.memo(ZG);function ZG(e){let{routes:t,future:n,state:r}=e;return m2(t,void 0,r,n)}var dS;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(dS||(dS={}));var fS;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(fS||(fS={}));function b0(e){let t=p.useRef(Lg(e)),n=p.useRef(!1),r=oi(),o=p.useMemo(()=>zG(r.search,n.current?null:t.current),[r.search]),i=Qt(),a=p.useCallback((l,c)=>{const u=Lg(typeof l=="function"?l(o):l);n.current=!0,i("?"+u,c)},[i,o]);return[o,a]}const eQ=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 Cu(e,t){const n=tQ(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 tQ(e){const{name:t}=e;if(t&&t.lastIndexOf(".")!==-1&&!e.type){const r=t.split(".").pop().toLowerCase(),o=eQ.get(r);o&&Object.defineProperty(e,"type",{value:o,writable:!1,configurable:!1,enumerable:!0})}return e}var El=(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 nQ=[".DS_Store","Thumbs.db"];function rQ(e){return El(this,null,function*(){return Pf(e)&&oQ(e.dataTransfer)?lQ(e.dataTransfer,e.type):iQ(e)?sQ(e):Array.isArray(e)&&e.every(t=>"getFile"in t&&typeof t.getFile=="function")?aQ(e):[]})}function oQ(e){return Pf(e)}function iQ(e){return Pf(e)&&Pf(e.target)}function Pf(e){return typeof e=="object"&&e!==null}function sQ(e){return $g(e.target.files).map(t=>Cu(t))}function aQ(e){return El(this,null,function*(){return(yield Promise.all(e.map(n=>n.getFile()))).map(n=>Cu(n))})}function lQ(e,t){return El(this,null,function*(){if(e.items){const n=$g(e.items).filter(o=>o.kind==="file");if(t!=="drop")return n;const r=yield Promise.all(n.map(cQ));return hS(y2(r))}return hS($g(e.files).map(n=>Cu(n)))})}function hS(e){return e.filter(t=>nQ.indexOf(t.name)===-1)}function $g(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 cQ(e){if(typeof e.webkitGetAsEntry!="function")return pS(e);const t=e.webkitGetAsEntry();return t&&t.isDirectory?x2(t):pS(e)}function y2(e){return e.reduce((t,n)=>[...t,...Array.isArray(n)?y2(n):[n]],[])}function pS(e){const t=e.getAsFile();if(!t)return Promise.reject(`${e} is not a File`);const n=Cu(t);return Promise.resolve(n)}function uQ(e){return El(this,null,function*(){return e.isDirectory?x2(e):dQ(e)})}function x2(e){const t=e.createReader();return new Promise((n,r)=>{const o=[];function i(){t.readEntries(a=>El(this,null,function*(){if(a.length){const l=Promise.all(a.map(uQ));o.push(l),i()}else try{const l=yield Promise.all(o);n(l)}catch(l){r(l)}}),a=>{r(a)})}i()})}function dQ(e){return El(this,null,function*(){return new Promise((t,n)=>{e.file(r=>{const o=Cu(r,e.fullPath);t(o)},r=>{n(r)})})})}function fQ(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 hQ=Object.defineProperty,pQ=Object.defineProperties,mQ=Object.getOwnPropertyDescriptors,mS=Object.getOwnPropertySymbols,gQ=Object.prototype.hasOwnProperty,vQ=Object.prototype.propertyIsEnumerable,gS=(e,t,n)=>t in e?hQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,yQ=(e,t)=>{for(var n in t||(t={}))gQ.call(t,n)&&gS(e,n,t[n]);if(mS)for(var n of mS(t))vQ.call(t,n)&&gS(e,n,t[n]);return e},xQ=(e,t)=>pQ(e,mQ(t));const bQ="file-invalid-type",wQ="file-too-large",SQ="file-too-small",jQ="too-many-files",CQ=e=>{e=Array.isArray(e)&&e.length===1?e[0]:e;const t=Array.isArray(e)?`one of ${e.join(", ")}`:e;return{code:bQ,message:`File type must be ${t}`}},vS=e=>({code:wQ,message:`File is larger than ${e} ${e===1?"byte":"bytes"}`}),yS=e=>({code:SQ,message:`File is smaller than ${e} ${e===1?"byte":"bytes"}`}),EQ={code:jQ,message:"Too many files"};function b2(e,t){const n=e.type==="application/x-moz-file"||fQ(e,t);return[n,n?null:CQ(t)]}function w2(e,t,n){if(ls(e.size))if(ls(t)&&ls(n)){if(e.size>n)return[!1,vS(n)];if(e.size<t)return[!1,yS(t)]}else{if(ls(t)&&e.size<t)return[!1,yS(t)];if(ls(n)&&e.size>n)return[!1,vS(n)]}return[!0,null]}function ls(e){return e!=null}function TQ({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]=b2(l,t),[u]=w2(l,n,r),d=a?a(l):null;return c&&u&&!d})}function kf(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function cd(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 xS(e){e.preventDefault()}function PQ(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function kQ(e){return e.indexOf("Edge/")!==-1}function RQ(e=window.navigator.userAgent){return PQ(e)||kQ(e)}function lo(...e){return(t,...n)=>e.some(r=>(!kf(t)&&r&&r(t,...n),kf(t)))}function _Q(){return"showOpenFilePicker"in window}function DQ(e){return ls(e)?[{description:"Files",accept:Object.entries(e).filter(([n,r])=>{let o=!0;return S2(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(j2))&&(console.warn(`Skipped "${n}" because an invalid file extension was provided.`),o=!1),o}).reduce((n,[r,o])=>xQ(yQ({},n),{[r]:o}),{})}]:e}function IQ(e){if(ls(e))return Object.entries(e).reduce((t,[n,r])=>[...t,n,...r],[]).filter(t=>S2(t)||j2(t)).join(",")}function AQ(e){return e instanceof DOMException&&(e.name==="AbortError"||e.code===e.ABORT_ERR)}function NQ(e){return e instanceof DOMException&&(e.name==="SecurityError"||e.code===e.SECURITY_ERR)}function S2(e){return e==="audio/*"||e==="video/*"||e==="image/*"||e==="text/*"||/\w+\/[-+.\w]+/g.test(e)}function j2(e){return/^.*\.[\w]+$/.test(e)}var MQ=Object.defineProperty,OQ=Object.defineProperties,LQ=Object.getOwnPropertyDescriptors,Rf=Object.getOwnPropertySymbols,C2=Object.prototype.hasOwnProperty,E2=Object.prototype.propertyIsEnumerable,bS=(e,t,n)=>t in e?MQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Mn=(e,t)=>{for(var n in t||(t={}))C2.call(t,n)&&bS(e,n,t[n]);if(Rf)for(var n of Rf(t))E2.call(t,n)&&bS(e,n,t[n]);return e},pi=(e,t)=>OQ(e,LQ(t)),_f=(e,t)=>{var n={};for(var r in e)C2.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Rf)for(var r of Rf(e))t.indexOf(r)<0&&E2.call(e,r)&&(n[r]=e[r]);return n};const w0=p.forwardRef((e,t)=>{var n=e,{children:r}=n,o=_f(n,["children"]);const i=P2(o),{open:a}=i,l=_f(i,["open"]);return p.useImperativeHandle(t,()=>({open:a}),[a]),un.createElement(p.Fragment,null,r(pi(Mn({},l),{open:a})))});w0.displayName="Dropzone";const T2={disabled:!1,getFilesFromEvent:rQ,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};w0.defaultProps=T2;w0.propTypes={children:gt.func,accept:gt.objectOf(gt.arrayOf(gt.string)),multiple:gt.bool,preventDropOnDocument:gt.bool,noClick:gt.bool,noKeyboard:gt.bool,noDrag:gt.bool,noDragEventsBubbling:gt.bool,minSize:gt.number,maxSize:gt.number,maxFiles:gt.number,disabled:gt.bool,getFilesFromEvent:gt.func,onFileDialogCancel:gt.func,onFileDialogOpen:gt.func,useFsAccessApi:gt.bool,autoFocus:gt.bool,onDragEnter:gt.func,onDragLeave:gt.func,onDragOver:gt.func,onDrop:gt.func,onDropAccepted:gt.func,onDropRejected:gt.func,onError:gt.func,validator:gt.func};const Fg={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function P2(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:y,preventDropOnDocument:w,noClick:b,noKeyboard:x,noDrag:C,noDragEventsBubbling:j,onError:T,validator:E}=Mn(Mn({},T2),e),_=p.useMemo(()=>IQ(t),[t]),k=p.useMemo(()=>DQ(t),[t]),A=p.useMemo(()=>typeof v=="function"?v:wS,[v]),O=p.useMemo(()=>typeof g=="function"?g:wS,[g]),U=p.useRef(null),N=p.useRef(null),[F,D]=p.useReducer($Q,Fg),{isFocused:R,isFileDialogActive:P}=F,$=p.useRef(typeof window<"u"&&window.isSecureContext&&S&&_Q()),L=()=>{!$.current&&P&&setTimeout(()=>{if(N.current){const{files:ne}=N.current;ne.length||(D({type:"closeDialog"}),O())}},300)};p.useEffect(()=>(window.addEventListener("focus",L,!1),()=>{window.removeEventListener("focus",L,!1)}),[N,P,O,$]);const V=p.useRef([]),K=ne=>{U.current&&U.current.contains(ne.target)||(ne.preventDefault(),V.current=[])};p.useEffect(()=>(w&&(document.addEventListener("dragover",xS,!1),document.addEventListener("drop",K,!1)),()=>{w&&(document.removeEventListener("dragover",xS),document.removeEventListener("drop",K))}),[U,w]),p.useEffect(()=>(!n&&y&&U.current&&U.current.focus(),()=>{}),[U,y,n]);const ie=p.useCallback(ne=>{T?T(ne):console.error(ne)},[T]),Re=p.useCallback(ne=>{ne.preventDefault(),ne.persist(),Z(ne),V.current=[...V.current,ne.target],cd(ne)&&Promise.resolve(r(ne)).then(pe=>{if(kf(ne)&&!j)return;const Q=pe.length,xe=Q>0&&TQ({files:pe,accept:_,minSize:i,maxSize:o,multiple:a,maxFiles:l,validator:E}),Be=Q>0&&!xe;D({isDragAccept:xe,isDragReject:Be,isDragActive:!0,type:"setDraggedFiles"}),c&&c(ne)}).catch(pe=>ie(pe))},[r,c,ie,j,_,i,o,a,l,E]),ae=p.useCallback(ne=>{ne.preventDefault(),ne.persist(),Z(ne);const pe=cd(ne);if(pe&&ne.dataTransfer)try{ne.dataTransfer.dropEffect="copy"}catch{}return pe&&d&&d(ne),!1},[d,j]),Ee=p.useCallback(ne=>{ne.preventDefault(),ne.persist(),Z(ne);const pe=V.current.filter(xe=>U.current&&U.current.contains(xe)),Q=pe.indexOf(ne.target);Q!==-1&&pe.splice(Q,1),V.current=pe,!(pe.length>0)&&(D({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),cd(ne)&&u&&u(ne))},[U,u,j]),Fe=p.useCallback((ne,pe)=>{const Q=[],xe=[];ne.forEach(Be=>{const[Nt,Pt]=b2(Be,_),[$t,St]=w2(Be,i,o),Sn=E?E(Be):null;if(Nt&&$t&&!Sn)Q.push(Be);else{let rr=[Pt,St];Sn&&(rr=rr.concat(Sn)),xe.push({file:Be,errors:rr.filter(Ki=>Ki)})}}),(!a&&Q.length>1||a&&l>=1&&Q.length>l)&&(Q.forEach(Be=>{xe.push({file:Be,errors:[EQ]})}),Q.splice(0)),D({acceptedFiles:Q,fileRejections:xe,type:"setFiles"}),f&&f(Q,xe,pe),xe.length>0&&m&&m(xe,pe),Q.length>0&&h&&h(Q,pe)},[D,a,_,i,o,l,f,h,m,E]),me=p.useCallback(ne=>{ne.preventDefault(),ne.persist(),Z(ne),V.current=[],cd(ne)&&Promise.resolve(r(ne)).then(pe=>{kf(ne)&&!j||Fe(pe,ne)}).catch(pe=>ie(pe)),D({type:"reset"})},[r,Fe,ie,j]),Le=p.useCallback(()=>{if($.current){D({type:"openDialog"}),A();const ne={multiple:a,types:k};window.showOpenFilePicker(ne).then(pe=>r(pe)).then(pe=>{Fe(pe,null),D({type:"closeDialog"})}).catch(pe=>{AQ(pe)?(O(pe),D({type:"closeDialog"})):NQ(pe)?($.current=!1,N.current?(N.current.value=null,N.current.click()):ie(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."))):ie(pe)});return}N.current&&(D({type:"openDialog"}),A(),N.current.value=null,N.current.click())},[D,A,O,S,Fe,ie,k,a]),nt=p.useCallback(ne=>{!U.current||!U.current.isEqualNode(ne.target)||(ne.key===" "||ne.key==="Enter"||ne.keyCode===32||ne.keyCode===13)&&(ne.preventDefault(),Le())},[U,Le]),Tt=p.useCallback(()=>{D({type:"focus"})},[]),Ve=p.useCallback(()=>{D({type:"blur"})},[]),Te=p.useCallback(()=>{b||(RQ()?setTimeout(Le,0):Le())},[b,Le]),Pe=ne=>n?null:ne,Xe=ne=>x?null:Pe(ne),Qe=ne=>C?null:Pe(ne),Z=ne=>{j&&ne.stopPropagation()},ue=p.useMemo(()=>(ne={})=>{var pe=ne,{refKey:Q="ref",role:xe,onKeyDown:Be,onFocus:Nt,onBlur:Pt,onClick:$t,onDragEnter:St,onDragOver:Sn,onDragLeave:rr,onDrop:Ki}=pe,vr=_f(pe,["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"]);return Mn(Mn({onKeyDown:Xe(lo(Be,nt)),onFocus:Xe(lo(Nt,Tt)),onBlur:Xe(lo(Pt,Ve)),onClick:Pe(lo($t,Te)),onDragEnter:Qe(lo(St,Re)),onDragOver:Qe(lo(Sn,ae)),onDragLeave:Qe(lo(rr,Ee)),onDrop:Qe(lo(Ki,me)),role:typeof xe=="string"&&xe!==""?xe:"presentation",[Q]:U},!n&&!x?{tabIndex:0}:{}),vr)},[U,nt,Tt,Ve,Te,Re,ae,Ee,me,x,C,n]),Se=p.useCallback(ne=>{ne.stopPropagation()},[]),He=p.useMemo(()=>(ne={})=>{var pe=ne,{refKey:Q="ref",onChange:xe,onClick:Be}=pe,Nt=_f(pe,["refKey","onChange","onClick"]);const Pt={accept:_,multiple:a,type:"file",style:{display:"none"},onChange:Pe(lo(xe,me)),onClick:Pe(lo(Be,Se)),tabIndex:-1,[Q]:N};return Mn(Mn({},Pt),Nt)},[N,t,a,me,n]);return pi(Mn({},F),{isFocused:R&&!n,getRootProps:ue,getInputProps:He,rootRef:U,inputRef:N,open:Pe(Le)})}function $Q(e,t){switch(t.type){case"focus":return pi(Mn({},e),{isFocused:!0});case"blur":return pi(Mn({},e),{isFocused:!1});case"openDialog":return pi(Mn({},Fg),{isFileDialogActive:!0});case"closeDialog":return pi(Mn({},e),{isFileDialogActive:!1});case"setDraggedFiles":return pi(Mn({},e),{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return pi(Mn({},e),{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return Mn({},Fg);default:return e}}function wS(){}const[FQ,zQ]=Bn("Dropzone component was not found in tree");function S0(e){const t=n=>{const{children:r,...o}=W(`Dropzone${L0(e)}`,{},n),i=zQ(),a=qo(r)?r:s.jsx("span",{children:r});return i[e]?p.cloneElement(a,o):null};return t.displayName=`@mantine/dropzone/${L0(e)}`,t}const BQ=S0("accept"),UQ=S0("reject"),VQ=S0("idle");var Vc={root:"m_d46a4834",inner:"m_b85f7144",fullScreen:"m_96f6e9ad",dropzone:"m_7946116d"};const WQ={loading:!1,multiple:!0,maxSize:1/0,autoFocus:!1,activateOnClick:!0,activateOnDrag:!0,dragEventsBubbling:!0,activateOnKeyboard:!0,useFsAccessApi:!0,variant:"light",rejectColor:"red"},HQ=(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":lt(t),"--dropzone-accept-color":i.color,"--dropzone-accept-bg":i.background,"--dropzone-reject-color":a.color,"--dropzone-reject-bg":a.background}}},Gi=X((e,t)=>{const n=W("Dropzone",WQ,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:y,onReject:w,openRef:b,name:x,maxFiles:C,autoFocus:j,activateOnClick:T,activateOnDrag:E,dragEventsBubbling:_,activateOnKeyboard:k,onDragEnter:A,onDragLeave:O,onDragOver:U,onFileDialogCancel:N,onFileDialogOpen:F,preventDropOnDocument:D,useFsAccessApi:R,getFilesFromEvent:P,validator:$,rejectColor:L,acceptColor:V,enablePointerEvents:K,loaderProps:ie,inputProps:Re,mod:ae,...Ee}=n,Fe=ce({name:"Dropzone",classes:Vc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:HQ}),{getRootProps:me,getInputProps:Le,isDragAccept:nt,isDragReject:Tt,open:Ve}=P2({onDrop:S,onDropAccepted:y,onDropRejected:w,disabled:d||f,accept:Array.isArray(g)?g.reduce((Pe,Xe)=>({...Pe,[Xe]:[]}),{}):g,multiple:h,maxSize:m,maxFiles:C,autoFocus:j,noClick:!T,noDrag:!E,noDragEventsBubbling:!_,noKeyboard:!k,onDragEnter:A,onDragLeave:O,onDragOver:U,onFileDialogCancel:N,onFileDialogOpen:F,preventDropOnDocument:D,useFsAccessApi:R,validator:$,...P?{getFilesFromEvent:P}:null});Mf(b,Ve);const Te=!nt&&!Tt;return s.jsx(FQ,{value:{accept:nt,reject:Tt,idle:Te},children:s.jsxs(q,{...me(),...Fe("root",{focusable:!0}),...Ee,mod:[{accept:nt,reject:Tt,idle:Te,loading:f,"activate-on-click":T},ae],children:[s.jsx(qy,{visible:f,overlayProps:{radius:u},unstyled:l,loaderProps:ie}),s.jsx("input",{...Le(Re),name:x}),s.jsx("div",{...Fe("inner"),ref:t,"data-enable-pointer-events":K||void 0,children:v})]})})});Gi.classes=Vc;Gi.displayName="@mantine/dropzone/Dropzone";Gi.Accept=BQ;Gi.Idle=VQ;Gi.Reject=UQ;const qQ={loading:!1,maxSize:1/0,activateOnClick:!1,activateOnDrag:!0,dragEventsBubbling:!0,activateOnKeyboard:!0,active:!0,zIndex:eo("max"),withinPortal:!0},j0=X((e,t)=>{const n=W("DropzoneFullScreen",qQ,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=ce({name:"DropzoneFullScreen",classes:Vc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,rootSelector:"fullScreen"}),{resolvedClassNames:y,resolvedStyles:w}=Hc({classNames:r,styles:a,props:n}),[b,x]=p.useState(0),[C,{open:j,close:T}]=Zg(!1),E=k=>{var A;(A=k.dataTransfer)!=null&&A.types.includes("Files")&&(x(O=>O+1),j())},_=()=>{x(k=>k-1)};return p.useEffect(()=>{b===0&&T()},[b]),p.useEffect(()=>{if(u)return document.addEventListener("dragenter",E,!1),document.addEventListener("dragleave",_,!1),()=>{document.removeEventListener("dragenter",E,!1),document.removeEventListener("dragleave",_,!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(Gi,{...v,classNames:y,styles:w,unstyled:l,className:Vc.dropzone,onDrop:k=>{d==null||d(k),T(),x(0)},onReject:k=>{f==null||f(k),T(),x(0)}})})})});j0.classes=Vc;j0.displayName="@mantine/dropzone/DropzoneFullScreen";Gi.FullScreen=j0;const ud=Gi,GQ='{"resourceType": "Bundle"}';function nm({id:e,title:t,message:n,color:r,icon:o,withCloseButton:i=!1,method:a="show",loading:l}){vo[a]({id:e,loading:l,title:t,message:n,color:r,icon:o,withCloseButton:i,autoClose:!1})}function QQ(){const e=At(),t=se(),[n,r]=p.useState({}),o=p.useCallback(async(l,c)=>{const u="batch-upload";nm({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=xk(d));const f=await t.executeBatch(d);r(h=>({...h,[c]:f})),nm({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){nm({id:u,title:"Batch Upload Failed",color:"red",message:De(d),method:"update",icon:s.jsx(xf,{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(Ne,{children:[s.jsx(ge,{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(ud,{onDrop:i,accept:["application/json"],children:s.jsxs(te,{justify:"center",gap:"xl",style:{minHeight:220,pointerEvents:"none"},children:[s.jsx(ud.Accept,{children:s.jsx(jw,{size:50,stroke:1.5,color:e.colors[e.primaryColor][5]})}),s.jsx(ud.Reject,{children:s.jsx(xf,{size:50,stroke:1.5,color:e.colors.red[5]})}),s.jsx(ud.Idle,{children:s.jsx(jw,{size:50,stroke:1.5})}),s.jsxs("div",{children:[s.jsx(fe,{size:"xl",inline:!0,children:"Drag files here or click to select files"}),s.jsx(fe,{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(Ke,{onSubmit:a,children:[s.jsx(pl,{"data-testid":"batch-input",name:"input",autosize:!0,minRows:20,defaultValue:GQ,deserialize:JSON.parse}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(oe,{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(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(oe,{onClick:()=>r({}),children:"Start over"})})]})]})}function KQ(){const{resourceType:e}=ct(),n=(Object.fromEntries(new URLSearchParams(location.search).entries()).ids||"").split(",").filter(o=>!!o),[r]=ol("Questionnaire",`subject-type=${e}`);return r?r.length===0?s.jsxs(Ne,{children:[s.jsxs(ge,{children:["No apps for ",e]}),s.jsx(Ge,{to:`/${e}`,children:"Return to search page"})]}):s.jsx(Ne,{children:s.jsx("div",{children:r.map(o=>s.jsxs("div",{children:[s.jsx("h3",{children:s.jsx(Ge,{to:`/forms/${o.id}?subject=`+n.map(i=>`${e}/${i}`).join(","),children:o.name})}),s.jsx("p",{children:o.description})]},o.id))})}):s.jsx(Jr,{})}function YQ(){const e=se(),[t,n]=p.useState(),[r,o]=p.useState(!1);return s.jsx(Ne,{width:450,children:s.jsxs(Ke,{onSubmit:i=>{n(void 0),e.post("auth/changepassword",i).then(()=>o(!0)).catch(a=>n(ht(a)))},children:[s.jsxs(mn,{style:{flexDirection:"column"},children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Change password"})]}),!r&&s.jsxs(Oe,{gap:"xl",mt:"xl",children:[s.jsx(Qr,{name:"oldPassword",label:"Old password",required:!0,autoFocus:!0,error:Je(t,"oldPassword")}),s.jsx(Qr,{name:"newPassword",label:"New password",required:!0,error:Je(t,"newPassword")}),s.jsx(Qr,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Je(t,"confirmPassword")}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(oe,{type:"submit",children:"Change password"})})]}),r&&s.jsx("div",{"data-testid":"success",children:"Password changed successfully"})]})})}const zg=["Form","JSON","Profiles"],XQ=["Profiles"],rm=zg[0].toLowerCase();function JQ(){const e=Qt(),t=At(),{resourceType:n}=ct(),[r,o]=p.useState(()=>{const a=window.location.pathname.split("/").pop();return a&&zg.map(l=>l.toLowerCase()).includes(a)?a:rm});function i(a){a||(a=rm),o(a),e(`/${n}/new/${a}`)}return s.jsxs(s.Fragment,{children:[s.jsxs(Yn,{children:[s.jsxs(fe,{p:"md",fw:500,children:["New ",n]}),s.jsx(Ir,{children:s.jsx(et,{defaultValue:rm,value:r,onChange:i,children:s.jsx(et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:zg.map(a=>s.jsx(et.Tab,{value:a.toLowerCase(),px:"md",children:XQ.includes(a)?s.jsxs(te,{gap:"xs",wrap:"nowrap",children:[a,s.jsx(ru,{color:t.primaryColor,size:"sm",children:"Beta"})]}):a},a))})})})]}),s.jsx(x0,{})]})}function ZQ(){return s.jsx(Ne,{children:s.jsxs(Oe,{children:[s.jsx(ge,{order:1,children:"Unexpected Error"}),s.jsx(fe,{children:"We're sorry, something went wrong."}),s.jsxs(fe,{children:["Please contact ",s.jsx(Ze,{href:"mailto:support@medplum.com",children:"support"})," for assistance."]})]})})}const eK="_root_1fbwr_1",tK="_entry_1fbwr_8",nK="_key_1fbwr_13",rK="_value_1fbwr_20",Kh={root:eK,entry:tK,key:nK,value:rK};function ze(e){return s.jsx(Ir,{children:s.jsx("div",{className:Kh.root,children:e.children})})}ze.Entry=function(t){return s.jsx("div",{className:Kh.entry,children:t.children})};ze.Key=function(t){return s.jsx("div",{className:Kh.key,children:t.children})};ze.Value=function(t){return s.jsx("div",{className:Kh.value,children:t.children})};function oK(e){if(e.gender==="male")return"blue";if(e.gender==="female")return"pink"}function k2(e){var n,r;const t=wt(e.patient);return t?s.jsxs(ze,{children:[s.jsx(Hi,{value:t,size:"lg",color:oK(t)}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Name"}),s.jsx(ze.Value,{children:s.jsx(Ge,{to:t,fw:500,children:t.name?s.jsx(qx,{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:i6(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 R2(e){const t=wt(e.resource);if(!t)return null;const n=[{key:"Type",value:s.jsx(Ge,{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!==st(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 C0(e){if(e.resourceType==="Patient")return e;if(e.resourceType==="DiagnosticReport"||e.resourceType==="Encounter"||e.resourceType==="Observation"||e.resourceType==="ServiceRequest")return e.subject}function iK(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 Dd(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 nl((t=e.getActiveLogin())==null?void 0:t.project)}function sK(e,t){const n=new Blob([e],{type:on.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 aK(){const{id:e}=ct(),t=oi(),r=Object.fromEntries(new URLSearchParams(t.search).entries()).subject,o=se(),[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 b={resourceType:"Bundle",type:"batch",entry:[{request:{method:"GET",url:`Questionnaire/${e}`}}]};if(r){const x=r.split(",").filter(C=>!!C);x.length===1&&b.entry.push({request:{method:"GET",url:x[0]}}),d(x)}o.executeBatch(b).then(x=>{var C,j,T,E,_,k,A,O;((T=(j=(C=x.entry)==null?void 0:C[0])==null?void 0:j.response)==null?void 0:T.status)!=="200"?g((k=(_=(E=x.entry)==null?void 0:E[0])==null?void 0:_.response)==null?void 0:k.outcome):(c((A=x.entry[0])==null?void 0:A.resource),h((O=x.entry[1])==null?void 0:O.resource)),a(!1)}).catch(x=>{g(x),a(!1)})},[o,e,r]),m)return s.jsx(Ne,{children:s.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)})});if(v)return s.jsxs(Ne,{children:[s.jsx(ge,{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(Ge,{to:v[0],children:"Review your answers"})}),v.length>1&&s.jsxs("li",{children:["Review your answers:",s.jsx("ul",{children:v.map(b=>s.jsx("li",{children:s.jsx(Ge,{to:b,children:st(b)})},b.id))})]}),f&&s.jsx("li",{children:s.jsxs(Ge,{to:f,children:["Back to ",Wo(f)]})}),s.jsx("li",{children:s.jsx(Ge,{to:"/",children:"Go back home"})})]})]});if(i||!l)return s.jsx(Jr,{});const y=f&&C0(f);return s.jsxs(s.Fragment,{children:[s.jsxs(Yn,{shadow:"xs",radius:0,children:[y&&s.jsx(k2,{patient:y}),f&&f.resourceType!=="Patient"&&s.jsx(R2,{resource:f}),s.jsx(q,{px:"xl",py:"md",children:s.jsxs(fe,{children:[Wo(l),u&&u.length>1&&s.jsxs(s.Fragment,{children:[" (for ",u.length," resources)"]})]})})]}),s.jsx(Ne,{children:s.jsx(VR,{questionnaire:l,subject:f&&Et(f),onSubmit:w})})]});async function w(b){const x=[];if(!u||u.length===0)x.push(await o.createResource(b));else for(const C of u)x.push(await o.createResource({...b,subject:{reference:C}}));S(x)}}const lK="_paper_unw9o_1",cK={paper:lK},uK={Bot:"/admin/bots/new",ClientApplication:"/admin/clients/new"};function _2(e,t){const n=e.resourceType||dK(t),r=e.fields??fK(n),o=e.filters??(e.resourceType?void 0:hK(n)),i=e.sortRules??pK(n),a=e.offset??0,l=e.count??Ah;return{...e,resourceType:n,fields:r,filters:o,sortRules:i,offset:a,count:l}}function dK(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 fK(e){const t=E0(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 hK(e){var t;return(t=E0(e))==null?void 0:t.filters}function pK(e){const t=E0(e);return t!=null&&t.sortRules?t.sortRules:[{code:"_lastUpdated",descending:!0}]}function E0(e){const t=localStorage.getItem(e+"-defaultSearch");return t?JSON.parse(t):void 0}function mK(e){localStorage.setItem("defaultResourceType",e.resourceType),localStorage.setItem(e.resourceType+"-defaultSearch",JSON.stringify(e))}async function gK(e,t){const n={resourceType:e.resourceType,count:1e3,offset:0,filters:e.filters},r=_2(n,t.getUserConfiguration()),o=await t.search(r.resourceType,Ra({...r,total:"accurate",fields:void 0}));return xk(o)}function SS(){const e=se(),t=Qt(),n=oi(),[r,o]=p.useState();return p.useEffect(()=>{const i=pk(n.pathname+n.search),a=_2(i,e.getUserConfiguration());n.pathname===`/${a.resourceType}`&&n.search===Ra(a)?(mK(a),o(a)):t(`/${a.resourceType}${Ra(a)}`)},[e,t,n]),!(r!=null&&r.resourceType)||!r.fields||r.fields.length===0?s.jsx(Jr,{}):s.jsx(Yn,{shadow:"xs",m:"md",p:"xs",className:cK.paper,children:s.jsx(wu,{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}${Ra(i.definition)}`)},onNew:()=>{t(uK[r.resourceType]??`/${r.resourceType}/new`)},onExportCsv:()=>{const i=e.fhirUrl(r.resourceType,"$csv")+Ra(r);e.download(i).then(a=>{window.open(window.URL.createObjectURL(a),"_blank")}).catch(a=>he({color:"red",message:De(a),autoClose:!1}))},onExportTransactionBundle:async()=>{gK(r,e).then(i=>sK(JSON.stringify(i,void 0,2))).catch(i=>he({color:"red",message:De(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=>he({color:"red",message:De(a),autoClose:!1})))},onBulk:i=>{t(`/bulk/${r.resourceType}?ids=${i.join(",")}`)}})})}function vK(){const e=se(),[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=>he({color:"red",message:De(l),autoClose:!1}))},[e]);const i=p.useCallback(l=>{e.post("auth/mfa/enroll",l).then(()=>{o(!0),he({color:"green",message:"Success"})}).catch(c=>he({color:"red",message:De(c),autoClose:!1}))},[e]),a=p.useCallback(()=>{e.post("auth/mfa/disable",{}).catch(console.log)},[e]);return r===void 0?null:r?s.jsx(Ne,{children:s.jsxs(te,{children:[s.jsx(ge,{children:"MFA is enabled"}),s.jsx(oe,{onClick:a,children:"Disable MFA"})]})}):s.jsx(Ne,{width:400,children:s.jsxs(Ke,{onSubmit:i,children:[s.jsx(ge,{children:"Multi Factor Auth Setup"}),s.jsx(mn,{children:s.jsx("img",{src:t})}),s.jsx(ve,{name:"token",label:"Code"}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{type:"submit",children:"Enroll"})})]})})}const om={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.7-a4111e333",MODE:"production",PROD:!0,RECAPTCHA_SITE_KEY:"__RECAPTCHA_SITE_KEY__",SSR:!1},Bg={baseUrl:"__MEDPLUM_BASE_URL__",clientId:"__MEDPLUM_CLIENT_ID__",googleClientId:"__GOOGLE_CLIENT_ID__",recaptchaSiteKey:"__RECAPTCHA_SITE_KEY__",registerEnabled:"__MEDPLUM_REGISTER_ENABLED__",awsTextractEnabled:om==null?void 0:om.MEDPLUM_AWS_TEXTRACT_ENABLED};function Eu(){return Bg}function D2(){return I2("registerEnabled")}function yK(){return I2("awsTextractEnabled")}function I2(e){try{return Bg[e]!==!1&&Bg[e]!=="false"}catch{return!0}}function xK(){const e=Qt(),[t]=b0(),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(JR,{onCode:o,onForgotPassword:()=>e("/resetpassword"),onRegister:()=>e("/register"),googleClientId:Eu().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(ro,{size:32}),s.jsx(ge,{children:"Sign in to Medplum"})]})}function bK(){const e=se(),t=Qt(),n=Eu();return p.useEffect(()=>{e.getProfile()&&t("/signin?project=new")},[e,t]),D2()?s.jsxs(yq,{type:"project",projectId:"new",onSuccess:()=>t("/"),googleClientId:n.googleClientId,recaptchaSiteKey:n.recaptchaSiteKey,children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Create a new account"})]}):s.jsx(Ne,{width:450,children:s.jsx(Vi,{icon:s.jsx(Sl,{size:16}),title:"New projects disabled",color:"red",children:"New projects are disabled on this server."})})}function wK(){const e=Qt(),t=se(),[n,r]=p.useState(),[o,i]=p.useState(!1),a=Eu().recaptchaSiteKey;return p.useEffect(()=>{a&&YR(a)},[a]),s.jsx(Ne,{width:450,children:s.jsxs(Ke,{onSubmit:async l=>{let c="";a&&(c=await XR(a)),t.post("auth/resetpassword",{...l,recaptchaToken:c}).then(()=>i(!0)).catch(u=>r(ht(u)))},children:[s.jsxs(Oe,{gap:"lg",mb:"xl",align:"center",children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Medplum Password Reset"})]}),s.jsxs(Oe,{gap:"xl",children:[s.jsx(Mr,{issues:vu(n,void 0)}),!o&&s.jsxs(s.Fragment,{children:[s.jsx(ve,{name:"email",type:"email",label:"Email",required:!0,autoFocus:!0,error:Je(n,"email")}),s.jsxs(te,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[s.jsx(Ze,{component:"button",type:"button",color:"dimmed",onClick:()=>e("/register"),size:"xs",children:"Register"}),s.jsx(oe,{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 SK(){var i;const e=Qt(),t=se(),[n,r]=p.useState();p.useEffect(()=>{t.get("auth/me").then(r).catch(a=>he({color:"red",message:De(a),autoClose:!1}))},[t]);function o(a){t.post("auth/revoke",{loginId:a}).then(()=>t.get("auth/me",{cache:"no-cache"})).then(r).then(()=>he({color:"green",message:"Login revoked"})).catch(l=>he({color:"red",message:De(l),autoClose:!1}))}return n?s.jsxs(s.Fragment,{children:[s.jsxs(Ne,{children:[s.jsx(ge,{children:"Security"}),s.jsxs(Yx,{children:[s.jsx(No,{term:"ID",children:s.jsx(Ze,{href:`/${st(n.profile)}`,children:n.profile.id})}),s.jsx(No,{term:"Resource Type",children:n.profile.resourceType}),s.jsx(No,{term:"Name",children:fu((i=n.profile.name)==null?void 0:i[0])})]})]}),s.jsxs(Ne,{children:[s.jsx(ge,{children:"Sessions"}),s.jsxs(de,{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:Fn(a.lastUpdated)}),s.jsx("td",{children:s.jsx(Ze,{href:"#",onClick:()=>o(a.id),children:"Revoke"})})]},a.id))})]})]}),s.jsxs(Ne,{children:[s.jsx(ge,{children:"Password"}),s.jsx(oe,{onClick:()=>e("/changepassword"),children:"Change password"})]}),s.jsxs(Ne,{children:[s.jsx(ge,{children:"Multi Factor Auth"}),s.jsxs("p",{children:["Enrolled: ",n.security.mfaEnrolled.toString()]}),!n.security.mfaEnrolled&&s.jsx(oe,{onClick:()=>e("/mfa"),children:"Enroll"})]})]}):null}function jK(){const{id:e,secret:t}=ct(),n=se(),[r,o]=p.useState(),[i,a]=p.useState(!1),l=vu(r,void 0);return s.jsxs(Ne,{width:450,children:[s.jsx(Mr,{issues:l}),s.jsxs(Ke,{onSubmit:c=>{if(c.password!==c.confirmPassword){o(Ri("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(ht(d)))},children:[s.jsxs(mn,{style:{flexDirection:"column"},children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Set password"})]}),!i&&s.jsxs(Oe,{children:[s.jsx(Qr,{name:"password",label:"New password",required:!0,error:Je(r,"password")}),s.jsx(Qr,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Je(r,"confirmPassword")}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{type:"submit",children:"Set password"})})]}),i&&s.jsxs("div",{"data-testid":"success",children:["Password set. You can now ",s.jsx(Ge,{to:"/signin",children:"sign in"}),"."]})]})]})}function CK(){const e=$h(),t=Qt(),[n]=b0(),r=Eu(),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(JR,{onSuccess:()=>o(),onForgotPassword:()=>t("/resetpassword"),onRegister:D2()?()=>t("/register"):void 0,googleClientId:r.googleClientId,login:n.get("login")||void 0,projectId:n.get("project")||void 0,children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Sign in to Medplum"}),n.get("project")==="new"&&s.jsx("div",{children:"Sign in again to create a new project"})]})}function EK(){const e=Qt(),t=oi(),[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(SW,{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 Yh(e){const t=se(),n=Qi(t),r=Qt(),[o,i]=p.useState({resourceType:"ProjectMembership",filters:[{code:"project",operator:re.EQUALS,value:"Project/"+n},{code:"profile-type",operator:re.EQUALS,value:e.resourceType}],fields:e.fields,count:100});return s.jsx(wu,{search:o,onClick:a=>r(`/admin/members/${a.resource.id}`),onChange:a=>i(a.definition),hideFilters:!0,hideToolbar:!0})}function TK(){return s.jsxs(s.Fragment,{children:[s.jsx(ge,{children:"Bots"}),s.jsx(Yh,{resourceType:"Bot",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(Ge,{to:"/admin/bots/new",children:"Create new bot"})})]})}function PK(){return s.jsxs(s.Fragment,{children:[s.jsx(ge,{children:"Clients"}),s.jsx(Yh,{resourceType:"ClientApplication",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(Ge,{to:"/admin/clients/new",children:"Create new client"})})]})}function Xh(e){return s.jsx(Ys,{resourceType:"AccessPolicy",name:"accessPolicy",defaultValue:e.defaultValue,placeholder:"Access Policy",onChange:t=>{ni(t)?e.onChange(Et(t)):e.onChange(void 0)}})}function kK(){const e=se(),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(ge,{children:"Create new Bot"}),s.jsxs(Ke,{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),he({color:"green",message:"Bot created"})}).catch(m=>{he({color:"red",message:De(m),autoClose:!1}),u(ht(m))})},children:[!d&&s.jsxs(Oe,{children:[s.jsx(vt,{title:"Name",htmlFor:"name",outcome:c,children:s.jsx(ve,{id:"name",name:"name",required:!0,autoFocus:!0,onChange:h=>r(h.currentTarget.value),error:Je(c,"name")})}),s.jsx(vt,{title:"Description",htmlFor:"description",outcome:c,children:s.jsx(ve,{id:"description",name:"description",onChange:h=>i(h.currentTarget.value),error:Je(c,"description")})}),s.jsx(vt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:c,children:s.jsx(Xh,{name:"accessPolicy",onChange:l})}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{type:"submit",children:"Create Bot"})})]}),d&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(fe,{children:"Bot created"}),s.jsxs(Ln,{children:[s.jsx(Ln.Item,{children:s.jsx(Ge,{to:d,children:"Go to new bot"})}),s.jsx(Ln.Item,{children:s.jsx(Ge,{to:"/admin/bots",children:"Back to bots list"})})]})]})]})]})}function RK(){const e=se(),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(ge,{children:"Create new Client"}),s.jsxs(Ke,{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),he({color:"green",message:"Client created"})}).catch(v=>{he({color:"red",message:De(v),autoClose:!1}),f(ht(v))})},children:[!h&&s.jsxs(Oe,{children:[s.jsx(vt,{title:"Name",htmlFor:"name",outcome:d,children:s.jsx(ve,{id:"name",name:"name",required:!0,autoFocus:!0,onChange:g=>r(g.currentTarget.value),error:Je(d,"name")})}),s.jsx(vt,{title:"Description",htmlFor:"description",outcome:d,children:s.jsx(ve,{id:"description",name:"description",onChange:g=>i(g.currentTarget.value),error:Je(d,"description")})}),s.jsx(vt,{title:"Redirect URI",htmlFor:"redirectUri",outcome:d,children:s.jsx(ve,{id:"redirectUri",name:"redirectUri",onChange:g=>l(g.currentTarget.value),error:Je(d,"redirectUri")})}),s.jsx(vt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:d,children:s.jsx(Xh,{name:"accessPolicy",onChange:u})}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{type:"submit",children:"Create Client"})})]}),h&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(fe,{children:"Client created"}),s.jsxs(Ln,{children:[s.jsx(Ln.Item,{children:s.jsx(Ge,{to:h,children:"Go to new client"})}),s.jsx(Ln.Item,{children:s.jsx(Ge,{to:"/admin/clients",children:"Back to clients list"})})]})]})]})]})}function _K(e){return s.jsx(Ys,{resourceType:"UserConfiguration",name:"userConfiguration",defaultValue:e.defaultValue,placeholder:"User Configuration",onChange:t=>{ni(t)?e.onChange(Et(t)):e.onChange(void 0)}})}function DK(){const{membershipId:e}=ct(),t=se(),n=Qi(t),r=Qt(),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(ht(S)))}return s.jsxs(s.Fragment,{children:[s.jsx(ge,{children:"Edit membership"}),s.jsx("h3",{children:s.jsx(Ua,{value:o.profile,link:!0})}),s.jsxs(Ke,{onSubmit:()=>{const S={...o,accessPolicy:i,userConfiguration:l,admin:u};t.post(`admin/projects/${n}/members/${e}`,S).then(()=>g(!0)).catch(y=>h(ht(y)))},children:[!m&&s.jsxs(Oe,{children:[s.jsx(vt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:f,children:s.jsx(Xh,{name:"accessPolicy",defaultValue:i,onChange:a})}),s.jsx(vt,{title:"User Configuration",htmlFor:"userConfiguration",outcome:f,children:s.jsx(_K,{name:"userConfiguration",defaultValue:l,onChange:c})}),s.jsx(vt,{title:"Admin",htmlFor:"admin",outcome:f,children:s.jsx(_n,{id:"admin",name:"admin",defaultChecked:u,onChange:S=>d(S.currentTarget.checked)})}),s.jsxs(te,{justify:"flex-end",mt:"xl",children:[s.jsx(oe,{type:"submit",children:"Save"}),s.jsx(oe,{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(Ge,{to:"/admin/project",children:"here"})," to return to the project admin page."]})]})]})]})}function IK(){const e=se(),[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"),_h(g)?a(g):d(g),c(m.sendEmail??!1),he({color:"green",message:"Invite success"})}).catch(g=>{he({color:"red",message:De(g),autoClose:!1}),a(ht(g))})},[e,t,r]);return s.jsxs(Ke,{onSubmit:f,children:[!u&&!i&&s.jsxs(Oe,{children:[s.jsx(ge,{children:"Invite new member"}),e.isSuperAdmin()&&s.jsx(vt,{title:"Project",htmlFor:"project",outcome:i,children:s.jsx(Ys,{resourceType:"Project",name:"project",defaultValue:t,onChange:n})}),s.jsx(It,{name:"resourceType",label:"Role",defaultValue:"Practitioner",data:["Practitioner","Patient","RelatedPerson"],error:Je(i,"resourceType")}),s.jsx(ve,{name:"firstName",label:"First Name",required:!0,autoFocus:!0,error:Je(i,"firstName")}),s.jsx(ve,{name:"lastName",label:"Last Name",required:!0,error:Je(i,"lastName")}),s.jsx(ve,{name:"email",type:"email",label:"Email",required:!0,error:Je(i,"email")}),s.jsx(vt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:i,children:s.jsx(Xh,{name:"accessPolicy",onChange:o})}),s.jsx(_n,{name:"sendEmail",label:"Send email",defaultChecked:!0}),s.jsx(_n,{name:"isAdmin",label:"Admin"}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{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(Ge,{to:"/admin/project",children:"here"})," to return to the project admin page."]})]}),u&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(fe,{children:"User created"}),l&&s.jsx(fe,{children:"Email sent"}),s.jsxs(Ln,{children:[s.jsx(Ln.Item,{children:s.jsx(Ge,{to:u,children:"Go to new membership"})}),s.jsx(Ln.Item,{children:s.jsx(Ge,{to:u.profile,children:"Go to new profile"})}),s.jsx(Ln.Item,{children:s.jsx(Ge,{to:"/admin/users",children:"Back to users list"})})]})]})]})}function AK(){return s.jsxs(s.Fragment,{children:[s.jsx(ge,{children:"Patients"}),s.jsx(Yh,{resourceType:"Patient",fields:["user","profile","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(Ge,{to:"/admin/invite",children:"Invite new patient"})})]})}function NK(){const e=se();if(!e.isLoading()&&!e.isProjectAdmin())return s.jsx(Mr,{outcome:BP});function t(n){e.post("admin/projects/setpassword",n).then(()=>he({color:"green",message:"Done"})).catch(r=>he({color:"red",message:De(r),autoClose:!1}))}return s.jsxs(Ne,{width:600,children:[s.jsx(ge,{order:1,children:"Project Admin"}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{order:2,children:"Force Set Password"}),s.jsx(fe,{children:"Sets the password for the specified user in this project."}),s.jsx(fe,{children:"This action can only be performed by project administrators. Passwords can only be set for users scoped in this project."}),s.jsx(Ke,{onSubmit:t,children:s.jsxs(Oe,{children:[s.jsx(ve,{name:"email",label:"Email",required:!0}),s.jsx(Qr,{name:"password",label:"Password",required:!0}),s.jsx(oe,{type:"submit",children:"Force Set Password"})]})})]})}function jS(){const e=se(),t=Qi(e),n=e.get(`admin/projects/${t}`).read();return s.jsxs(s.Fragment,{children:[s.jsx(ge,{children:"Details"}),s.jsxs(Yx,{children:[s.jsx(No,{term:"ID",children:n.project.id}),s.jsx(No,{term:"Name",children:n.project.name})]})]})}const CS=["Details","Users","Patients","Clients","Bots","Secrets","Sites"];function MK(){const e=Qt(),n=oi().pathname.replace("/admin/","")||CS[0],r=se(),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(Yn,{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(Ir,{children:s.jsx(et,{value:n.toLowerCase(),onChange:a,children:s.jsx(et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:CS.map(l=>s.jsx(et.Tab,{value:l.toLowerCase(),children:l},l))})})})]}),s.jsx(Ne,{children:s.jsx(x0,{})})]})}function OK(){const e=se(),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(Xr(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(()=>he({color:"green",message:"Saved"})).catch(console.log)},children:[s.jsx(ge,{children:"Project Secrets"}),s.jsx("p",{children:"Use project secrets to store sensitive information such as API keys or other access credentials."}),s.jsx(jl,{property:Gs("Project","secret"),name:"secret",path:"Project.secret",defaultValue:i,onChange:a,outcome:void 0}),s.jsx(oe,{type:"submit",children:"Save"})]})}function LK(){const e=se(),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(Xr(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(()=>he({color:"green",message:"Saved"})).catch(c=>{var d,f,h,m;const u=ht(c);he({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(ge,{children:"Project Sites"}),s.jsx("p",{children:"Use project sites configure your project on a separate domain."}),s.jsx(jl,{property:Gs("Project","site"),name:"site",path:"Project.site",defaultValue:i,onChange:a,outcome:void 0}),s.jsx(oe,{type:"submit",children:"Save"})]})}function $K(){const e=se(),[t,{open:n,close:r}]=Zg(!1),[o,i]=p.useState(""),[a,l]=p.useState();if(!e.isLoading()&&!e.isSuperAdmin())return s.jsx(Mr,{outcome:BP});function c(){dd(e,"Rebuilding Structure Definitions","admin/super/structuredefinitions")}function u(){dd(e,"Rebuilding Search Parameters","admin/super/searchparameters")}function d(){dd(e,"Rebuilding Value Sets","admin/super/valuesets")}function f(S){dd(e,"Reindexing Resources","admin/super/reindex",S)}function h(S){e.post("admin/super/removebotidjobsfromqueue",S).then(()=>he({color:"green",message:"Done"})).catch(y=>he({color:"red",message:De(y),autoClose:!1}))}function m(S){e.post("admin/super/purge",{...S,before:eR(S.before)}).then(()=>he({color:"green",message:"Done"})).catch(y=>he({color:"red",message:De(y),autoClose:!1}))}function g(S){e.post("admin/super/setpassword",S).then(()=>he({color:"green",message:"Done"})).catch(y=>he({color:"red",message:De(y),autoClose:!1}))}function v(){e.post("fhir/R4/$db-stats",{}).then(S=>{var y,w;i("Database Stats"),l(s.jsx("pre",{children:(w=(y=S.parameter)==null?void 0:y.find(b=>b.name==="tableString"))==null?void 0:w.valueString})),n()}).catch(S=>he({color:"red",message:De(S),autoClose:!1}))}return s.jsxs(Ne,{width:600,children:[s.jsx(ge,{order:1,children:"Super Admin"}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{children:s.jsx(oe,{onClick:c,children:"Rebuild StructureDefinitions"})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{children:s.jsx(oe,{onClick:u,children:"Rebuild SearchParameters"})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{children:s.jsx(oe,{onClick:d,children:"Rebuild ValueSets"})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{onSubmit:f,children:s.jsxs(Oe,{children:[s.jsx(vt,{title:"Resource Type",htmlFor:"resourceType",children:s.jsx(ve,{id:"resourceType",name:"resourceType",placeholder:"Reindex Resource Type"})}),s.jsx(vt,{title:"Search Filter",htmlFor:"filter",children:s.jsx(ve,{id:"filter",name:"filter",placeholder:"e.g. name=Sam&birthdate=lt2000-01-01"})}),s.jsx(oe,{type:"submit",children:"Reindex"})]})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{onSubmit:m,children:s.jsxs(Oe,{children:[s.jsx(vt,{title:"Purge Resource Type",htmlFor:"purgeResourceType",children:s.jsx(It,{id:"purgeResourceType",name:"resourceType",data:["","AuditEvent","Login"]})}),s.jsx(vt,{title:"Purge Before",htmlFor:"before",children:s.jsx(_s,{name:"before",placeholder:"Before Date"})}),s.jsx(oe,{type:"submit",children:"Purge"})]})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{order:2,children:"Remove Bot ID Jobs from Queue"}),s.jsx("p",{children:"Remove all queued jobs for a Bot ID"}),s.jsx(Ke,{onSubmit:h,children:s.jsxs(Oe,{children:[s.jsx(vt,{title:"Bot ID",children:s.jsx(ve,{name:"botId",placeholder:"Bot Id"})}),s.jsx(oe,{type:"submit",children:"Remove Jobs by Bot ID"})]})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{onSubmit:g,children:s.jsxs(Oe,{children:[s.jsx(ve,{name:"email",label:"Email",required:!0}),s.jsx(Qr,{name:"password",label:"Password",required:!0}),s.jsx(ve,{name:"projectId",label:"Project ID"}),s.jsx(oe,{type:"submit",children:"Force Set Password"})]})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{order:2,children:"Database Stats"}),s.jsx("p",{children:"Query current table statistics from the database."}),s.jsx(Ke,{onSubmit:v,children:s.jsx(oe,{type:"submit",children:"Get Database Stats"})}),s.jsx(wn,{opened:t,onClose:r,title:o,centered:!0,children:a})]})}function dd(e,t,n,r){vo.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(()=>{vo.update({id:n,color:"green",title:t,message:"Done",icon:s.jsx(Ks,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}).catch(i=>{vo.update({id:n,color:"red",title:t,message:De(i),icon:s.jsx(xf,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})})}function FK(){return s.jsxs(s.Fragment,{children:[s.jsx(ge,{children:"Users"}),s.jsx(Yh,{resourceType:"Practitioner",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(Ge,{to:"/admin/invite",children:"Invite new user"})})]})}function zK(){const[e]=ol("ObservationDefinition","_count=100");return e?s.jsxs(de,{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(yo,{value:(n=t.category)==null?void 0:n[0]})}),s.jsx("td",{children:s.jsx(yo,{value:t.code})}),s.jsx("td",{children:s.jsx(yo,{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(Ug,{ranges:t.qualifiedInterval})})]},t.id)})})]}):s.jsx(Jr,{})}function Ug(e){const{ranges:t}=e;if(!t)return null;const n=ES(t.map(o=>o.gender));if(n.length>1)return Nc(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:nn(o)})}),s.jsx(Ug,{ranges:(i=e.ranges)==null?void 0:i.filter(a=>a.gender===o)})]},o)})});const r=ES(t.map(o=>o.age&&Mc(o.age)));return r.length>1?(Nc(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:nn(o)})}),s.jsx(Ug,{ranges:(i=e.ranges)==null?void 0:i.filter(a=>Mc(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(Jx,{value:o.range})})]})})},`range-${o.condition}`))})}function ES(e){return[...new Set(e.filter(t=>!!t))]}function BK(){const[e]=ol("ActivityDefinition","_count=100"),[t]=ol("ObservationDefinition","_count=100");return!e||!t?s.jsx(Jr,{}):s.jsxs(de,{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(yo,{value:(r=n.category)==null?void 0:r[0]})}),s.jsx("td",{children:s.jsx(yo,{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 UK(e){var a;const t=se(),[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(Ge,{to:o,suffix:"checklist",children:"Request Group"})]}),s.jsxs("li",{children:["Back to the ",s.jsx(Ge,{to:e.planDefinition,children:"Plan Definition"})]})]})]}):s.jsx(Ke,{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(Oe,{children:[s.jsxs(ge,{children:['Start "',e.planDefinition.title,'"']}),s.jsxs(fe,{children:["Use the ",s.jsx("strong",{children:"Apply"})," operation to create a group of tasks for a workflow."]}),s.jsx(fe,{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(yo,{value:l.code[0]})]},`action-${c}`)})}),s.jsx(vt,{title:"Subject",children:s.jsx(zh,{name:"subject",targetTypes:["Patient","Practitioner"],defaultValue:n,onChange:r})}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{type:"submit",children:"Go"})})]})})}function VK(){const{resourceType:e,id:t}=ct(),n=wt({reference:e+"/"+t});return n?s.jsx(Ne,{children:s.jsx(UK,{planDefinition:n})}):null}function WK(){const{resourceType:e,id:t}=ct(),n=wt({reference:e+"/"+t}),[r,o]=ol("Questionnaire","subject-type="+e),[i,a]=ol("ClientApplication",{_count:1e3});if(!n||o||a)return s.jsx(Jr,{});const l=i==null?void 0:i.filter(d=>HK(e)&&!!d.launchUri);if((!r||r.length===0)&&(!l||l.length===0))return s.jsxs(Ne,{children:[s.jsx(ge,{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=Et(n):n.resourceType==="Encounter"&&(c=n.subject,u=Et(n)),s.jsxs(Ne,{children:[r==null?void 0:r.map(d=>s.jsxs("div",{children:[s.jsx(ge,{order:3,children:s.jsx(Ge,{to:`/forms/${d.id}?subject=${st(n)}`,children:d.title||d.name})}),s.jsx(fe,{children:d.description})]},d.id)),l==null?void 0:l.map(d=>s.jsxs("div",{children:[s.jsx(ge,{order:3,children:s.jsx(gq,{client:d,patient:c,encounter:u,children:d.name})}),s.jsx(fe,{children:d.description})]},d.id))]})}function HK(e){return e==="Patient"||e==="Encounter"}function qK(){const{resourceType:e,id:t}=ct(),n=Qt(),[r,o]=p.useState({resourceType:"AuditEvent",filters:[{code:"entity",operator:re.EQUALS,value:`${e}/${t}`}],fields:["id","outcome","outcomeDesc","_lastUpdated"],sortRules:[{code:"-_lastUpdated"}],count:20});return s.jsx(Ne,{children:s.jsx(wu,{search:r,onClick:i=>n(`/${i.resource.resourceType}/${i.resource.id}`),onChange:i=>o(i.definition),hideFilters:!0})})}function GK(){const e=se(),{resourceType:t,id:n}=ct(),r=e.readHistory(t,n).read();return s.jsx(Ne,{children:s.jsx(iq,{history:r})})}const QK="_hl7Input_k5xm3_1",KK={hl7Input:QK};function YK(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 XK(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=>{Dd(r.currentTarget,{command:"setValue",value:t}).catch(console.error)}})}const JK=`{
572
+ */function Tf(){return Tf=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},Tf.apply(this,arguments)}function Lg(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 BG(e,t){let n=Lg(e);return t&&t.forEach((r,o)=>{n.has(o)||t.getAll(o).forEach(i=>{n.append(o,i)})}),n}const UG="6";try{window.__reactRouterVersion=UG}catch{}function VG(e,t){return rG({basename:void 0,future:Tf({},void 0,{v7_prependBasename:!0}),history:Pq({window:void 0}),hydrationData:WG(),routes:e,mapRouteProperties:zG,unstable_dataStrategy:void 0,unstable_patchRoutesOnMiss:void 0,window:void 0}).initialize()}function WG(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=Tf({},t,{errors:HG(t.errors)})),t}function HG(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 Cf(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 qG=p.createContext({isTransitioning:!1}),GG=p.createContext(new Map),QG="startTransition",cS=zS[QG],KG="flushSync",uS=DN[KG];function YG(e){cS?cS(e):e()}function Wl(e){uS?uS(e):e()}class XG{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 JG(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:y}=r||{},w=p.useCallback(E=>{y?YG(E):E()},[y]),b=p.useCallback((E,_)=>{let{deletedFetchers:k,unstable_flushSync:A,unstable_viewTransitionOpts:O}=_;k.forEach(N=>S.current.delete(N)),E.fetchers.forEach((N,F)=>{N.data!==void 0&&S.current.set(F,N.data)});let U=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!O||U){A?Wl(()=>i(E)):w(()=>i(E));return}if(A){Wl(()=>{h&&(d&&d.resolve(),h.skipTransition()),u({isTransitioning:!0,flushSync:!0,currentLocation:O.currentLocation,nextLocation:O.nextLocation})});let N=n.window.document.startViewTransition(()=>{Wl(()=>i(E))});N.finished.finally(()=>{Wl(()=>{f(void 0),m(void 0),l(void 0),u({isTransitioning:!1})})}),Wl(()=>m(N));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,w]);p.useLayoutEffect(()=>n.subscribe(b),[n,b]),p.useEffect(()=>{c.isTransitioning&&!c.flushSync&&f(new XG)},[c]),p.useEffect(()=>{if(d&&a&&n.window){let E=a,_=d.promise,k=n.window.document.startViewTransition(async()=>{w(()=>i(E)),await _});k.finished.finally(()=>{f(void 0),m(void 0),l(void 0),u({isTransitioning:!1})}),m(k)}},[w,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 x=p.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:E=>n.navigate(E),push:(E,_,k)=>n.navigate(E,{state:_,preventScrollReset:k==null?void 0:k.preventScrollReset}),replace:(E,_,k)=>n.navigate(E,{replace:!0,state:_,preventScrollReset:k==null?void 0:k.preventScrollReset})}),[n]),C=n.basename||"/",j=p.useMemo(()=>({router:n,navigator:x,static:!1,basename:C}),[n,x,C]),T=p.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return p.createElement(p.Fragment,null,p.createElement(Hh.Provider,{value:j},p.createElement(f2.Provider,{value:o},p.createElement(GG.Provider,{value:S.current},p.createElement(qG.Provider,{value:c},p.createElement($G,{basename:C,location:o.location,navigationType:o.historyAction,navigator:x,future:T},o.initialized||n.future.v7_partialHydration?p.createElement(ZG,{routes:n.routes,future:n.future,state:o}):t))))),null)}const ZG=p.memo(eQ);function eQ(e){let{routes:t,future:n,state:r}=e;return m2(t,void 0,r,n)}var dS;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(dS||(dS={}));var fS;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(fS||(fS={}));function b0(e){let t=p.useRef(Lg(e)),n=p.useRef(!1),r=oi(),o=p.useMemo(()=>BG(r.search,n.current?null:t.current),[r.search]),i=Qt(),a=p.useCallback((l,c)=>{const u=Lg(typeof l=="function"?l(o):l);n.current=!0,i("?"+u,c)},[i,o]);return[o,a]}const tQ=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 Cu(e,t){const n=nQ(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 nQ(e){const{name:t}=e;if(t&&t.lastIndexOf(".")!==-1&&!e.type){const r=t.split(".").pop().toLowerCase(),o=tQ.get(r);o&&Object.defineProperty(e,"type",{value:o,writable:!1,configurable:!1,enumerable:!0})}return e}var El=(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 rQ=[".DS_Store","Thumbs.db"];function oQ(e){return El(this,null,function*(){return Pf(e)&&iQ(e.dataTransfer)?cQ(e.dataTransfer,e.type):sQ(e)?aQ(e):Array.isArray(e)&&e.every(t=>"getFile"in t&&typeof t.getFile=="function")?lQ(e):[]})}function iQ(e){return Pf(e)}function sQ(e){return Pf(e)&&Pf(e.target)}function Pf(e){return typeof e=="object"&&e!==null}function aQ(e){return $g(e.target.files).map(t=>Cu(t))}function lQ(e){return El(this,null,function*(){return(yield Promise.all(e.map(n=>n.getFile()))).map(n=>Cu(n))})}function cQ(e,t){return El(this,null,function*(){if(e.items){const n=$g(e.items).filter(o=>o.kind==="file");if(t!=="drop")return n;const r=yield Promise.all(n.map(uQ));return hS(y2(r))}return hS($g(e.files).map(n=>Cu(n)))})}function hS(e){return e.filter(t=>rQ.indexOf(t.name)===-1)}function $g(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 uQ(e){if(typeof e.webkitGetAsEntry!="function")return pS(e);const t=e.webkitGetAsEntry();return t&&t.isDirectory?x2(t):pS(e)}function y2(e){return e.reduce((t,n)=>[...t,...Array.isArray(n)?y2(n):[n]],[])}function pS(e){const t=e.getAsFile();if(!t)return Promise.reject(`${e} is not a File`);const n=Cu(t);return Promise.resolve(n)}function dQ(e){return El(this,null,function*(){return e.isDirectory?x2(e):fQ(e)})}function x2(e){const t=e.createReader();return new Promise((n,r)=>{const o=[];function i(){t.readEntries(a=>El(this,null,function*(){if(a.length){const l=Promise.all(a.map(dQ));o.push(l),i()}else try{const l=yield Promise.all(o);n(l)}catch(l){r(l)}}),a=>{r(a)})}i()})}function fQ(e){return El(this,null,function*(){return new Promise((t,n)=>{e.file(r=>{const o=Cu(r,e.fullPath);t(o)},r=>{n(r)})})})}function hQ(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 pQ=Object.defineProperty,mQ=Object.defineProperties,gQ=Object.getOwnPropertyDescriptors,mS=Object.getOwnPropertySymbols,vQ=Object.prototype.hasOwnProperty,yQ=Object.prototype.propertyIsEnumerable,gS=(e,t,n)=>t in e?pQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,xQ=(e,t)=>{for(var n in t||(t={}))vQ.call(t,n)&&gS(e,n,t[n]);if(mS)for(var n of mS(t))yQ.call(t,n)&&gS(e,n,t[n]);return e},bQ=(e,t)=>mQ(e,gQ(t));const wQ="file-invalid-type",SQ="file-too-large",jQ="file-too-small",CQ="too-many-files",EQ=e=>{e=Array.isArray(e)&&e.length===1?e[0]:e;const t=Array.isArray(e)?`one of ${e.join(", ")}`:e;return{code:wQ,message:`File type must be ${t}`}},vS=e=>({code:SQ,message:`File is larger than ${e} ${e===1?"byte":"bytes"}`}),yS=e=>({code:jQ,message:`File is smaller than ${e} ${e===1?"byte":"bytes"}`}),TQ={code:CQ,message:"Too many files"};function b2(e,t){const n=e.type==="application/x-moz-file"||hQ(e,t);return[n,n?null:EQ(t)]}function w2(e,t,n){if(ls(e.size))if(ls(t)&&ls(n)){if(e.size>n)return[!1,vS(n)];if(e.size<t)return[!1,yS(t)]}else{if(ls(t)&&e.size<t)return[!1,yS(t)];if(ls(n)&&e.size>n)return[!1,vS(n)]}return[!0,null]}function ls(e){return e!=null}function PQ({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]=b2(l,t),[u]=w2(l,n,r),d=a?a(l):null;return c&&u&&!d})}function kf(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function cd(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 xS(e){e.preventDefault()}function kQ(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function RQ(e){return e.indexOf("Edge/")!==-1}function _Q(e=window.navigator.userAgent){return kQ(e)||RQ(e)}function lo(...e){return(t,...n)=>e.some(r=>(!kf(t)&&r&&r(t,...n),kf(t)))}function DQ(){return"showOpenFilePicker"in window}function IQ(e){return ls(e)?[{description:"Files",accept:Object.entries(e).filter(([n,r])=>{let o=!0;return S2(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(j2))&&(console.warn(`Skipped "${n}" because an invalid file extension was provided.`),o=!1),o}).reduce((n,[r,o])=>bQ(xQ({},n),{[r]:o}),{})}]:e}function AQ(e){if(ls(e))return Object.entries(e).reduce((t,[n,r])=>[...t,n,...r],[]).filter(t=>S2(t)||j2(t)).join(",")}function NQ(e){return e instanceof DOMException&&(e.name==="AbortError"||e.code===e.ABORT_ERR)}function MQ(e){return e instanceof DOMException&&(e.name==="SecurityError"||e.code===e.SECURITY_ERR)}function S2(e){return e==="audio/*"||e==="video/*"||e==="image/*"||e==="text/*"||/\w+\/[-+.\w]+/g.test(e)}function j2(e){return/^.*\.[\w]+$/.test(e)}var OQ=Object.defineProperty,LQ=Object.defineProperties,$Q=Object.getOwnPropertyDescriptors,Rf=Object.getOwnPropertySymbols,C2=Object.prototype.hasOwnProperty,E2=Object.prototype.propertyIsEnumerable,bS=(e,t,n)=>t in e?OQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Mn=(e,t)=>{for(var n in t||(t={}))C2.call(t,n)&&bS(e,n,t[n]);if(Rf)for(var n of Rf(t))E2.call(t,n)&&bS(e,n,t[n]);return e},pi=(e,t)=>LQ(e,$Q(t)),_f=(e,t)=>{var n={};for(var r in e)C2.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Rf)for(var r of Rf(e))t.indexOf(r)<0&&E2.call(e,r)&&(n[r]=e[r]);return n};const w0=p.forwardRef((e,t)=>{var n=e,{children:r}=n,o=_f(n,["children"]);const i=P2(o),{open:a}=i,l=_f(i,["open"]);return p.useImperativeHandle(t,()=>({open:a}),[a]),un.createElement(p.Fragment,null,r(pi(Mn({},l),{open:a})))});w0.displayName="Dropzone";const T2={disabled:!1,getFilesFromEvent:oQ,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};w0.defaultProps=T2;w0.propTypes={children:gt.func,accept:gt.objectOf(gt.arrayOf(gt.string)),multiple:gt.bool,preventDropOnDocument:gt.bool,noClick:gt.bool,noKeyboard:gt.bool,noDrag:gt.bool,noDragEventsBubbling:gt.bool,minSize:gt.number,maxSize:gt.number,maxFiles:gt.number,disabled:gt.bool,getFilesFromEvent:gt.func,onFileDialogCancel:gt.func,onFileDialogOpen:gt.func,useFsAccessApi:gt.bool,autoFocus:gt.bool,onDragEnter:gt.func,onDragLeave:gt.func,onDragOver:gt.func,onDrop:gt.func,onDropAccepted:gt.func,onDropRejected:gt.func,onError:gt.func,validator:gt.func};const Fg={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function P2(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:y,preventDropOnDocument:w,noClick:b,noKeyboard:x,noDrag:C,noDragEventsBubbling:j,onError:T,validator:E}=Mn(Mn({},T2),e),_=p.useMemo(()=>AQ(t),[t]),k=p.useMemo(()=>IQ(t),[t]),A=p.useMemo(()=>typeof v=="function"?v:wS,[v]),O=p.useMemo(()=>typeof g=="function"?g:wS,[g]),U=p.useRef(null),N=p.useRef(null),[F,D]=p.useReducer(FQ,Fg),{isFocused:R,isFileDialogActive:P}=F,$=p.useRef(typeof window<"u"&&window.isSecureContext&&S&&DQ()),L=()=>{!$.current&&P&&setTimeout(()=>{if(N.current){const{files:ne}=N.current;ne.length||(D({type:"closeDialog"}),O())}},300)};p.useEffect(()=>(window.addEventListener("focus",L,!1),()=>{window.removeEventListener("focus",L,!1)}),[N,P,O,$]);const V=p.useRef([]),K=ne=>{U.current&&U.current.contains(ne.target)||(ne.preventDefault(),V.current=[])};p.useEffect(()=>(w&&(document.addEventListener("dragover",xS,!1),document.addEventListener("drop",K,!1)),()=>{w&&(document.removeEventListener("dragover",xS),document.removeEventListener("drop",K))}),[U,w]),p.useEffect(()=>(!n&&y&&U.current&&U.current.focus(),()=>{}),[U,y,n]);const ie=p.useCallback(ne=>{T?T(ne):console.error(ne)},[T]),Re=p.useCallback(ne=>{ne.preventDefault(),ne.persist(),Z(ne),V.current=[...V.current,ne.target],cd(ne)&&Promise.resolve(r(ne)).then(pe=>{if(kf(ne)&&!j)return;const Q=pe.length,xe=Q>0&&PQ({files:pe,accept:_,minSize:i,maxSize:o,multiple:a,maxFiles:l,validator:E}),Be=Q>0&&!xe;D({isDragAccept:xe,isDragReject:Be,isDragActive:!0,type:"setDraggedFiles"}),c&&c(ne)}).catch(pe=>ie(pe))},[r,c,ie,j,_,i,o,a,l,E]),ae=p.useCallback(ne=>{ne.preventDefault(),ne.persist(),Z(ne);const pe=cd(ne);if(pe&&ne.dataTransfer)try{ne.dataTransfer.dropEffect="copy"}catch{}return pe&&d&&d(ne),!1},[d,j]),Ee=p.useCallback(ne=>{ne.preventDefault(),ne.persist(),Z(ne);const pe=V.current.filter(xe=>U.current&&U.current.contains(xe)),Q=pe.indexOf(ne.target);Q!==-1&&pe.splice(Q,1),V.current=pe,!(pe.length>0)&&(D({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),cd(ne)&&u&&u(ne))},[U,u,j]),Fe=p.useCallback((ne,pe)=>{const Q=[],xe=[];ne.forEach(Be=>{const[Nt,Pt]=b2(Be,_),[$t,St]=w2(Be,i,o),Sn=E?E(Be):null;if(Nt&&$t&&!Sn)Q.push(Be);else{let rr=[Pt,St];Sn&&(rr=rr.concat(Sn)),xe.push({file:Be,errors:rr.filter(Ki=>Ki)})}}),(!a&&Q.length>1||a&&l>=1&&Q.length>l)&&(Q.forEach(Be=>{xe.push({file:Be,errors:[TQ]})}),Q.splice(0)),D({acceptedFiles:Q,fileRejections:xe,type:"setFiles"}),f&&f(Q,xe,pe),xe.length>0&&m&&m(xe,pe),Q.length>0&&h&&h(Q,pe)},[D,a,_,i,o,l,f,h,m,E]),me=p.useCallback(ne=>{ne.preventDefault(),ne.persist(),Z(ne),V.current=[],cd(ne)&&Promise.resolve(r(ne)).then(pe=>{kf(ne)&&!j||Fe(pe,ne)}).catch(pe=>ie(pe)),D({type:"reset"})},[r,Fe,ie,j]),Le=p.useCallback(()=>{if($.current){D({type:"openDialog"}),A();const ne={multiple:a,types:k};window.showOpenFilePicker(ne).then(pe=>r(pe)).then(pe=>{Fe(pe,null),D({type:"closeDialog"})}).catch(pe=>{NQ(pe)?(O(pe),D({type:"closeDialog"})):MQ(pe)?($.current=!1,N.current?(N.current.value=null,N.current.click()):ie(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."))):ie(pe)});return}N.current&&(D({type:"openDialog"}),A(),N.current.value=null,N.current.click())},[D,A,O,S,Fe,ie,k,a]),nt=p.useCallback(ne=>{!U.current||!U.current.isEqualNode(ne.target)||(ne.key===" "||ne.key==="Enter"||ne.keyCode===32||ne.keyCode===13)&&(ne.preventDefault(),Le())},[U,Le]),Tt=p.useCallback(()=>{D({type:"focus"})},[]),Ve=p.useCallback(()=>{D({type:"blur"})},[]),Te=p.useCallback(()=>{b||(_Q()?setTimeout(Le,0):Le())},[b,Le]),Pe=ne=>n?null:ne,Xe=ne=>x?null:Pe(ne),Qe=ne=>C?null:Pe(ne),Z=ne=>{j&&ne.stopPropagation()},ue=p.useMemo(()=>(ne={})=>{var pe=ne,{refKey:Q="ref",role:xe,onKeyDown:Be,onFocus:Nt,onBlur:Pt,onClick:$t,onDragEnter:St,onDragOver:Sn,onDragLeave:rr,onDrop:Ki}=pe,vr=_f(pe,["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"]);return Mn(Mn({onKeyDown:Xe(lo(Be,nt)),onFocus:Xe(lo(Nt,Tt)),onBlur:Xe(lo(Pt,Ve)),onClick:Pe(lo($t,Te)),onDragEnter:Qe(lo(St,Re)),onDragOver:Qe(lo(Sn,ae)),onDragLeave:Qe(lo(rr,Ee)),onDrop:Qe(lo(Ki,me)),role:typeof xe=="string"&&xe!==""?xe:"presentation",[Q]:U},!n&&!x?{tabIndex:0}:{}),vr)},[U,nt,Tt,Ve,Te,Re,ae,Ee,me,x,C,n]),Se=p.useCallback(ne=>{ne.stopPropagation()},[]),He=p.useMemo(()=>(ne={})=>{var pe=ne,{refKey:Q="ref",onChange:xe,onClick:Be}=pe,Nt=_f(pe,["refKey","onChange","onClick"]);const Pt={accept:_,multiple:a,type:"file",style:{display:"none"},onChange:Pe(lo(xe,me)),onClick:Pe(lo(Be,Se)),tabIndex:-1,[Q]:N};return Mn(Mn({},Pt),Nt)},[N,t,a,me,n]);return pi(Mn({},F),{isFocused:R&&!n,getRootProps:ue,getInputProps:He,rootRef:U,inputRef:N,open:Pe(Le)})}function FQ(e,t){switch(t.type){case"focus":return pi(Mn({},e),{isFocused:!0});case"blur":return pi(Mn({},e),{isFocused:!1});case"openDialog":return pi(Mn({},Fg),{isFileDialogActive:!0});case"closeDialog":return pi(Mn({},e),{isFileDialogActive:!1});case"setDraggedFiles":return pi(Mn({},e),{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return pi(Mn({},e),{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return Mn({},Fg);default:return e}}function wS(){}const[zQ,BQ]=Bn("Dropzone component was not found in tree");function S0(e){const t=n=>{const{children:r,...o}=W(`Dropzone${L0(e)}`,{},n),i=BQ(),a=qo(r)?r:s.jsx("span",{children:r});return i[e]?p.cloneElement(a,o):null};return t.displayName=`@mantine/dropzone/${L0(e)}`,t}const UQ=S0("accept"),VQ=S0("reject"),WQ=S0("idle");var Vc={root:"m_d46a4834",inner:"m_b85f7144",fullScreen:"m_96f6e9ad",dropzone:"m_7946116d"};const HQ={loading:!1,multiple:!0,maxSize:1/0,autoFocus:!1,activateOnClick:!0,activateOnDrag:!0,dragEventsBubbling:!0,activateOnKeyboard:!0,useFsAccessApi:!0,variant:"light",rejectColor:"red"},qQ=(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":lt(t),"--dropzone-accept-color":i.color,"--dropzone-accept-bg":i.background,"--dropzone-reject-color":a.color,"--dropzone-reject-bg":a.background}}},Gi=X((e,t)=>{const n=W("Dropzone",HQ,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:y,onReject:w,openRef:b,name:x,maxFiles:C,autoFocus:j,activateOnClick:T,activateOnDrag:E,dragEventsBubbling:_,activateOnKeyboard:k,onDragEnter:A,onDragLeave:O,onDragOver:U,onFileDialogCancel:N,onFileDialogOpen:F,preventDropOnDocument:D,useFsAccessApi:R,getFilesFromEvent:P,validator:$,rejectColor:L,acceptColor:V,enablePointerEvents:K,loaderProps:ie,inputProps:Re,mod:ae,...Ee}=n,Fe=ce({name:"Dropzone",classes:Vc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:qQ}),{getRootProps:me,getInputProps:Le,isDragAccept:nt,isDragReject:Tt,open:Ve}=P2({onDrop:S,onDropAccepted:y,onDropRejected:w,disabled:d||f,accept:Array.isArray(g)?g.reduce((Pe,Xe)=>({...Pe,[Xe]:[]}),{}):g,multiple:h,maxSize:m,maxFiles:C,autoFocus:j,noClick:!T,noDrag:!E,noDragEventsBubbling:!_,noKeyboard:!k,onDragEnter:A,onDragLeave:O,onDragOver:U,onFileDialogCancel:N,onFileDialogOpen:F,preventDropOnDocument:D,useFsAccessApi:R,validator:$,...P?{getFilesFromEvent:P}:null});Mf(b,Ve);const Te=!nt&&!Tt;return s.jsx(zQ,{value:{accept:nt,reject:Tt,idle:Te},children:s.jsxs(q,{...me(),...Fe("root",{focusable:!0}),...Ee,mod:[{accept:nt,reject:Tt,idle:Te,loading:f,"activate-on-click":T},ae],children:[s.jsx(qy,{visible:f,overlayProps:{radius:u},unstyled:l,loaderProps:ie}),s.jsx("input",{...Le(Re),name:x}),s.jsx("div",{...Fe("inner"),ref:t,"data-enable-pointer-events":K||void 0,children:v})]})})});Gi.classes=Vc;Gi.displayName="@mantine/dropzone/Dropzone";Gi.Accept=UQ;Gi.Idle=WQ;Gi.Reject=VQ;const GQ={loading:!1,maxSize:1/0,activateOnClick:!1,activateOnDrag:!0,dragEventsBubbling:!0,activateOnKeyboard:!0,active:!0,zIndex:eo("max"),withinPortal:!0},j0=X((e,t)=>{const n=W("DropzoneFullScreen",GQ,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=ce({name:"DropzoneFullScreen",classes:Vc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,rootSelector:"fullScreen"}),{resolvedClassNames:y,resolvedStyles:w}=Hc({classNames:r,styles:a,props:n}),[b,x]=p.useState(0),[C,{open:j,close:T}]=Zg(!1),E=k=>{var A;(A=k.dataTransfer)!=null&&A.types.includes("Files")&&(x(O=>O+1),j())},_=()=>{x(k=>k-1)};return p.useEffect(()=>{b===0&&T()},[b]),p.useEffect(()=>{if(u)return document.addEventListener("dragenter",E,!1),document.addEventListener("dragleave",_,!1),()=>{document.removeEventListener("dragenter",E,!1),document.removeEventListener("dragleave",_,!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(Gi,{...v,classNames:y,styles:w,unstyled:l,className:Vc.dropzone,onDrop:k=>{d==null||d(k),T(),x(0)},onReject:k=>{f==null||f(k),T(),x(0)}})})})});j0.classes=Vc;j0.displayName="@mantine/dropzone/DropzoneFullScreen";Gi.FullScreen=j0;const ud=Gi,QQ='{"resourceType": "Bundle"}';function nm({id:e,title:t,message:n,color:r,icon:o,withCloseButton:i=!1,method:a="show",loading:l}){vo[a]({id:e,loading:l,title:t,message:n,color:r,icon:o,withCloseButton:i,autoClose:!1})}function KQ(){const e=At(),t=se(),[n,r]=p.useState({}),o=p.useCallback(async(l,c)=>{const u="batch-upload";nm({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=xk(d));const f=await t.executeBatch(d);r(h=>({...h,[c]:f})),nm({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){nm({id:u,title:"Batch Upload Failed",color:"red",message:De(d),method:"update",icon:s.jsx(xf,{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(Ne,{children:[s.jsx(ge,{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(ud,{onDrop:i,accept:["application/json"],children:s.jsxs(te,{justify:"center",gap:"xl",style:{minHeight:220,pointerEvents:"none"},children:[s.jsx(ud.Accept,{children:s.jsx(jw,{size:50,stroke:1.5,color:e.colors[e.primaryColor][5]})}),s.jsx(ud.Reject,{children:s.jsx(xf,{size:50,stroke:1.5,color:e.colors.red[5]})}),s.jsx(ud.Idle,{children:s.jsx(jw,{size:50,stroke:1.5})}),s.jsxs("div",{children:[s.jsx(fe,{size:"xl",inline:!0,children:"Drag files here or click to select files"}),s.jsx(fe,{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(Ke,{onSubmit:a,children:[s.jsx(pl,{"data-testid":"batch-input",name:"input",autosize:!0,minRows:20,defaultValue:QQ,deserialize:JSON.parse}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(oe,{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(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(oe,{onClick:()=>r({}),children:"Start over"})})]})]})}function YQ(){const{resourceType:e}=ct(),n=(Object.fromEntries(new URLSearchParams(location.search).entries()).ids||"").split(",").filter(o=>!!o),[r]=ol("Questionnaire",`subject-type=${e}`);return r?r.length===0?s.jsxs(Ne,{children:[s.jsxs(ge,{children:["No apps for ",e]}),s.jsx(Ge,{to:`/${e}`,children:"Return to search page"})]}):s.jsx(Ne,{children:s.jsx("div",{children:r.map(o=>s.jsxs("div",{children:[s.jsx("h3",{children:s.jsx(Ge,{to:`/forms/${o.id}?subject=`+n.map(i=>`${e}/${i}`).join(","),children:o.name})}),s.jsx("p",{children:o.description})]},o.id))})}):s.jsx(Jr,{})}function XQ(){const e=se(),[t,n]=p.useState(),[r,o]=p.useState(!1);return s.jsx(Ne,{width:450,children:s.jsxs(Ke,{onSubmit:i=>{n(void 0),e.post("auth/changepassword",i).then(()=>o(!0)).catch(a=>n(ht(a)))},children:[s.jsxs(mn,{style:{flexDirection:"column"},children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Change password"})]}),!r&&s.jsxs(Oe,{gap:"xl",mt:"xl",children:[s.jsx(Qr,{name:"oldPassword",label:"Old password",required:!0,autoFocus:!0,error:Je(t,"oldPassword")}),s.jsx(Qr,{name:"newPassword",label:"New password",required:!0,error:Je(t,"newPassword")}),s.jsx(Qr,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Je(t,"confirmPassword")}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(oe,{type:"submit",children:"Change password"})})]}),r&&s.jsx("div",{"data-testid":"success",children:"Password changed successfully"})]})})}const zg=["Form","JSON","Profiles"],JQ=["Profiles"],rm=zg[0].toLowerCase();function ZQ(){const e=Qt(),t=At(),{resourceType:n}=ct(),[r,o]=p.useState(()=>{const a=window.location.pathname.split("/").pop();return a&&zg.map(l=>l.toLowerCase()).includes(a)?a:rm});function i(a){a||(a=rm),o(a),e(`/${n}/new/${a}`)}return s.jsxs(s.Fragment,{children:[s.jsxs(Yn,{children:[s.jsxs(fe,{p:"md",fw:500,children:["New ",n]}),s.jsx(Ir,{children:s.jsx(et,{defaultValue:rm,value:r,onChange:i,children:s.jsx(et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:zg.map(a=>s.jsx(et.Tab,{value:a.toLowerCase(),px:"md",children:JQ.includes(a)?s.jsxs(te,{gap:"xs",wrap:"nowrap",children:[a,s.jsx(ru,{color:t.primaryColor,size:"sm",children:"Beta"})]}):a},a))})})})]}),s.jsx(x0,{})]})}function eK(){return s.jsx(Ne,{children:s.jsxs(Oe,{children:[s.jsx(ge,{order:1,children:"Unexpected Error"}),s.jsx(fe,{children:"We're sorry, something went wrong."}),s.jsxs(fe,{children:["Please contact ",s.jsx(Ze,{href:"mailto:support@medplum.com",children:"support"})," for assistance."]})]})})}const tK="_root_1fbwr_1",nK="_entry_1fbwr_8",rK="_key_1fbwr_13",oK="_value_1fbwr_20",Kh={root:tK,entry:nK,key:rK,value:oK};function ze(e){return s.jsx(Ir,{children:s.jsx("div",{className:Kh.root,children:e.children})})}ze.Entry=function(t){return s.jsx("div",{className:Kh.entry,children:t.children})};ze.Key=function(t){return s.jsx("div",{className:Kh.key,children:t.children})};ze.Value=function(t){return s.jsx("div",{className:Kh.value,children:t.children})};function iK(e){if(e.gender==="male")return"blue";if(e.gender==="female")return"pink"}function k2(e){var n,r;const t=wt(e.patient);return t?s.jsxs(ze,{children:[s.jsx(Hi,{value:t,size:"lg",color:iK(t)}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Name"}),s.jsx(ze.Value,{children:s.jsx(Ge,{to:t,fw:500,children:t.name?s.jsx(qx,{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:i6(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 R2(e){const t=wt(e.resource);if(!t)return null;const n=[{key:"Type",value:s.jsx(Ge,{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!==st(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 C0(e){if(e.resourceType==="Patient")return e;if(e.resourceType==="DiagnosticReport"||e.resourceType==="Encounter"||e.resourceType==="Observation"||e.resourceType==="ServiceRequest")return e.subject}function sK(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 Dd(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 nl((t=e.getActiveLogin())==null?void 0:t.project)}function aK(e,t){const n=new Blob([e],{type:on.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}=ct(),t=oi(),r=Object.fromEntries(new URLSearchParams(t.search).entries()).subject,o=se(),[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 b={resourceType:"Bundle",type:"batch",entry:[{request:{method:"GET",url:`Questionnaire/${e}`}}]};if(r){const x=r.split(",").filter(C=>!!C);x.length===1&&b.entry.push({request:{method:"GET",url:x[0]}}),d(x)}o.executeBatch(b).then(x=>{var C,j,T,E,_,k,A,O;((T=(j=(C=x.entry)==null?void 0:C[0])==null?void 0:j.response)==null?void 0:T.status)!=="200"?g((k=(_=(E=x.entry)==null?void 0:E[0])==null?void 0:_.response)==null?void 0:k.outcome):(c((A=x.entry[0])==null?void 0:A.resource),h((O=x.entry[1])==null?void 0:O.resource)),a(!1)}).catch(x=>{g(x),a(!1)})},[o,e,r]),m)return s.jsx(Ne,{children:s.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)})});if(v)return s.jsxs(Ne,{children:[s.jsx(ge,{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(Ge,{to:v[0],children:"Review your answers"})}),v.length>1&&s.jsxs("li",{children:["Review your answers:",s.jsx("ul",{children:v.map(b=>s.jsx("li",{children:s.jsx(Ge,{to:b,children:st(b)})},b.id))})]}),f&&s.jsx("li",{children:s.jsxs(Ge,{to:f,children:["Back to ",Wo(f)]})}),s.jsx("li",{children:s.jsx(Ge,{to:"/",children:"Go back home"})})]})]});if(i||!l)return s.jsx(Jr,{});const y=f&&C0(f);return s.jsxs(s.Fragment,{children:[s.jsxs(Yn,{shadow:"xs",radius:0,children:[y&&s.jsx(k2,{patient:y}),f&&f.resourceType!=="Patient"&&s.jsx(R2,{resource:f}),s.jsx(q,{px:"xl",py:"md",children:s.jsxs(fe,{children:[Wo(l),u&&u.length>1&&s.jsxs(s.Fragment,{children:[" (for ",u.length," resources)"]})]})})]}),s.jsx(Ne,{children:s.jsx(VR,{questionnaire:l,subject:f&&Et(f),onSubmit:w})})]});async function w(b){const x=[];if(!u||u.length===0)x.push(await o.createResource(b));else for(const C of u)x.push(await o.createResource({...b,subject:{reference:C}}));S(x)}}const cK="_paper_unw9o_1",uK={paper:cK},dK={Bot:"/admin/bots/new",ClientApplication:"/admin/clients/new"};function _2(e,t){const n=e.resourceType||fK(t),r=e.fields??hK(n),o=e.filters??(e.resourceType?void 0:pK(n)),i=e.sortRules??mK(n),a=e.offset??0,l=e.count??Ah;return{...e,resourceType:n,fields:r,filters:o,sortRules:i,offset:a,count:l}}function fK(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 hK(e){const t=E0(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 pK(e){var t;return(t=E0(e))==null?void 0:t.filters}function mK(e){const t=E0(e);return t!=null&&t.sortRules?t.sortRules:[{code:"_lastUpdated",descending:!0}]}function E0(e){const t=localStorage.getItem(e+"-defaultSearch");return t?JSON.parse(t):void 0}function gK(e){localStorage.setItem("defaultResourceType",e.resourceType),localStorage.setItem(e.resourceType+"-defaultSearch",JSON.stringify(e))}async function vK(e,t){const n={resourceType:e.resourceType,count:1e3,offset:0,filters:e.filters},r=_2(n,t.getUserConfiguration()),o=await t.search(r.resourceType,Ra({...r,total:"accurate",fields:void 0}));return xk(o)}function SS(){const e=se(),t=Qt(),n=oi(),[r,o]=p.useState();return p.useEffect(()=>{const i=pk(n.pathname+n.search),a=_2(i,e.getUserConfiguration());n.pathname===`/${a.resourceType}`&&n.search===Ra(a)?(gK(a),o(a)):t(`/${a.resourceType}${Ra(a)}`)},[e,t,n]),!(r!=null&&r.resourceType)||!r.fields||r.fields.length===0?s.jsx(Jr,{}):s.jsx(Yn,{shadow:"xs",m:"md",p:"xs",className:uK.paper,children:s.jsx(wu,{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}${Ra(i.definition)}`)},onNew:()=>{t(dK[r.resourceType]??`/${r.resourceType}/new`)},onExportCsv:()=>{const i=e.fhirUrl(r.resourceType,"$csv")+Ra(r);e.download(i).then(a=>{window.open(window.URL.createObjectURL(a),"_blank")}).catch(a=>he({color:"red",message:De(a),autoClose:!1}))},onExportTransactionBundle:async()=>{vK(r,e).then(i=>aK(JSON.stringify(i,void 0,2))).catch(i=>he({color:"red",message:De(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=>he({color:"red",message:De(a),autoClose:!1})))},onBulk:i=>{t(`/bulk/${r.resourceType}?ids=${i.join(",")}`)}})})}function yK(){const e=se(),[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=>he({color:"red",message:De(l),autoClose:!1}))},[e]);const i=p.useCallback(l=>{e.post("auth/mfa/enroll",l).then(()=>{o(!0),he({color:"green",message:"Success"})}).catch(c=>he({color:"red",message:De(c),autoClose:!1}))},[e]),a=p.useCallback(()=>{e.post("auth/mfa/disable",{}).catch(console.log)},[e]);return r===void 0?null:r?s.jsx(Ne,{children:s.jsxs(te,{children:[s.jsx(ge,{children:"MFA is enabled"}),s.jsx(oe,{onClick:a,children:"Disable MFA"})]})}):s.jsx(Ne,{width:400,children:s.jsxs(Ke,{onSubmit:i,children:[s.jsx(ge,{children:"Multi Factor Auth Setup"}),s.jsx(mn,{children:s.jsx("img",{src:t})}),s.jsx(ve,{name:"token",label:"Code"}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{type:"submit",children:"Enroll"})})]})})}const om={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.8-b2b7ed8c5",MODE:"production",PROD:!0,RECAPTCHA_SITE_KEY:"__RECAPTCHA_SITE_KEY__",SSR:!1},Bg={baseUrl:"__MEDPLUM_BASE_URL__",clientId:"__MEDPLUM_CLIENT_ID__",googleClientId:"__GOOGLE_CLIENT_ID__",recaptchaSiteKey:"__RECAPTCHA_SITE_KEY__",registerEnabled:"__MEDPLUM_REGISTER_ENABLED__",awsTextractEnabled:om==null?void 0:om.MEDPLUM_AWS_TEXTRACT_ENABLED};function Eu(){return Bg}function D2(){return I2("registerEnabled")}function xK(){return I2("awsTextractEnabled")}function I2(e){try{return Bg[e]!==!1&&Bg[e]!=="false"}catch{return!0}}function bK(){const e=Qt(),[t]=b0(),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(JR,{onCode:o,onForgotPassword:()=>e("/resetpassword"),onRegister:()=>e("/register"),googleClientId:Eu().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(ro,{size:32}),s.jsx(ge,{children:"Sign in to Medplum"})]})}function wK(){const e=se(),t=Qt(),n=Eu();return p.useEffect(()=>{e.getProfile()&&t("/signin?project=new")},[e,t]),D2()?s.jsxs(xq,{type:"project",projectId:"new",onSuccess:()=>t("/"),googleClientId:n.googleClientId,recaptchaSiteKey:n.recaptchaSiteKey,children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Create a new account"})]}):s.jsx(Ne,{width:450,children:s.jsx(Vi,{icon:s.jsx(Sl,{size:16}),title:"New projects disabled",color:"red",children:"New projects are disabled on this server."})})}function SK(){const e=Qt(),t=se(),[n,r]=p.useState(),[o,i]=p.useState(!1),a=Eu().recaptchaSiteKey;return p.useEffect(()=>{a&&YR(a)},[a]),s.jsx(Ne,{width:450,children:s.jsxs(Ke,{onSubmit:async l=>{let c="";a&&(c=await XR(a)),t.post("auth/resetpassword",{...l,recaptchaToken:c}).then(()=>i(!0)).catch(u=>r(ht(u)))},children:[s.jsxs(Oe,{gap:"lg",mb:"xl",align:"center",children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Medplum Password Reset"})]}),s.jsxs(Oe,{gap:"xl",children:[s.jsx(Mr,{issues:vu(n,void 0)}),!o&&s.jsxs(s.Fragment,{children:[s.jsx(ve,{name:"email",type:"email",label:"Email",required:!0,autoFocus:!0,error:Je(n,"email")}),s.jsxs(te,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[s.jsx(Ze,{component:"button",type:"button",color:"dimmed",onClick:()=>e("/register"),size:"xs",children:"Register"}),s.jsx(oe,{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=Qt(),t=se(),[n,r]=p.useState();p.useEffect(()=>{t.get("auth/me").then(r).catch(a=>he({color:"red",message:De(a),autoClose:!1}))},[t]);function o(a){t.post("auth/revoke",{loginId:a}).then(()=>t.get("auth/me",{cache:"no-cache"})).then(r).then(()=>he({color:"green",message:"Login revoked"})).catch(l=>he({color:"red",message:De(l),autoClose:!1}))}return n?s.jsxs(s.Fragment,{children:[s.jsxs(Ne,{children:[s.jsx(ge,{children:"Security"}),s.jsxs(Yx,{children:[s.jsx(No,{term:"ID",children:s.jsx(Ze,{href:`/${st(n.profile)}`,children:n.profile.id})}),s.jsx(No,{term:"Resource Type",children:n.profile.resourceType}),s.jsx(No,{term:"Name",children:fu((i=n.profile.name)==null?void 0:i[0])})]})]}),s.jsxs(Ne,{children:[s.jsx(ge,{children:"Sessions"}),s.jsxs(de,{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:Fn(a.lastUpdated)}),s.jsx("td",{children:s.jsx(Ze,{href:"#",onClick:()=>o(a.id),children:"Revoke"})})]},a.id))})]})]}),s.jsxs(Ne,{children:[s.jsx(ge,{children:"Password"}),s.jsx(oe,{onClick:()=>e("/changepassword"),children:"Change password"})]}),s.jsxs(Ne,{children:[s.jsx(ge,{children:"Multi Factor Auth"}),s.jsxs("p",{children:["Enrolled: ",n.security.mfaEnrolled.toString()]}),!n.security.mfaEnrolled&&s.jsx(oe,{onClick:()=>e("/mfa"),children:"Enroll"})]})]}):null}function CK(){const{id:e,secret:t}=ct(),n=se(),[r,o]=p.useState(),[i,a]=p.useState(!1),l=vu(r,void 0);return s.jsxs(Ne,{width:450,children:[s.jsx(Mr,{issues:l}),s.jsxs(Ke,{onSubmit:c=>{if(c.password!==c.confirmPassword){o(Ri("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(ht(d)))},children:[s.jsxs(mn,{style:{flexDirection:"column"},children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Set password"})]}),!i&&s.jsxs(Oe,{children:[s.jsx(Qr,{name:"password",label:"New password",required:!0,error:Je(r,"password")}),s.jsx(Qr,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Je(r,"confirmPassword")}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{type:"submit",children:"Set password"})})]}),i&&s.jsxs("div",{"data-testid":"success",children:["Password set. You can now ",s.jsx(Ge,{to:"/signin",children:"sign in"}),"."]})]})]})}function EK(){const e=$h(),t=Qt(),[n]=b0(),r=Eu(),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(JR,{onSuccess:()=>o(),onForgotPassword:()=>t("/resetpassword"),onRegister:D2()?()=>t("/register"):void 0,googleClientId:r.googleClientId,login:n.get("login")||void 0,projectId:n.get("project")||void 0,children:[s.jsx(ro,{size:32}),s.jsx(ge,{children:"Sign in to Medplum"}),n.get("project")==="new"&&s.jsx("div",{children:"Sign in again to create a new project"})]})}function TK(){const e=Qt(),t=oi(),[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(jW,{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 Yh(e){const t=se(),n=Qi(t),r=Qt(),[o,i]=p.useState({resourceType:"ProjectMembership",filters:[{code:"project",operator:re.EQUALS,value:"Project/"+n},{code:"profile-type",operator:re.EQUALS,value:e.resourceType}],fields:e.fields,count:100});return s.jsx(wu,{search:o,onClick:a=>r(`/admin/members/${a.resource.id}`),onChange:a=>i(a.definition),hideFilters:!0,hideToolbar:!0})}function PK(){return s.jsxs(s.Fragment,{children:[s.jsx(ge,{children:"Bots"}),s.jsx(Yh,{resourceType:"Bot",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(Ge,{to:"/admin/bots/new",children:"Create new bot"})})]})}function kK(){return s.jsxs(s.Fragment,{children:[s.jsx(ge,{children:"Clients"}),s.jsx(Yh,{resourceType:"ClientApplication",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(Ge,{to:"/admin/clients/new",children:"Create new client"})})]})}function Xh(e){return s.jsx(Ys,{resourceType:"AccessPolicy",name:"accessPolicy",defaultValue:e.defaultValue,placeholder:"Access Policy",onChange:t=>{ni(t)?e.onChange(Et(t)):e.onChange(void 0)}})}function RK(){const e=se(),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(ge,{children:"Create new Bot"}),s.jsxs(Ke,{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),he({color:"green",message:"Bot created"})}).catch(m=>{he({color:"red",message:De(m),autoClose:!1}),u(ht(m))})},children:[!d&&s.jsxs(Oe,{children:[s.jsx(vt,{title:"Name",htmlFor:"name",outcome:c,children:s.jsx(ve,{id:"name",name:"name",required:!0,autoFocus:!0,onChange:h=>r(h.currentTarget.value),error:Je(c,"name")})}),s.jsx(vt,{title:"Description",htmlFor:"description",outcome:c,children:s.jsx(ve,{id:"description",name:"description",onChange:h=>i(h.currentTarget.value),error:Je(c,"description")})}),s.jsx(vt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:c,children:s.jsx(Xh,{name:"accessPolicy",onChange:l})}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{type:"submit",children:"Create Bot"})})]}),d&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(fe,{children:"Bot created"}),s.jsxs(Ln,{children:[s.jsx(Ln.Item,{children:s.jsx(Ge,{to:d,children:"Go to new bot"})}),s.jsx(Ln.Item,{children:s.jsx(Ge,{to:"/admin/bots",children:"Back to bots list"})})]})]})]})]})}function _K(){const e=se(),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(ge,{children:"Create new Client"}),s.jsxs(Ke,{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),he({color:"green",message:"Client created"})}).catch(v=>{he({color:"red",message:De(v),autoClose:!1}),f(ht(v))})},children:[!h&&s.jsxs(Oe,{children:[s.jsx(vt,{title:"Name",htmlFor:"name",outcome:d,children:s.jsx(ve,{id:"name",name:"name",required:!0,autoFocus:!0,onChange:g=>r(g.currentTarget.value),error:Je(d,"name")})}),s.jsx(vt,{title:"Description",htmlFor:"description",outcome:d,children:s.jsx(ve,{id:"description",name:"description",onChange:g=>i(g.currentTarget.value),error:Je(d,"description")})}),s.jsx(vt,{title:"Redirect URI",htmlFor:"redirectUri",outcome:d,children:s.jsx(ve,{id:"redirectUri",name:"redirectUri",onChange:g=>l(g.currentTarget.value),error:Je(d,"redirectUri")})}),s.jsx(vt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:d,children:s.jsx(Xh,{name:"accessPolicy",onChange:u})}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{type:"submit",children:"Create Client"})})]}),h&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(fe,{children:"Client created"}),s.jsxs(Ln,{children:[s.jsx(Ln.Item,{children:s.jsx(Ge,{to:h,children:"Go to new client"})}),s.jsx(Ln.Item,{children:s.jsx(Ge,{to:"/admin/clients",children:"Back to clients list"})})]})]})]})]})}function DK(e){return s.jsx(Ys,{resourceType:"UserConfiguration",name:"userConfiguration",defaultValue:e.defaultValue,placeholder:"User Configuration",onChange:t=>{ni(t)?e.onChange(Et(t)):e.onChange(void 0)}})}function IK(){const{membershipId:e}=ct(),t=se(),n=Qi(t),r=Qt(),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(ht(S)))}return s.jsxs(s.Fragment,{children:[s.jsx(ge,{children:"Edit membership"}),s.jsx("h3",{children:s.jsx(Ua,{value:o.profile,link:!0})}),s.jsxs(Ke,{onSubmit:()=>{const S={...o,accessPolicy:i,userConfiguration:l,admin:u};t.post(`admin/projects/${n}/members/${e}`,S).then(()=>g(!0)).catch(y=>h(ht(y)))},children:[!m&&s.jsxs(Oe,{children:[s.jsx(vt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:f,children:s.jsx(Xh,{name:"accessPolicy",defaultValue:i,onChange:a})}),s.jsx(vt,{title:"User Configuration",htmlFor:"userConfiguration",outcome:f,children:s.jsx(DK,{name:"userConfiguration",defaultValue:l,onChange:c})}),s.jsx(vt,{title:"Admin",htmlFor:"admin",outcome:f,children:s.jsx(_n,{id:"admin",name:"admin",defaultChecked:u,onChange:S=>d(S.currentTarget.checked)})}),s.jsxs(te,{justify:"flex-end",mt:"xl",children:[s.jsx(oe,{type:"submit",children:"Save"}),s.jsx(oe,{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(Ge,{to:"/admin/project",children:"here"})," to return to the project admin page."]})]})]})]})}function AK(){const e=se(),[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"),_h(g)?a(g):d(g),c(m.sendEmail??!1),he({color:"green",message:"Invite success"})}).catch(g=>{he({color:"red",message:De(g),autoClose:!1}),a(ht(g))})},[e,t,r]);return s.jsxs(Ke,{onSubmit:f,children:[!u&&!i&&s.jsxs(Oe,{children:[s.jsx(ge,{children:"Invite new member"}),e.isSuperAdmin()&&s.jsx(vt,{title:"Project",htmlFor:"project",outcome:i,children:s.jsx(Ys,{resourceType:"Project",name:"project",defaultValue:t,onChange:n})}),s.jsx(It,{name:"resourceType",label:"Role",defaultValue:"Practitioner",data:["Practitioner","Patient","RelatedPerson"],error:Je(i,"resourceType")}),s.jsx(ve,{name:"firstName",label:"First Name",required:!0,autoFocus:!0,error:Je(i,"firstName")}),s.jsx(ve,{name:"lastName",label:"Last Name",required:!0,error:Je(i,"lastName")}),s.jsx(ve,{name:"email",type:"email",label:"Email",required:!0,error:Je(i,"email")}),s.jsx(vt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:i,children:s.jsx(Xh,{name:"accessPolicy",onChange:o})}),s.jsx(_n,{name:"sendEmail",label:"Send email",defaultChecked:!0}),s.jsx(_n,{name:"isAdmin",label:"Admin"}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{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(Ge,{to:"/admin/project",children:"here"})," to return to the project admin page."]})]}),u&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(fe,{children:"User created"}),l&&s.jsx(fe,{children:"Email sent"}),s.jsxs(Ln,{children:[s.jsx(Ln.Item,{children:s.jsx(Ge,{to:u,children:"Go to new membership"})}),s.jsx(Ln.Item,{children:s.jsx(Ge,{to:u.profile,children:"Go to new profile"})}),s.jsx(Ln.Item,{children:s.jsx(Ge,{to:"/admin/users",children:"Back to users list"})})]})]})]})}function NK(){return s.jsxs(s.Fragment,{children:[s.jsx(ge,{children:"Patients"}),s.jsx(Yh,{resourceType:"Patient",fields:["user","profile","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(Ge,{to:"/admin/invite",children:"Invite new patient"})})]})}function MK(){const e=se();if(!e.isLoading()&&!e.isProjectAdmin())return s.jsx(Mr,{outcome:BP});function t(n){e.post("admin/projects/setpassword",n).then(()=>he({color:"green",message:"Done"})).catch(r=>he({color:"red",message:De(r),autoClose:!1}))}return s.jsxs(Ne,{width:600,children:[s.jsx(ge,{order:1,children:"Project Admin"}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{order:2,children:"Force Set Password"}),s.jsx(fe,{children:"Sets the password for the specified user in this project."}),s.jsx(fe,{children:"This action can only be performed by project administrators. Passwords can only be set for users scoped in this project."}),s.jsx(Ke,{onSubmit:t,children:s.jsxs(Oe,{children:[s.jsx(ve,{name:"email",label:"Email",required:!0}),s.jsx(Qr,{name:"password",label:"Password",required:!0}),s.jsx(oe,{type:"submit",children:"Force Set Password"})]})})]})}function jS(){const e=se(),t=Qi(e),n=e.get(`admin/projects/${t}`).read();return s.jsxs(s.Fragment,{children:[s.jsx(ge,{children:"Details"}),s.jsxs(Yx,{children:[s.jsx(No,{term:"ID",children:n.project.id}),s.jsx(No,{term:"Name",children:n.project.name})]})]})}const CS=["Details","Users","Patients","Clients","Bots","Secrets","Sites"];function OK(){const e=Qt(),n=oi().pathname.replace("/admin/","")||CS[0],r=se(),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(Yn,{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(Ir,{children:s.jsx(et,{value:n.toLowerCase(),onChange:a,children:s.jsx(et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:CS.map(l=>s.jsx(et.Tab,{value:l.toLowerCase(),children:l},l))})})})]}),s.jsx(Ne,{children:s.jsx(x0,{})})]})}function LK(){const e=se(),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(Xr(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(()=>he({color:"green",message:"Saved"})).catch(console.log)},children:[s.jsx(ge,{children:"Project Secrets"}),s.jsx("p",{children:"Use project secrets to store sensitive information such as API keys or other access credentials."}),s.jsx(jl,{property:Gs("Project","secret"),name:"secret",path:"Project.secret",defaultValue:i,onChange:a,outcome:void 0}),s.jsx(oe,{type:"submit",children:"Save"})]})}function $K(){const e=se(),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(Xr(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(()=>he({color:"green",message:"Saved"})).catch(c=>{var d,f,h,m;const u=ht(c);he({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(ge,{children:"Project Sites"}),s.jsx("p",{children:"Use project sites configure your project on a separate domain."}),s.jsx(jl,{property:Gs("Project","site"),name:"site",path:"Project.site",defaultValue:i,onChange:a,outcome:void 0}),s.jsx(oe,{type:"submit",children:"Save"})]})}function FK(){const e=se(),[t,{open:n,close:r}]=Zg(!1),[o,i]=p.useState(""),[a,l]=p.useState();if(!e.isLoading()&&!e.isSuperAdmin())return s.jsx(Mr,{outcome:BP});function c(){dd(e,"Rebuilding Structure Definitions","admin/super/structuredefinitions")}function u(){dd(e,"Rebuilding Search Parameters","admin/super/searchparameters")}function d(){dd(e,"Rebuilding Value Sets","admin/super/valuesets")}function f(S){dd(e,"Reindexing Resources","admin/super/reindex",S)}function h(S){e.post("admin/super/removebotidjobsfromqueue",S).then(()=>he({color:"green",message:"Done"})).catch(y=>he({color:"red",message:De(y),autoClose:!1}))}function m(S){e.post("admin/super/purge",{...S,before:eR(S.before)}).then(()=>he({color:"green",message:"Done"})).catch(y=>he({color:"red",message:De(y),autoClose:!1}))}function g(S){e.post("admin/super/setpassword",S).then(()=>he({color:"green",message:"Done"})).catch(y=>he({color:"red",message:De(y),autoClose:!1}))}function v(){e.post("fhir/R4/$db-stats",{}).then(S=>{var y,w;i("Database Stats"),l(s.jsx("pre",{children:(w=(y=S.parameter)==null?void 0:y.find(b=>b.name==="tableString"))==null?void 0:w.valueString})),n()}).catch(S=>he({color:"red",message:De(S),autoClose:!1}))}return s.jsxs(Ne,{width:600,children:[s.jsx(ge,{order:1,children:"Super Admin"}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{children:s.jsx(oe,{onClick:c,children:"Rebuild StructureDefinitions"})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{children:s.jsx(oe,{onClick:u,children:"Rebuild SearchParameters"})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{children:s.jsx(oe,{onClick:d,children:"Rebuild ValueSets"})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{onSubmit:f,children:s.jsxs(Oe,{children:[s.jsx(vt,{title:"Resource Type",htmlFor:"resourceType",children:s.jsx(ve,{id:"resourceType",name:"resourceType",placeholder:"Reindex Resource Type"})}),s.jsx(vt,{title:"Search Filter",htmlFor:"filter",children:s.jsx(ve,{id:"filter",name:"filter",placeholder:"e.g. name=Sam&birthdate=lt2000-01-01"})}),s.jsx(oe,{type:"submit",children:"Reindex"})]})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{onSubmit:m,children:s.jsxs(Oe,{children:[s.jsx(vt,{title:"Purge Resource Type",htmlFor:"purgeResourceType",children:s.jsx(It,{id:"purgeResourceType",name:"resourceType",data:["","AuditEvent","Login"]})}),s.jsx(vt,{title:"Purge Before",htmlFor:"before",children:s.jsx(_s,{name:"before",placeholder:"Before Date"})}),s.jsx(oe,{type:"submit",children:"Purge"})]})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{order:2,children:"Remove Bot ID Jobs from Queue"}),s.jsx("p",{children:"Remove all queued jobs for a Bot ID"}),s.jsx(Ke,{onSubmit:h,children:s.jsxs(Oe,{children:[s.jsx(vt,{title:"Bot ID",children:s.jsx(ve,{name:"botId",placeholder:"Bot Id"})}),s.jsx(oe,{type:"submit",children:"Remove Jobs by Bot ID"})]})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{onSubmit:g,children:s.jsxs(Oe,{children:[s.jsx(ve,{name:"email",label:"Email",required:!0}),s.jsx(Qr,{name:"password",label:"Password",required:!0}),s.jsx(ve,{name:"projectId",label:"Project ID"}),s.jsx(oe,{type:"submit",children:"Force Set Password"})]})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{order:2,children:"Database Stats"}),s.jsx("p",{children:"Query current table statistics from the database."}),s.jsx(Ke,{onSubmit:v,children:s.jsx(oe,{type:"submit",children:"Get Database Stats"})}),s.jsx(wn,{opened:t,onClose:r,title:o,centered:!0,children:a})]})}function dd(e,t,n,r){vo.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(()=>{vo.update({id:n,color:"green",title:t,message:"Done",icon:s.jsx(Ks,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}).catch(i=>{vo.update({id:n,color:"red",title:t,message:De(i),icon:s.jsx(xf,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})})}function zK(){return s.jsxs(s.Fragment,{children:[s.jsx(ge,{children:"Users"}),s.jsx(Yh,{resourceType:"Practitioner",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(Ge,{to:"/admin/invite",children:"Invite new user"})})]})}function BK(){const[e]=ol("ObservationDefinition","_count=100");return e?s.jsxs(de,{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(yo,{value:(n=t.category)==null?void 0:n[0]})}),s.jsx("td",{children:s.jsx(yo,{value:t.code})}),s.jsx("td",{children:s.jsx(yo,{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(Ug,{ranges:t.qualifiedInterval})})]},t.id)})})]}):s.jsx(Jr,{})}function Ug(e){const{ranges:t}=e;if(!t)return null;const n=ES(t.map(o=>o.gender));if(n.length>1)return Nc(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:nn(o)})}),s.jsx(Ug,{ranges:(i=e.ranges)==null?void 0:i.filter(a=>a.gender===o)})]},o)})});const r=ES(t.map(o=>o.age&&Mc(o.age)));return r.length>1?(Nc(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:nn(o)})}),s.jsx(Ug,{ranges:(i=e.ranges)==null?void 0:i.filter(a=>Mc(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(Jx,{value:o.range})})]})})},`range-${o.condition}`))})}function ES(e){return[...new Set(e.filter(t=>!!t))]}function UK(){const[e]=ol("ActivityDefinition","_count=100"),[t]=ol("ObservationDefinition","_count=100");return!e||!t?s.jsx(Jr,{}):s.jsxs(de,{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(yo,{value:(r=n.category)==null?void 0:r[0]})}),s.jsx("td",{children:s.jsx(yo,{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 VK(e){var a;const t=se(),[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(Ge,{to:o,suffix:"checklist",children:"Request Group"})]}),s.jsxs("li",{children:["Back to the ",s.jsx(Ge,{to:e.planDefinition,children:"Plan Definition"})]})]})]}):s.jsx(Ke,{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(Oe,{children:[s.jsxs(ge,{children:['Start "',e.planDefinition.title,'"']}),s.jsxs(fe,{children:["Use the ",s.jsx("strong",{children:"Apply"})," operation to create a group of tasks for a workflow."]}),s.jsx(fe,{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(yo,{value:l.code[0]})]},`action-${c}`)})}),s.jsx(vt,{title:"Subject",children:s.jsx(zh,{name:"subject",targetTypes:["Patient","Practitioner"],defaultValue:n,onChange:r})}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{type:"submit",children:"Go"})})]})})}function WK(){const{resourceType:e,id:t}=ct(),n=wt({reference:e+"/"+t});return n?s.jsx(Ne,{children:s.jsx(VK,{planDefinition:n})}):null}function HK(){const{resourceType:e,id:t}=ct(),n=wt({reference:e+"/"+t}),[r,o]=ol("Questionnaire","subject-type="+e),[i,a]=ol("ClientApplication",{_count:1e3});if(!n||o||a)return s.jsx(Jr,{});const l=i==null?void 0:i.filter(d=>qK(e)&&!!d.launchUri);if((!r||r.length===0)&&(!l||l.length===0))return s.jsxs(Ne,{children:[s.jsx(ge,{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=Et(n):n.resourceType==="Encounter"&&(c=n.subject,u=Et(n)),s.jsxs(Ne,{children:[r==null?void 0:r.map(d=>s.jsxs("div",{children:[s.jsx(ge,{order:3,children:s.jsx(Ge,{to:`/forms/${d.id}?subject=${st(n)}`,children:d.title||d.name})}),s.jsx(fe,{children:d.description})]},d.id)),l==null?void 0:l.map(d=>s.jsxs("div",{children:[s.jsx(ge,{order:3,children:s.jsx(vq,{client:d,patient:c,encounter:u,children:d.name})}),s.jsx(fe,{children:d.description})]},d.id))]})}function qK(e){return e==="Patient"||e==="Encounter"}function GK(){const{resourceType:e,id:t}=ct(),n=Qt(),[r,o]=p.useState({resourceType:"AuditEvent",filters:[{code:"entity",operator:re.EQUALS,value:`${e}/${t}`}],fields:["id","outcome","outcomeDesc","_lastUpdated"],sortRules:[{code:"-_lastUpdated"}],count:20});return s.jsx(Ne,{children:s.jsx(wu,{search:r,onClick:i=>n(`/${i.resource.resourceType}/${i.resource.id}`),onChange:i=>o(i.definition),hideFilters:!0})})}function QK(){const e=se(),{resourceType:t,id:n}=ct(),r=e.readHistory(t,n).read();return s.jsx(Ne,{children:s.jsx(sq,{history:r})})}const KK="_hl7Input_k5xm3_1",YK={hl7Input:KK};function XK(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 JK(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=>{Dd(r.currentTarget,{command:"setValue",value:t}).catch(console.error)}})}const ZK=`{
573
573
  "resourceType": "Patient",
574
574
  "name": [
575
575
  {
@@ -579,5 +579,5 @@ Error generating stack: `+i.message+`
579
579
  "family": "Smith"
580
580
  }
581
581
  ]
582
- }`,ZK="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 eY(){const e=se(),{id:t}=ct(),[n,r]=p.useState(),[o,i]=p.useState(),[a,l]=p.useState(JK),[c,u]=p.useState(ZK),[d,f]=p.useState(on.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 tY(e,j))}).catch(j=>he({color:"red",message:De(j),autoClose:!1}))},[e,t]);const S=p.useCallback(()=>Dd(h.current,{command:"getValue"}),[]),y=p.useCallback(()=>Dd(h.current,{command:"getOutput"}),[]),w=p.useCallback(async()=>d===on.FHIR_JSON?JSON.parse(a):c,[d,a,c]),b=p.useCallback(async j=>{j.preventDefault(),j.stopPropagation(),v(!0);try{const T=await S(),E=await e.createAttachment(T,"index.ts","text/typescript"),_=[];n!=null&&n.sourceCode?_.push({op:"replace",path:"/sourceCode",value:E}):_.push({op:"add",path:"/sourceCode",value:E}),await e.patchResource("Bot",t,_),he({color:"green",message:"Saved"})}catch(T){he({color:"red",message:De(T),autoClose:!1})}finally{v(!1)}},[e,t,n,S]),x=p.useCallback(async j=>{j.preventDefault(),j.stopPropagation(),v(!0);try{const T=await y();await e.post(e.fhirUrl("Bot",t,"$deploy"),{code:T}),he({color:"green",message:"Deployed"})}catch(T){he({color:"red",message:De(T),autoClose:!1})}finally{v(!1)}},[e,t,y]),C=p.useCallback(async j=>{j.preventDefault(),j.stopPropagation(),v(!0);try{const T=await w(),E=await e.post(e.fhirUrl("Bot",t,"$execute"),T,d);await Dd(m.current,{command:"setValue",value:E}),he({color:"green",message:"Success"})}catch(T){he({color:"red",message:De(T),autoClose:!1})}finally{v(!1)}},[e,t,w,d]);return!n||o===void 0?null:s.jsxs(ur,{m:0,gutter:0,style:{overflow:"hidden"},children:[s.jsx(ur.Col,{span:8,children:s.jsxs(Yn,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[s.jsx(XK,{iframeRef:h,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:o,minHeight:"528px"}),s.jsxs(te,{justify:"flex-end",gap:"xs",children:[s.jsx(oe,{type:"button",onClick:b,loading:g,leftSection:s.jsx(cz,{size:"1rem"}),children:"Save"}),s.jsx(oe,{type:"button",onClick:x,loading:g,leftSection:s.jsx(Ux,{size:"1rem"}),children:"Deploy"}),s.jsx(oe,{type:"button",onClick:C,loading:g,leftSection:s.jsx(jz,{size:"1rem"}),children:"Execute"})]})]})}),s.jsxs(ur.Col,{span:4,children:[s.jsxs(Yn,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[s.jsx(It,{data:[{label:"FHIR",value:on.FHIR_JSON},{label:"HL7",value:on.HL7_V2}],onChange:j=>f(j.currentTarget.value)}),d===on.FHIR_JSON?s.jsx(pl,{value:a,onChange:j=>l(j),autosize:!0,minRows:15}):s.jsx("textarea",{className:KK.hl7Input,value:c,onChange:j=>u(j.currentTarget.value),rows:15})]}),s.jsx(Yn,{m:2,p:"xs",shadow:"md",children:s.jsx(YK,{iframeRef:m,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function tY(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(nk);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 nY(){const e=se(),{resourceType:t,id:n}=ct(),r={reference:t+"/"+n},o=p.useCallback(i=>{e.updateResource(Xs(i)).then(()=>{he({color:"green",message:"Success"})}).catch(a=>{he({color:"red",message:De(a),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return s.jsx(Ne,{children:s.jsx(NW,{value:r,onSubmit:o})});case"Questionnaire":return s.jsx(Ne,{children:s.jsx(vH,{questionnaire:r,onSubmit:o})});default:return null}}function rY(){const{resourceType:e,id:t}=ct(),n=wt({reference:e+"/"+t}),r=Qt();return n?s.jsx(Ne,{children:s.jsx(BH,{value:n,onStart:(o,i)=>r(`/forms/${nl(i)}`),onEdit:(o,i,a)=>r(`/${a.reference}}`)})}):null}function oY(){const e=se(),{resourceType:t,id:n}=ct(),r=Qt();return s.jsxs(Ne,{children:[s.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),s.jsx(oe,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>r(`/${t}`)).catch(o=>he({color:"red",message:De(o),autoClose:!1}))},children:"Delete"})]})}const iY="_selectProfileBtn_tbaz6_1",sY="_chevron_tbaz6_13",TS={selectProfileBtn:iY,chevron:sY};function aY(){var c,u;const{resourceType:e,id:t}=ct(),n=wt({reference:e+"/"+t}),[r,o]=p.useState(),i=nu({onDropdownClose:()=>i.resetSelectedOption()}),a=p.useMemo(()=>{var d;if(Bt((d=n==null?void 0:n.meta)==null?void 0:d.profile))return[s.jsx(Me.Option,{value:"",children:"None"},""),...n.meta.profile.map(f=>s.jsx(Me.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 Bt(a)&&(l=s.jsx(te,{justify:"flex-end",children:s.jsxs(Oe,{align:"flex-end",gap:"xs",children:[s.jsxs(Me,{store:i,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:d=>{o(d),i.closeDropdown()},children:[s.jsx(Me.Target,{children:s.jsx(bn,{onClick:()=>i.toggleDropdown(),children:s.jsxs(Fy,{fw:"bold",fs:"sm",className:TS.selectProfileBtn,children:[s.jsx("span",{children:"Pick profile"}),s.jsx(Bx,{stroke:1.5,className:TS.chevron})]})})}),s.jsx(Me.Dropdown,{w:"max-content",children:s.jsx(Me.Options,{children:a})})]}),s.jsx(q,{children:r?s.jsxs(s.Fragment,{children:[s.jsx(fe,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),s.jsx(fe,{span:!0,size:"sm",children:r||"Nothing selected"})]}):s.jsx(fe,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),s.jsx(Ne,{children:s.jsxs(Oe,{gap:"xl",children:[l,s.jsx(u0,{value:n,profileUrl:r})]})})}function lY(){const e=se(),{resourceType:t,id:n}=ct(),[r,o]=p.useState(),[i,a]=p.useState(),l=Qt(),[c,u]=p.useState();p.useEffect(()=>{e.readResource(t,n).then(m=>{o(Xr(m)),a(Xr(m))}).catch(m=>{u(ht(m)),he({color:"red",message:De(m),autoClose:!1})})},[e,t,n]);const d=p.useCallback(m=>{u(void 0),e.updateResource(Xs(m)).then(()=>{l(`/${t}/${n}/details`),he({id:"succes",color:"green",message:"Success"})}).catch(g=>{u(ht(g)),he({color:"red",message:De(g),autoClose:!1})})},[e,t,n,l]),f=p.useCallback(m=>{u(void 0);const g=i0.createPatch(r,m);e.patchResource(t,n,g).then(()=>{l(`/${t}/${n}/details`),he({id:"succes",color:"green",message:"Success"})}).catch(v=>{u(ht(v)),he({color:"red",message:De(v),autoClose:!1})})},[e,t,n,r,l]),h=p.useCallback(()=>l(`/${t}/${n}/delete`),[l,t,n]);return i?s.jsx(Ne,{children:s.jsx(jf,{defaultValue:i,onSubmit:d,onPatch:f,onDelete:h,outcome:c})}):null}function A2({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,o=se(),[i,a]=p.useState();return p.useEffect(()=>{o.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(l=>{a(l.filter(HB))}).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(bx,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:s.jsx(Lz,{size:"90%"})}),children:l.title||l.name},l.url)})})})}function N2(e,t){const n=se(),r=Qt();return{defaultValue:{resourceType:e},handleSubmit:a=>{t&&t(void 0),n.createResource(a).then(l=>r("/"+l.resourceType+"/"+l.id)).catch(l=>{t&&t(ht(l)),he({color:"red",message:De(l),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function im(){const{resourceType:e}=ct(),t=oi(),[n,r]=p.useState(),{defaultValue:o,handleSubmit:i}=N2(e,r),[a,l]=p.useState(),c=t.pathname.toLowerCase().endsWith("profiles"),u=p.useCallback(d=>{const f=Xs(d);a&&ik(f,a.url),i(f)},[a,i]);return c?s.jsx(Ne,{children:s.jsxs(Oe,{children:[s.jsx(A2,{resource:o,currentProfile:a,onChange:l}),a?s.jsx(jf,{defaultValue:o,onSubmit:u,outcome:n,profileUrl:a.url},a.url):s.jsx(fe,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):s.jsx(Ne,{children:s.jsx(jf,{defaultValue:o,onSubmit:i,outcome:n})})}function cY(){const e=se(),{resourceType:t,id:n}=ct(),r=e.readHistory(t,n).read();return s.jsx(Ne,{children:s.jsx(fq,{history:r})})}function uY(){const{resourceType:e}=ct(),[t,n]=p.useState(),{defaultValue:r,handleSubmit:o}=N2(e,n),i=p.useCallback(a=>{o(JSON.parse(a["new-resource"]))},[o]);return s.jsxs(Ne,{children:[t&&s.jsx(Mr,{outcome:t}),s.jsxs(Ke,{onSubmit:i,children:[s.jsx(pl,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:pr(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(oe,{type:"submit",children:"OK"})})]})]})}function dY(){const e=se(),{resourceType:t,id:n}=ct(),r=wt({reference:t+"/"+n}),o=Qt(),[i,a]=p.useState(),l=p.useCallback(c=>{e.updateResource(Xs(JSON.parse(c.resource))).then(()=>{a(void 0),o(`/${t}/${n}/details`),he({color:"green",message:"Success"})}).catch(u=>{he({color:"red",message:De(u),autoClose:!1})})},[e,t,n,o]);return r?s.jsxs(Ne,{children:[i&&s.jsx(Mr,{outcome:i}),s.jsxs(Ke,{onSubmit:l,children:[s.jsx(pl,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:pr(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(oe,{type:"submit",children:"OK"})})]})]}):null}function fY(){const{resourceType:e,id:t}=ct();return wt({reference:e+"/"+t})?s.jsxs(Ne,{children:[s.jsxs(Vi,{icon:s.jsx(Sl,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",s.jsx("br",{}),s.jsx(Ze,{href:`/forms/${t}`,children:`/forms/${t}`})]}),s.jsx(VR,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function hY(){const e=se(),{resourceType:t,id:n}=ct(),[r,o]=p.useState(),[i,a]=p.useState();return p.useEffect(()=>{e.readResource(t,n).then(l=>o(Xr(l))).catch(l=>{he({color:"red",message:De(l)})})},[e,t,n]),r?s.jsxs(Ne,{children:[s.jsxs(ge,{order:2,children:["Available ",t," profiles"]}),s.jsx(Oe,{children:s.jsxs(s.Fragment,{children:[s.jsx(A2,{resource:r,currentProfile:i,onChange:a}),i?s.jsx(pY,{profile:i,resource:r,onResourceUpdated:l=>o(l)},i.url):s.jsx(fe,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const pY=({profile:e,resource:t,onResourceUpdated:n})=>{const r=se(),[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?ik(d,e.url):j6(d,e.url),r.updateResource(d).then(f=>{n(f),he({color:"green",message:"Success"})}).catch(f=>{i(ht(f)),he({color:"red",message:De(f),autoClose:!1})})},[r,e.url,n,a]);return s.jsxs(Oe,{children:[s.jsx(lu,{size:"md",checked:a,label:`Conform resource to ${e.title}`,onChange:u=>l(u.currentTarget.checked),"data-testid":"profile-toggle"}),a?s.jsx(jf,{profileUrl:e.url,defaultValue:t,onSubmit:c,outcome:o}):s.jsx("form",{noValidate:!0,onSubmit:u=>{u.preventDefault(),c(t)},children:s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{type:"submit",children:"OK"})})})]})};function mY(){const e=se(),{id:t}=ct(),[n,r]=p.useState(),[o,i]=p.useState(0),a=e.searchResources("Subscription","status=active&_count=100").read().filter(c=>gY(c,t));function l(){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:st(n)}}).then(()=>{r(void 0),i(Date.now()),e.invalidateSearches("Subscription"),he({color:"green",message:"Success"})}).catch(c=>he({color:"red",message:De(c),autoClose:!1}))}return s.jsxs(Ne,{children:[s.jsx(ge,{children:"Bots"}),a.length===0&&s.jsx("p",{children:"No bots found."}),a.map(c=>{var u;return s.jsxs("div",{children:[s.jsx("h3",{children:s.jsx(Cl,{value:{reference:(u=c.channel)==null?void 0:u.endpoint},link:!0})}),s.jsxs("p",{children:["Criteria: ",c.criteria]})]},c.id)}),s.jsx("hr",{}),s.jsx(ge,{children:"Connect to bot"}),s.jsxs(te,{children:[s.jsx(Ys,{name:"bot",resourceType:"Bot",onChange:c=>r(c)}),s.jsx(oe,{onClick:l,children:"Connect"})]}),s.jsx("div",{style:{display:"none"},children:o})]})}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 vY(){const{id:e}=ct(),t=Qt(),[n,r]=p.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:re.EQUALS,value:"Questionnaire/"+e}],fields:["id","_lastUpdated"]});return s.jsx(Ne,{children:s.jsx(wu,{search:n,onClick:o=>t(`/${o.resource.resourceType}/${o.resource.id}`),onChange:o=>r(o.definition),hideFilters:!0,hideToolbar:!0})})}function yY(){const e=se(),{resourceType:t,id:n}=ct(),r=wt({reference:t+"/"+n}),o=p.useCallback(i=>{e.updateResource(Xs(i)).then(()=>{he({color:"green",message:"Success"})}).catch(a=>{he({color:"red",message:De(a),autoClose:!1})})},[e]);return r?s.jsx(Ne,{children:s.jsx(AH,{onSubmit:o,definition:r})}):null}function xY(){const{resourceType:e,id:t}=ct(),n=wt({reference:e+"/"+t});return n?s.jsx(Ne,{children:e==="MeasureReport"?s.jsx(kW,{measureReport:n}):s.jsx(r0,{value:n})}):null}const bY="_container_1ue98_1",wY="_entry_1ue98_14",SY="_active_1ue98_21",sm={container:bY,entry:wY,active:SY};function jY(e){const t=se(),n=wt(e.value),[r,o]=p.useState();return p.useEffect(()=>{if(!n)return;const i=C0(n);if(!i)return;const a="reference"in i?i.reference:st(i);t.search("ServiceRequest","subject="+a).then(l=>{const u=l.entry.map(d=>d.resource);xR(u),u.reverse(),o(u)}).catch(l=>he({color:"red",message:De(l),autoClose:!1}))},[t,n]),r?s.jsx("div",{"data-testid":"quick-service-requests",className:sm.container,children:r.map(i=>{var a,l,c,u,d,f,h;return s.jsxs("div",{className:rt(sm.entry,{[sm.active]:i.id===(n==null?void 0:n.id)}),children:[s.jsx("p",{children:s.jsx(Ge,{to:i,children:CY(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:EY(i)})]},i.id)})}):null}function CY(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function EY(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const TY="_container_1l2dh_1",PY={container:TY};function kY(e){var o,i,a,l;const t=wt(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:PY.container,children:s.jsx(It,{defaultValue:e.defaultValue,onChange:c=>e.onChange(c.currentTarget.value),data:n})})}function RY(e){var n,r;const t=wt(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:Fn((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:_Y(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:DY(t)})]}):s.jsx(s.Fragment,{})]}):null}function _Y(e){var o;const t=(o=e.collection)==null?void 0:o.collectedDateTime;if(!t)return;const n=new Date(t);return M2(O2(n,new Date))}function DY(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 M2(O2(t,n))}function M2(e){return e.toString().padStart(3,"0")+"D"}function O2(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function IY(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 AY=["Profiles"];function NY(){var b,x,C,j,T,E,_;const e=se(),{resourceType:t,id:n}=ct(),r={reference:t+"/"+n},o=Qt(),[i,a]=p.useState(),l=wt(r,a),c=IY(t),[u,d]=p.useState(()=>{const k=window.location.pathname.split("/").pop();return k&&c.map(A=>A.toLowerCase()).includes(k)?k:c[0].toLowerCase()}),f=At();async function h(){var O,U;const A=(U=(O=(await e.readHistory(t,n)).entry)==null?void 0:O.find(N=>!!N.resource))==null?void 0:U.resource;A?m(A):he({color:"red",message:"No history to restore",autoClose:!1})}function m(k){e.updateResource(Xs(k)).then(()=>{a(void 0),he({color:"green",message:"Success"})}).catch(A=>{he({color:"red",message:De(A),autoClose:!1})})}if(i)return V$(i)?s.jsxs(Ne,{children:[s.jsx(ge,{children:"Deleted"}),s.jsx("p",{children:"The resource was deleted."}),s.jsx(oe,{color:"red",onClick:h,children:"Restore"})]}):s.jsx(Mr,{outcome:i});function g(k){k||(k=c[0].toLowerCase()),d(k),o(`/${t}/${n}/${k}`)}function v(k){const A=l,O=A.orderDetail||[];O.length===0&&O.push({}),O[0].text!==k&&(O[0].text=k,m({...A,orderDetail:O}))}const S=l&&C0(l),y=l&&iK(l),w=(C=(x=(b=e.getUserConfiguration())==null?void 0:b.option)==null?void 0:x.find(k=>k.id==="statusValueSet"))==null?void 0:C.valueString;return s.jsxs(s.Fragment,{children:[(l==null?void 0:l.resourceType)==="ServiceRequest"&&w&&s.jsx(kY,{valueSet:{reference:w},defaultValue:(T=(j=l.orderDetail)==null?void 0:j[0])==null?void 0:T.text,onChange:v},st(l)+"-"+((_=(E=l.orderDetail)==null?void 0:E[0])==null?void 0:_.text)),l&&s.jsx(jY,{value:l}),l&&s.jsxs(Yn,{children:[S&&s.jsx(k2,{patient:S}),y&&s.jsx(RY,{specimen:y}),t!=="Patient"&&s.jsx(R2,{resource:r}),s.jsx(Ir,{children:s.jsx(et,{value:u.toLowerCase(),onChange:g,children:s.jsx(et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:c.map(k=>s.jsx(et.Tab,{value:k.toLowerCase(),children:AY.includes(k)?s.jsxs(te,{gap:"xs",wrap:"nowrap",children:[k,s.jsx(ru,{color:f.primaryColor,size:"sm",children:"Beta"})]}):k},k))})})})]}),s.jsx(x0,{})]})}function PS(){var y,w,b,x;const e=Qt(),{resourceType:t,id:n,versionId:r,tab:o}=ct(),i=se(),[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(Jr,{});if(!c)return s.jsxs(Ne,{children:[s.jsx(ge,{children:"Resource not found"}),s.jsx(Ge,{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(Ne,{children:[s.jsx(ge,{children:"Version not found"}),s.jsx(Ge,{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(Yn,{children:[s.jsx(yu,{fluid:!0,p:"md",children:s.jsx(fe,{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(Ne,{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: ",(y=g.meta)==null?void 0:y.versionId]}),s.jsxs("li",{children:["Previous:"," ",s.jsx(Ge,{to:`/${t}/${n}/_history/${(w=v.meta)==null?void 0:w.versionId}`,children:(b=v.meta)==null?void 0:b.versionId})]})]}),s.jsx(lq,{original:v,revised:g})]}):s.jsxs(s.Fragment,{children:[s.jsxs("ul",{children:[s.jsxs("li",{children:["Current: ",(x=g.meta)==null?void 0:x.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 MY(){const{resourceType:e,id:t}=ct(),n=Qt(),[r,o]=p.useState({resourceType:"Subscription",filters:[{code:"url",operator:re.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return s.jsx(Ne,{children:s.jsx(gW,{search:r,onClick:i=>n(`/${i.resource.resourceType}/${i.resource.id}`),onChange:i=>o(i.definition),hideFilters:!0})})}function OY(e){const t=se(),{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?st(l):void 0,verbose:u}),he({color:"green",message:"Done"}),o()}catch(h){he({color:"red",message:De(h),autoClose:!1})}},[t,n,o,i,l,u]);return s.jsx(wn,{opened:r,onClose:o,title:"Resend Subscriptions",children:s.jsx(Ke,{onSubmit:f,children:s.jsxs(Oe,{children:[s.jsx(_n,{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(_n,{label:"Verbose mode",onChange:h=>d(h.currentTarget.checked)}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{type:"submit",children:"Resend"})})]})})})}function kS(){const e=se(),t=Lh(),{resourceType:n,id:r}=ct(),o={reference:n+"/"+r},[i,a]=p.useState(),l=Zg(!1);function c(w,b){return e.updateResource({...w,priority:b})}function u(w,b){c(w,"stat").then(b).catch(console.error)}function d(w,b){c(w,"routine").then(b).catch(console.error)}function f(w){t(`/${w.resourceType}/${w.id}`)}function h(w){t(`/${w.resourceType}/${w.id}/edit`)}function m(w){t(`/${w.resourceType}/${w.id}/delete`)}function g(w){a(w),l[1].open()}function v(w){var b;t(`/${w.resourceType}/${w.id}/_history/${(b=w.meta)==null?void 0:b.versionId}`)}function S(w,b){e.post(e.fhirUrl(w.resourceType,w.id,"$aws-textract"),{}).then(b).catch(console.error)}function y(w){var D;const{primaryResource:b,currentResource:x,reloadTimeline:C}=w,j=x.resourceType===b.resourceType&&x.id===b.id,T=x.resourceType==="Communication"&&x.priority!=="stat",E=x.resourceType==="Communication"&&x.priority==="stat",_=j,k=!j,A=!j,O=!j,U=(D=e.getProjectMembership())==null?void 0:D.admin,N=U,F=yK()&&(x.resourceType==="DocumentReference"||x.resourceType==="Media");return s.jsxs(J.Dropdown,{children:[s.jsx(J.Label,{children:"Resource"}),T&&s.jsx(J.Item,{leftSection:s.jsx(wz,{size:14}),onClick:()=>u(x,C),"aria-label":`Pin ${st(x)}`,children:"Pin"}),E&&s.jsx(J.Item,{leftSection:s.jsx(Sz,{size:14}),onClick:()=>d(x,C),"aria-label":`Unpin ${st(x)}`,children:"Unpin"}),k&&s.jsx(J.Item,{leftSection:s.jsx(Sw,{size:14}),onClick:()=>f(x),"aria-label":`Details ${st(x)}`,children:"Details"}),_&&s.jsx(J.Item,{leftSection:s.jsx(Sw,{size:14}),onClick:()=>v(x),"aria-label":`Details ${st(x)}`,children:"Details"}),A&&s.jsx(J.Item,{leftSection:s.jsx(Nk,{size:14}),onClick:()=>h(x),"aria-label":`Edit ${st(x)}`,children:"Edit"}),U&&s.jsxs(s.Fragment,{children:[s.jsx(J.Divider,{}),s.jsx(J.Label,{children:"Admin"}),N&&s.jsx(J.Item,{leftSection:s.jsx(Pz,{size:14}),onClick:()=>g(x),"aria-label":`Resend Subscriptions ${st(x)}`,children:"Resend Subscriptions"})]}),F&&s.jsxs(s.Fragment,{children:[s.jsx(J.Divider,{}),s.jsx(J.Label,{children:"AWS AI"}),s.jsx(J.Item,{leftSection:s.jsx(Mz,{size:14}),onClick:()=>S(x,C),"aria-label":`AWS Textract ${st(x)}`,children:"AWS Textract"})]}),O&&s.jsxs(s.Fragment,{children:[s.jsx(J.Divider,{}),s.jsx(J.Label,{children:"Danger zone"}),s.jsx(J.Item,{color:"red",leftSection:s.jsx(Hx,{size:14}),onClick:()=>m(x),"aria-label":`Delete ${st(x)}`,children:"Delete"})]})]})}return s.jsxs(s.Fragment,{children:[n==="Encounter"&&s.jsx(EV,{encounter:o,getMenu:y}),n==="Patient"&&s.jsx(RW,{patient:o,getMenu:y}),n==="ServiceRequest"&&s.jsx(mq,{serviceRequest:o,getMenu:y}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&s.jsx(CV,{resource:o,getMenu:y}),s.jsx(OY,{resource:i,opened:l[0],onClose:l[1].close},`resend-subscriptions-${i==null?void 0:i.id}`)]})}function LY(){const e=se(),{id:t}=ct(),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(),[y,w]=p.useState(!1),[b,x]=p.useState(!1);p.useEffect(()=>{if(r||i||l||y){x(!0);return}x(!1)},[r,i,l,y]);const C=p.useCallback(()=>{o(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(A=>{var O,U,N,F,D,R;d((U=(O=A.parameter)==null?void 0:O.find(P=>P.name==="status"))==null?void 0:U.valueCode),h((F=(N=A.parameter)==null?void 0:N.find(P=>P.name==="version"))==null?void 0:F.valueString),g((R=(D=A.parameter)==null?void 0:D.find(P=>P.name==="lastUpdated"))==null?void 0:R.valueInstant)}).catch(A=>k(De(A))).finally(()=>o(!1))},[e,t]),j=p.useCallback(A=>{const O=A.host,U=A.pingCount||1;O&&(w(!0),e.pushToAgent(n,O,`PING ${U}`,on.PING,!0).then(N=>S(N)).catch(N=>k(De(N))).finally(()=>w(!1)))},[e,n]),T=p.useCallback(()=>{a(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(A=>{_("Agent config reloaded successfully.")}).catch(A=>k(De(A))).finally(()=>a(!1))},[e,t]),E=p.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$upgrade"),{cache:"reload"}).then(A=>{_("Agent upgraded successfully.")}).catch(A=>k(De(A))).finally(()=>c(!1))},[e,t]);function _(A){he({color:"green",title:"Success",icon:s.jsx(Ks,{size:"1rem"}),message:A})}function k(A){he({color:"red",title:"Error",message:A,autoClose:!1})}return s.jsxs(Ne,{children:[s.jsx(ge,{order:1,children:"Agent Tools"}),s.jsxs("div",{style:{marginBottom:10},children:["Agent: ",s.jsx(Cl,{value:n,link:!0})]}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(oe,{onClick:C,loading:r,disabled:b&&!r,children:"Get Status"}),!r&&u&&s.jsx(de,{children:s.jsxs(de.Tbody,{children:[s.jsxs(de.Tr,{children:[s.jsx(de.Td,{children:"Status"}),s.jsx(de.Td,{children:s.jsx(n0,{status:u})})]}),s.jsxs(de.Tr,{children:[s.jsx(de.Td,{children:"Version"}),s.jsx(de.Td,{children:f})]}),s.jsxs(de.Tr,{children:[s.jsx(de.Td,{children:"Last Updated"}),s.jsx(de.Td,{children:Fn(m,void 0,{timeZoneName:"longOffset"})})]})]})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(oe,{onClick:T,loading:i,disabled:b&&!i,"aria-label":"Reload config",children:"Reload Config"}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(oe,{onClick:E,loading:l,disabled:b&&!l,"aria-label":"Upgrade agent",children:"Upgrade"}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{onSubmit:j,children:s.jsxs(te,{children:[s.jsx(ve,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:s.jsx(tn,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:y,disabled:b&&!y,children:s.jsx(Rz,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),s.jsx(rx,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!y&&v&&s.jsxs(s.Fragment,{children:[s.jsx(ge,{order:5,mt:"sm",mb:0,children:"Last Ping"}),s.jsx("pre",{children:v})]})]})}function $Y(){return s.jsx($G,{children:s.jsxs(we,{errorElement:s.jsx(ZQ,{}),children:[s.jsx(we,{path:"/signin",element:s.jsx(CK,{})}),s.jsx(we,{path:"/oauth",element:s.jsx(xK,{})}),s.jsx(we,{path:"/resetpassword",element:s.jsx(wK,{})}),s.jsx(we,{path:"/setpassword/:id/:secret",element:s.jsx(jK,{})}),s.jsx(we,{path:"/register",element:s.jsx(bK,{})}),s.jsx(we,{path:"/changepassword",element:s.jsx(YQ,{})}),s.jsx(we,{path:"/security",element:s.jsx(SK,{})}),s.jsx(we,{path:"/mfa",element:s.jsx(vK,{})}),s.jsx(we,{path:"/batch",element:s.jsx(QQ,{})}),s.jsx(we,{path:"/bulk/:resourceType",element:s.jsx(KQ,{})}),s.jsx(we,{path:"/smart",element:s.jsx(EK,{})}),s.jsx(we,{path:"/forms/:id",element:s.jsx(aK,{})}),s.jsx(we,{path:"/admin/super",element:s.jsx($K,{})}),s.jsx(we,{path:"/admin/config",element:s.jsx(NK,{})}),s.jsxs(we,{path:"/admin",element:s.jsx(MK,{}),children:[s.jsx(we,{path:"patients",element:s.jsx(AK,{})}),s.jsx(we,{path:"bots/new",element:s.jsx(kK,{})}),s.jsx(we,{path:"bots",element:s.jsx(TK,{})}),s.jsx(we,{path:"clients/new",element:s.jsx(RK,{})}),s.jsx(we,{path:"clients",element:s.jsx(PK,{})}),s.jsx(we,{path:"details",element:s.jsx(jS,{})}),s.jsx(we,{path:"invite",element:s.jsx(IK,{})}),s.jsx(we,{path:"users",element:s.jsx(FK,{})}),s.jsx(we,{path:"project",element:s.jsx(jS,{})}),s.jsx(we,{path:"secrets",element:s.jsx(OK,{})}),s.jsx(we,{path:"sites",element:s.jsx(LK,{})}),s.jsx(we,{path:"members/:membershipId",element:s.jsx(DK,{})})]}),s.jsx(we,{path:"/lab/assays",element:s.jsx(zK,{})}),s.jsx(we,{path:"/lab/panels",element:s.jsx(BK,{})}),s.jsx(we,{path:"/:resourceType/:id/_history/:versionId/:tab",element:s.jsx(PS,{})}),s.jsx(we,{path:"/:resourceType/:id/_history/:versionId",element:s.jsx(PS,{})}),s.jsxs(we,{path:"/:resourceType/new",element:s.jsx(JQ,{}),children:[s.jsx(we,{index:!0,element:s.jsx(im,{})}),s.jsx(we,{path:"form",element:s.jsx(im,{})}),s.jsx(we,{path:"json",element:s.jsx(uY,{})}),s.jsx(we,{path:"profiles",element:s.jsx(im,{})})]}),s.jsxs(we,{path:"/:resourceType/:id",element:s.jsx(NY,{}),children:[s.jsx(we,{index:!0,element:s.jsx(kS,{})}),s.jsx(we,{path:"apply",element:s.jsx(VK,{})}),s.jsx(we,{path:"apps",element:s.jsx(WK,{})}),s.jsx(we,{path:"event",element:s.jsx(qK,{})}),s.jsx(we,{path:"blame",element:s.jsx(GK,{})}),s.jsx(we,{path:"bots",element:s.jsx(mY,{})}),s.jsx(we,{path:"builder",element:s.jsx(nY,{})}),s.jsx(we,{path:"checklist",element:s.jsx(rY,{})}),s.jsx(we,{path:"delete",element:s.jsx(oY,{})}),s.jsx(we,{path:"details",element:s.jsx(aY,{})}),s.jsx(we,{path:"edit",element:s.jsx(lY,{})}),s.jsx(we,{path:"editor",element:s.jsx(eY,{})}),s.jsx(we,{path:"history",element:s.jsx(cY,{})}),s.jsx(we,{path:"json",element:s.jsx(dY,{})}),s.jsx(we,{path:"preview",element:s.jsx(fY,{})}),s.jsx(we,{path:"responses",element:s.jsx(vY,{})}),s.jsx(we,{path:"report",element:s.jsx(xY,{})}),s.jsx(we,{path:"ranges",element:s.jsx(yY,{})}),s.jsx(we,{path:"subscriptions",element:s.jsx(MY,{})}),s.jsx(we,{path:"timeline",element:s.jsx(kS,{})}),s.jsx(we,{path:"tools",element:s.jsx(LY,{})}),s.jsx(we,{path:"profiles",element:s.jsx(hY,{})})]}),s.jsx(we,{path:"/:resourceType",element:s.jsx(SS,{})}),s.jsx(we,{path:"/",element:s.jsx(SS,{})})]})})}function FY(){const e=se(),t=e.getUserConfiguration(),n=oi(),[r]=b0();return e.isLoading()?s.jsx(Jr,{}):s.jsx(kB,{logo:s.jsx(ro,{size:24}),pathname:n.pathname,searchParams:r,version:b8,menus:zY(t),displayAddBookmark:!!(t!=null&&t.id),children:s.jsx(p.Suspense,{fallback:s.jsx(Jr,{}),children:s.jsx($Y,{})})})}function zY(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:BY(i.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:s.jsx(gz,{})}]}),t}const RS={Patient:Iz,Practitioner:pz,Organization:iz,ServiceRequest:Ez,DiagnosticReport:kz,Questionnaire:hz,admin:nz,AccessPolicy:mz,Subscription:Oz,batch:bz,Observation:xz};function BY(e){try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in RS){const n=RS[t];return s.jsx(n,{})}}catch{}return s.jsx(Rh,{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 UY(){const e=Eu(),t=new Ck({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=UG([{path:"*",element:s.jsx(FY,{})}]),o=a=>r.navigate(a);ZR(document.getElementById("root")).render(s.jsx(p.StrictMode,{children:s.jsx(z8,{medplum:t,navigate:o,children:s.jsxs(dj,{theme:n,children:[s.jsx(ti,{position:"bottom-right"}),s.jsx(XG,{router:r})]})})}))}UY().catch(console.error);
583
- //# sourceMappingURL=index-8yUj9xIJ.js.map
582
+ }`,eY="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 tY(){const e=se(),{id:t}=ct(),[n,r]=p.useState(),[o,i]=p.useState(),[a,l]=p.useState(ZK),[c,u]=p.useState(eY),[d,f]=p.useState(on.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 nY(e,j))}).catch(j=>he({color:"red",message:De(j),autoClose:!1}))},[e,t]);const S=p.useCallback(()=>Dd(h.current,{command:"getValue"}),[]),y=p.useCallback(()=>Dd(h.current,{command:"getOutput"}),[]),w=p.useCallback(async()=>d===on.FHIR_JSON?JSON.parse(a):c,[d,a,c]),b=p.useCallback(async j=>{j.preventDefault(),j.stopPropagation(),v(!0);try{const T=await S(),E=await e.createAttachment(T,"index.ts","text/typescript"),_=[];n!=null&&n.sourceCode?_.push({op:"replace",path:"/sourceCode",value:E}):_.push({op:"add",path:"/sourceCode",value:E}),await e.patchResource("Bot",t,_),he({color:"green",message:"Saved"})}catch(T){he({color:"red",message:De(T),autoClose:!1})}finally{v(!1)}},[e,t,n,S]),x=p.useCallback(async j=>{j.preventDefault(),j.stopPropagation(),v(!0);try{const T=await y();await e.post(e.fhirUrl("Bot",t,"$deploy"),{code:T}),he({color:"green",message:"Deployed"})}catch(T){he({color:"red",message:De(T),autoClose:!1})}finally{v(!1)}},[e,t,y]),C=p.useCallback(async j=>{j.preventDefault(),j.stopPropagation(),v(!0);try{const T=await w(),E=await e.post(e.fhirUrl("Bot",t,"$execute"),T,d);await Dd(m.current,{command:"setValue",value:E}),he({color:"green",message:"Success"})}catch(T){he({color:"red",message:De(T),autoClose:!1})}finally{v(!1)}},[e,t,w,d]);return!n||o===void 0?null:s.jsxs(ur,{m:0,gutter:0,style:{overflow:"hidden"},children:[s.jsx(ur.Col,{span:8,children:s.jsxs(Yn,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[s.jsx(JK,{iframeRef:h,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:o,minHeight:"528px"}),s.jsxs(te,{justify:"flex-end",gap:"xs",children:[s.jsx(oe,{type:"button",onClick:b,loading:g,leftSection:s.jsx(uz,{size:"1rem"}),children:"Save"}),s.jsx(oe,{type:"button",onClick:x,loading:g,leftSection:s.jsx(Ux,{size:"1rem"}),children:"Deploy"}),s.jsx(oe,{type:"button",onClick:C,loading:g,leftSection:s.jsx(Cz,{size:"1rem"}),children:"Execute"})]})]})}),s.jsxs(ur.Col,{span:4,children:[s.jsxs(Yn,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[s.jsx(It,{data:[{label:"FHIR",value:on.FHIR_JSON},{label:"HL7",value:on.HL7_V2}],onChange:j=>f(j.currentTarget.value)}),d===on.FHIR_JSON?s.jsx(pl,{value:a,onChange:j=>l(j),autosize:!0,minRows:15}):s.jsx("textarea",{className:YK.hl7Input,value:c,onChange:j=>u(j.currentTarget.value),rows:15})]}),s.jsx(Yn,{m:2,p:"xs",shadow:"md",children:s.jsx(XK,{iframeRef:m,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function nY(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(nk);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 rY(){const e=se(),{resourceType:t,id:n}=ct(),r={reference:t+"/"+n},o=p.useCallback(i=>{e.updateResource(Xs(i)).then(()=>{he({color:"green",message:"Success"})}).catch(a=>{he({color:"red",message:De(a),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return s.jsx(Ne,{children:s.jsx(MW,{value:r,onSubmit:o})});case"Questionnaire":return s.jsx(Ne,{children:s.jsx(yH,{questionnaire:r,onSubmit:o})});default:return null}}function oY(){const{resourceType:e,id:t}=ct(),n=wt({reference:e+"/"+t}),r=Qt();return n?s.jsx(Ne,{children:s.jsx(UH,{value:n,onStart:(o,i)=>r(`/forms/${nl(i)}`),onEdit:(o,i,a)=>r(`/${a.reference}}`)})}):null}function iY(){const e=se(),{resourceType:t,id:n}=ct(),r=Qt();return s.jsxs(Ne,{children:[s.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),s.jsx(oe,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>r(`/${t}`)).catch(o=>he({color:"red",message:De(o),autoClose:!1}))},children:"Delete"})]})}const sY="_selectProfileBtn_tbaz6_1",aY="_chevron_tbaz6_13",TS={selectProfileBtn:sY,chevron:aY};function lY(){var c,u;const{resourceType:e,id:t}=ct(),n=wt({reference:e+"/"+t}),[r,o]=p.useState(),i=nu({onDropdownClose:()=>i.resetSelectedOption()}),a=p.useMemo(()=>{var d;if(Bt((d=n==null?void 0:n.meta)==null?void 0:d.profile))return[s.jsx(Me.Option,{value:"",children:"None"},""),...n.meta.profile.map(f=>s.jsx(Me.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 Bt(a)&&(l=s.jsx(te,{justify:"flex-end",children:s.jsxs(Oe,{align:"flex-end",gap:"xs",children:[s.jsxs(Me,{store:i,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:d=>{o(d),i.closeDropdown()},children:[s.jsx(Me.Target,{children:s.jsx(bn,{onClick:()=>i.toggleDropdown(),children:s.jsxs(Fy,{fw:"bold",fs:"sm",className:TS.selectProfileBtn,children:[s.jsx("span",{children:"Pick profile"}),s.jsx(Bx,{stroke:1.5,className:TS.chevron})]})})}),s.jsx(Me.Dropdown,{w:"max-content",children:s.jsx(Me.Options,{children:a})})]}),s.jsx(q,{children:r?s.jsxs(s.Fragment,{children:[s.jsx(fe,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),s.jsx(fe,{span:!0,size:"sm",children:r||"Nothing selected"})]}):s.jsx(fe,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),s.jsx(Ne,{children:s.jsxs(Oe,{gap:"xl",children:[l,s.jsx(u0,{value:n,profileUrl:r})]})})}function cY(){const e=se(),{resourceType:t,id:n}=ct(),[r,o]=p.useState(),[i,a]=p.useState(),l=Qt(),[c,u]=p.useState();p.useEffect(()=>{e.readResource(t,n).then(m=>{o(Xr(m)),a(Xr(m))}).catch(m=>{u(ht(m)),he({color:"red",message:De(m),autoClose:!1})})},[e,t,n]);const d=p.useCallback(m=>{u(void 0),e.updateResource(Xs(m)).then(()=>{l(`/${t}/${n}/details`),he({id:"succes",color:"green",message:"Success"})}).catch(g=>{u(ht(g)),he({color:"red",message:De(g),autoClose:!1})})},[e,t,n,l]),f=p.useCallback(m=>{u(void 0);const g=i0.createPatch(r,m);e.patchResource(t,n,g).then(()=>{l(`/${t}/${n}/details`),he({id:"succes",color:"green",message:"Success"})}).catch(v=>{u(ht(v)),he({color:"red",message:De(v),autoClose:!1})})},[e,t,n,r,l]),h=p.useCallback(()=>l(`/${t}/${n}/delete`),[l,t,n]);return i?s.jsx(Ne,{children:s.jsx(jf,{defaultValue:i,onSubmit:d,onPatch:f,onDelete:h,outcome:c})}):null}function A2({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,o=se(),[i,a]=p.useState();return p.useEffect(()=>{o.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(l=>{a(l.filter(qB))}).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(bx,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:s.jsx($z,{size:"90%"})}),children:l.title||l.name},l.url)})})})}function N2(e,t){const n=se(),r=Qt();return{defaultValue:{resourceType:e},handleSubmit:a=>{t&&t(void 0),n.createResource(a).then(l=>r("/"+l.resourceType+"/"+l.id)).catch(l=>{t&&t(ht(l)),he({color:"red",message:De(l),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function im(){const{resourceType:e}=ct(),t=oi(),[n,r]=p.useState(),{defaultValue:o,handleSubmit:i}=N2(e,r),[a,l]=p.useState(),c=t.pathname.toLowerCase().endsWith("profiles"),u=p.useCallback(d=>{const f=Xs(d);a&&ik(f,a.url),i(f)},[a,i]);return c?s.jsx(Ne,{children:s.jsxs(Oe,{children:[s.jsx(A2,{resource:o,currentProfile:a,onChange:l}),a?s.jsx(jf,{defaultValue:o,onSubmit:u,outcome:n,profileUrl:a.url},a.url):s.jsx(fe,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):s.jsx(Ne,{children:s.jsx(jf,{defaultValue:o,onSubmit:i,outcome:n})})}function uY(){const e=se(),{resourceType:t,id:n}=ct(),r=e.readHistory(t,n).read();return s.jsx(Ne,{children:s.jsx(hq,{history:r})})}function dY(){const{resourceType:e}=ct(),[t,n]=p.useState(),{defaultValue:r,handleSubmit:o}=N2(e,n),i=p.useCallback(a=>{o(JSON.parse(a["new-resource"]))},[o]);return s.jsxs(Ne,{children:[t&&s.jsx(Mr,{outcome:t}),s.jsxs(Ke,{onSubmit:i,children:[s.jsx(pl,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:pr(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(oe,{type:"submit",children:"OK"})})]})]})}function fY(){const e=se(),{resourceType:t,id:n}=ct(),r=wt({reference:t+"/"+n}),o=Qt(),[i,a]=p.useState(),l=p.useCallback(c=>{e.updateResource(Xs(JSON.parse(c.resource))).then(()=>{a(void 0),o(`/${t}/${n}/details`),he({color:"green",message:"Success"})}).catch(u=>{he({color:"red",message:De(u),autoClose:!1})})},[e,t,n,o]);return r?s.jsxs(Ne,{children:[i&&s.jsx(Mr,{outcome:i}),s.jsxs(Ke,{onSubmit:l,children:[s.jsx(pl,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:pr(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(oe,{type:"submit",children:"OK"})})]})]}):null}function hY(){const{resourceType:e,id:t}=ct();return wt({reference:e+"/"+t})?s.jsxs(Ne,{children:[s.jsxs(Vi,{icon:s.jsx(Sl,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",s.jsx("br",{}),s.jsx(Ze,{href:`/forms/${t}`,children:`/forms/${t}`})]}),s.jsx(VR,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function pY(){const e=se(),{resourceType:t,id:n}=ct(),[r,o]=p.useState(),[i,a]=p.useState();return p.useEffect(()=>{e.readResource(t,n).then(l=>o(Xr(l))).catch(l=>{he({color:"red",message:De(l)})})},[e,t,n]),r?s.jsxs(Ne,{children:[s.jsxs(ge,{order:2,children:["Available ",t," profiles"]}),s.jsx(Oe,{children:s.jsxs(s.Fragment,{children:[s.jsx(A2,{resource:r,currentProfile:i,onChange:a}),i?s.jsx(mY,{profile:i,resource:r,onResourceUpdated:l=>o(l)},i.url):s.jsx(fe,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const mY=({profile:e,resource:t,onResourceUpdated:n})=>{const r=se(),[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?ik(d,e.url):j6(d,e.url),r.updateResource(d).then(f=>{n(f),he({color:"green",message:"Success"})}).catch(f=>{i(ht(f)),he({color:"red",message:De(f),autoClose:!1})})},[r,e.url,n,a]);return s.jsxs(Oe,{children:[s.jsx(lu,{size:"md",checked:a,label:`Conform resource to ${e.title}`,onChange:u=>l(u.currentTarget.checked),"data-testid":"profile-toggle"}),a?s.jsx(jf,{profileUrl:e.url,defaultValue:t,onSubmit:c,outcome:o}):s.jsx("form",{noValidate:!0,onSubmit:u=>{u.preventDefault(),c(t)},children:s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(oe,{type:"submit",children:"OK"})})})]})};function gY(){const e=se(),{id:t}=ct(),[n,r]=p.useState(),[o,i]=p.useState(0),a=e.searchResources("Subscription","status=active&_count=100").read().filter(c=>vY(c,t));function l(){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:st(n)}}).then(()=>{r(void 0),i(Date.now()),e.invalidateSearches("Subscription"),he({color:"green",message:"Success"})}).catch(c=>he({color:"red",message:De(c),autoClose:!1}))}return s.jsxs(Ne,{children:[s.jsx(ge,{children:"Bots"}),a.length===0&&s.jsx("p",{children:"No bots found."}),a.map(c=>{var u;return s.jsxs("div",{children:[s.jsx("h3",{children:s.jsx(Cl,{value:{reference:(u=c.channel)==null?void 0:u.endpoint},link:!0})}),s.jsxs("p",{children:["Criteria: ",c.criteria]})]},c.id)}),s.jsx("hr",{}),s.jsx(ge,{children:"Connect to bot"}),s.jsxs(te,{children:[s.jsx(Ys,{name:"bot",resourceType:"Bot",onChange:c=>r(c)}),s.jsx(oe,{onClick:l,children:"Connect"})]}),s.jsx("div",{style:{display:"none"},children:o})]})}function vY(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 yY(){const{id:e}=ct(),t=Qt(),[n,r]=p.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:re.EQUALS,value:"Questionnaire/"+e}],fields:["id","_lastUpdated"]});return s.jsx(Ne,{children:s.jsx(wu,{search:n,onClick:o=>t(`/${o.resource.resourceType}/${o.resource.id}`),onChange:o=>r(o.definition),hideFilters:!0,hideToolbar:!0})})}function xY(){const e=se(),{resourceType:t,id:n}=ct(),r=wt({reference:t+"/"+n}),o=p.useCallback(i=>{e.updateResource(Xs(i)).then(()=>{he({color:"green",message:"Success"})}).catch(a=>{he({color:"red",message:De(a),autoClose:!1})})},[e]);return r?s.jsx(Ne,{children:s.jsx(NH,{onSubmit:o,definition:r})}):null}function bY(){const{resourceType:e,id:t}=ct(),n=wt({reference:e+"/"+t});return n?s.jsx(Ne,{children:e==="MeasureReport"?s.jsx(RW,{measureReport:n}):s.jsx(r0,{value:n})}):null}const wY="_container_1ue98_1",SY="_entry_1ue98_14",jY="_active_1ue98_21",sm={container:wY,entry:SY,active:jY};function CY(e){const t=se(),n=wt(e.value),[r,o]=p.useState();return p.useEffect(()=>{if(!n)return;const i=C0(n);if(!i)return;const a="reference"in i?i.reference:st(i);t.search("ServiceRequest","subject="+a).then(l=>{const u=l.entry.map(d=>d.resource);xR(u),u.reverse(),o(u)}).catch(l=>he({color:"red",message:De(l),autoClose:!1}))},[t,n]),r?s.jsx("div",{"data-testid":"quick-service-requests",className:sm.container,children:r.map(i=>{var a,l,c,u,d,f,h;return s.jsxs("div",{className:rt(sm.entry,{[sm.active]:i.id===(n==null?void 0:n.id)}),children:[s.jsx("p",{children:s.jsx(Ge,{to:i,children:EY(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:TY(i)})]},i.id)})}):null}function EY(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function TY(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const PY="_container_1l2dh_1",kY={container:PY};function RY(e){var o,i,a,l;const t=wt(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:kY.container,children:s.jsx(It,{defaultValue:e.defaultValue,onChange:c=>e.onChange(c.currentTarget.value),data:n})})}function _Y(e){var n,r;const t=wt(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:Fn((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:DY(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:IY(t)})]}):s.jsx(s.Fragment,{})]}):null}function DY(e){var o;const t=(o=e.collection)==null?void 0:o.collectedDateTime;if(!t)return;const n=new Date(t);return M2(O2(n,new Date))}function IY(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 M2(O2(t,n))}function M2(e){return e.toString().padStart(3,"0")+"D"}function O2(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function AY(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 NY=["Profiles"];function MY(){var b,x,C,j,T,E,_;const e=se(),{resourceType:t,id:n}=ct(),r={reference:t+"/"+n},o=Qt(),[i,a]=p.useState(),l=wt(r,a),c=AY(t),[u,d]=p.useState(()=>{const k=window.location.pathname.split("/").pop();return k&&c.map(A=>A.toLowerCase()).includes(k)?k:c[0].toLowerCase()}),f=At();async function h(){var O,U;const A=(U=(O=(await e.readHistory(t,n)).entry)==null?void 0:O.find(N=>!!N.resource))==null?void 0:U.resource;A?m(A):he({color:"red",message:"No history to restore",autoClose:!1})}function m(k){e.updateResource(Xs(k)).then(()=>{a(void 0),he({color:"green",message:"Success"})}).catch(A=>{he({color:"red",message:De(A),autoClose:!1})})}if(i)return V$(i)?s.jsxs(Ne,{children:[s.jsx(ge,{children:"Deleted"}),s.jsx("p",{children:"The resource was deleted."}),s.jsx(oe,{color:"red",onClick:h,children:"Restore"})]}):s.jsx(Mr,{outcome:i});function g(k){k||(k=c[0].toLowerCase()),d(k),o(`/${t}/${n}/${k}`)}function v(k){const A=l,O=A.orderDetail||[];O.length===0&&O.push({}),O[0].text!==k&&(O[0].text=k,m({...A,orderDetail:O}))}const S=l&&C0(l),y=l&&sK(l),w=(C=(x=(b=e.getUserConfiguration())==null?void 0:b.option)==null?void 0:x.find(k=>k.id==="statusValueSet"))==null?void 0:C.valueString;return s.jsxs(s.Fragment,{children:[(l==null?void 0:l.resourceType)==="ServiceRequest"&&w&&s.jsx(RY,{valueSet:{reference:w},defaultValue:(T=(j=l.orderDetail)==null?void 0:j[0])==null?void 0:T.text,onChange:v},st(l)+"-"+((_=(E=l.orderDetail)==null?void 0:E[0])==null?void 0:_.text)),l&&s.jsx(CY,{value:l}),l&&s.jsxs(Yn,{children:[S&&s.jsx(k2,{patient:S}),y&&s.jsx(_Y,{specimen:y}),t!=="Patient"&&s.jsx(R2,{resource:r}),s.jsx(Ir,{children:s.jsx(et,{value:u.toLowerCase(),onChange:g,children:s.jsx(et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:c.map(k=>s.jsx(et.Tab,{value:k.toLowerCase(),children:NY.includes(k)?s.jsxs(te,{gap:"xs",wrap:"nowrap",children:[k,s.jsx(ru,{color:f.primaryColor,size:"sm",children:"Beta"})]}):k},k))})})})]}),s.jsx(x0,{})]})}function PS(){var y,w,b,x;const e=Qt(),{resourceType:t,id:n,versionId:r,tab:o}=ct(),i=se(),[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(Jr,{});if(!c)return s.jsxs(Ne,{children:[s.jsx(ge,{children:"Resource not found"}),s.jsx(Ge,{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(Ne,{children:[s.jsx(ge,{children:"Version not found"}),s.jsx(Ge,{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(Yn,{children:[s.jsx(yu,{fluid:!0,p:"md",children:s.jsx(fe,{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(Ne,{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: ",(y=g.meta)==null?void 0:y.versionId]}),s.jsxs("li",{children:["Previous:"," ",s.jsx(Ge,{to:`/${t}/${n}/_history/${(w=v.meta)==null?void 0:w.versionId}`,children:(b=v.meta)==null?void 0:b.versionId})]})]}),s.jsx(cq,{original:v,revised:g})]}):s.jsxs(s.Fragment,{children:[s.jsxs("ul",{children:[s.jsxs("li",{children:["Current: ",(x=g.meta)==null?void 0:x.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 OY(){const{resourceType:e,id:t}=ct(),n=Qt(),[r,o]=p.useState({resourceType:"Subscription",filters:[{code:"url",operator:re.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return s.jsx(Ne,{children:s.jsx(vW,{search:r,onClick:i=>n(`/${i.resource.resourceType}/${i.resource.id}`),onChange:i=>o(i.definition),hideFilters:!0})})}function LY(e){const t=se(),{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?st(l):void 0,verbose:u}),he({color:"green",message:"Done"}),o()}catch(h){he({color:"red",message:De(h),autoClose:!1})}},[t,n,o,i,l,u]);return s.jsx(wn,{opened:r,onClose:o,title:"Resend Subscriptions",children:s.jsx(Ke,{onSubmit:f,children:s.jsxs(Oe,{children:[s.jsx(_n,{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(_n,{label:"Verbose mode",onChange:h=>d(h.currentTarget.checked)}),s.jsx(te,{justify:"flex-end",children:s.jsx(oe,{type:"submit",children:"Resend"})})]})})})}function kS(){const e=se(),t=Lh(),{resourceType:n,id:r}=ct(),o={reference:n+"/"+r},[i,a]=p.useState(),l=Zg(!1);function c(w,b){return e.updateResource({...w,priority:b})}function u(w,b){c(w,"stat").then(b).catch(console.error)}function d(w,b){c(w,"routine").then(b).catch(console.error)}function f(w){t(`/${w.resourceType}/${w.id}`)}function h(w){t(`/${w.resourceType}/${w.id}/edit`)}function m(w){t(`/${w.resourceType}/${w.id}/delete`)}function g(w){a(w),l[1].open()}function v(w){var b;t(`/${w.resourceType}/${w.id}/_history/${(b=w.meta)==null?void 0:b.versionId}`)}function S(w,b){e.post(e.fhirUrl(w.resourceType,w.id,"$aws-textract"),{}).then(b).catch(console.error)}function y(w){var D;const{primaryResource:b,currentResource:x,reloadTimeline:C}=w,j=x.resourceType===b.resourceType&&x.id===b.id,T=x.resourceType==="Communication"&&x.priority!=="stat",E=x.resourceType==="Communication"&&x.priority==="stat",_=j,k=!j,A=!j,O=!j,U=(D=e.getProjectMembership())==null?void 0:D.admin,N=U,F=xK()&&(x.resourceType==="DocumentReference"||x.resourceType==="Media");return s.jsxs(J.Dropdown,{children:[s.jsx(J.Label,{children:"Resource"}),T&&s.jsx(J.Item,{leftSection:s.jsx(Sz,{size:14}),onClick:()=>u(x,C),"aria-label":`Pin ${st(x)}`,children:"Pin"}),E&&s.jsx(J.Item,{leftSection:s.jsx(jz,{size:14}),onClick:()=>d(x,C),"aria-label":`Unpin ${st(x)}`,children:"Unpin"}),k&&s.jsx(J.Item,{leftSection:s.jsx(Sw,{size:14}),onClick:()=>f(x),"aria-label":`Details ${st(x)}`,children:"Details"}),_&&s.jsx(J.Item,{leftSection:s.jsx(Sw,{size:14}),onClick:()=>v(x),"aria-label":`Details ${st(x)}`,children:"Details"}),A&&s.jsx(J.Item,{leftSection:s.jsx(Nk,{size:14}),onClick:()=>h(x),"aria-label":`Edit ${st(x)}`,children:"Edit"}),U&&s.jsxs(s.Fragment,{children:[s.jsx(J.Divider,{}),s.jsx(J.Label,{children:"Admin"}),N&&s.jsx(J.Item,{leftSection:s.jsx(kz,{size:14}),onClick:()=>g(x),"aria-label":`Resend Subscriptions ${st(x)}`,children:"Resend Subscriptions"})]}),F&&s.jsxs(s.Fragment,{children:[s.jsx(J.Divider,{}),s.jsx(J.Label,{children:"AWS AI"}),s.jsx(J.Item,{leftSection:s.jsx(Oz,{size:14}),onClick:()=>S(x,C),"aria-label":`AWS Textract ${st(x)}`,children:"AWS Textract"})]}),O&&s.jsxs(s.Fragment,{children:[s.jsx(J.Divider,{}),s.jsx(J.Label,{children:"Danger zone"}),s.jsx(J.Item,{color:"red",leftSection:s.jsx(Hx,{size:14}),onClick:()=>m(x),"aria-label":`Delete ${st(x)}`,children:"Delete"})]})]})}return s.jsxs(s.Fragment,{children:[n==="Encounter"&&s.jsx(TV,{encounter:o,getMenu:y}),n==="Patient"&&s.jsx(_W,{patient:o,getMenu:y}),n==="ServiceRequest"&&s.jsx(gq,{serviceRequest:o,getMenu:y}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&s.jsx(EV,{resource:o,getMenu:y}),s.jsx(LY,{resource:i,opened:l[0],onClose:l[1].close},`resend-subscriptions-${i==null?void 0:i.id}`)]})}function $Y(){const e=se(),{id:t}=ct(),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(),[y,w]=p.useState(!1),[b,x]=p.useState(!1);p.useEffect(()=>{if(r||i||l||y){x(!0);return}x(!1)},[r,i,l,y]);const C=p.useCallback(()=>{o(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(A=>{var O,U,N,F,D,R;d((U=(O=A.parameter)==null?void 0:O.find(P=>P.name==="status"))==null?void 0:U.valueCode),h((F=(N=A.parameter)==null?void 0:N.find(P=>P.name==="version"))==null?void 0:F.valueString),g((R=(D=A.parameter)==null?void 0:D.find(P=>P.name==="lastUpdated"))==null?void 0:R.valueInstant)}).catch(A=>k(De(A))).finally(()=>o(!1))},[e,t]),j=p.useCallback(A=>{const O=A.host,U=A.pingCount||1;O&&(w(!0),e.pushToAgent(n,O,`PING ${U}`,on.PING,!0).then(N=>S(N)).catch(N=>k(De(N))).finally(()=>w(!1)))},[e,n]),T=p.useCallback(()=>{a(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(A=>{_("Agent config reloaded successfully.")}).catch(A=>k(De(A))).finally(()=>a(!1))},[e,t]),E=p.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$upgrade"),{cache:"reload"}).then(A=>{_("Agent upgraded successfully.")}).catch(A=>k(De(A))).finally(()=>c(!1))},[e,t]);function _(A){he({color:"green",title:"Success",icon:s.jsx(Ks,{size:"1rem"}),message:A})}function k(A){he({color:"red",title:"Error",message:A,autoClose:!1})}return s.jsxs(Ne,{children:[s.jsx(ge,{order:1,children:"Agent Tools"}),s.jsxs("div",{style:{marginBottom:10},children:["Agent: ",s.jsx(Cl,{value:n,link:!0})]}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(oe,{onClick:C,loading:r,disabled:b&&!r,children:"Get Status"}),!r&&u&&s.jsx(de,{children:s.jsxs(de.Tbody,{children:[s.jsxs(de.Tr,{children:[s.jsx(de.Td,{children:"Status"}),s.jsx(de.Td,{children:s.jsx(n0,{status:u})})]}),s.jsxs(de.Tr,{children:[s.jsx(de.Td,{children:"Version"}),s.jsx(de.Td,{children:f})]}),s.jsxs(de.Tr,{children:[s.jsx(de.Td,{children:"Last Updated"}),s.jsx(de.Td,{children:Fn(m,void 0,{timeZoneName:"longOffset"})})]})]})}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(oe,{onClick:T,loading:i,disabled:b&&!i,"aria-label":"Reload config",children:"Reload Config"}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(oe,{onClick:E,loading:l,disabled:b&&!l,"aria-label":"Upgrade agent",children:"Upgrade"}),s.jsx(cn,{my:"lg"}),s.jsx(ge,{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(Ke,{onSubmit:j,children:s.jsxs(te,{children:[s.jsx(ve,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:s.jsx(tn,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:y,disabled:b&&!y,children:s.jsx(_z,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),s.jsx(rx,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!y&&v&&s.jsxs(s.Fragment,{children:[s.jsx(ge,{order:5,mt:"sm",mb:0,children:"Last Ping"}),s.jsx("pre",{children:v})]})]})}function FY(){return s.jsx(FG,{children:s.jsxs(we,{errorElement:s.jsx(eK,{}),children:[s.jsx(we,{path:"/signin",element:s.jsx(EK,{})}),s.jsx(we,{path:"/oauth",element:s.jsx(bK,{})}),s.jsx(we,{path:"/resetpassword",element:s.jsx(SK,{})}),s.jsx(we,{path:"/setpassword/:id/:secret",element:s.jsx(CK,{})}),s.jsx(we,{path:"/register",element:s.jsx(wK,{})}),s.jsx(we,{path:"/changepassword",element:s.jsx(XQ,{})}),s.jsx(we,{path:"/security",element:s.jsx(jK,{})}),s.jsx(we,{path:"/mfa",element:s.jsx(yK,{})}),s.jsx(we,{path:"/batch",element:s.jsx(KQ,{})}),s.jsx(we,{path:"/bulk/:resourceType",element:s.jsx(YQ,{})}),s.jsx(we,{path:"/smart",element:s.jsx(TK,{})}),s.jsx(we,{path:"/forms/:id",element:s.jsx(lK,{})}),s.jsx(we,{path:"/admin/super",element:s.jsx(FK,{})}),s.jsx(we,{path:"/admin/config",element:s.jsx(MK,{})}),s.jsxs(we,{path:"/admin",element:s.jsx(OK,{}),children:[s.jsx(we,{path:"patients",element:s.jsx(NK,{})}),s.jsx(we,{path:"bots/new",element:s.jsx(RK,{})}),s.jsx(we,{path:"bots",element:s.jsx(PK,{})}),s.jsx(we,{path:"clients/new",element:s.jsx(_K,{})}),s.jsx(we,{path:"clients",element:s.jsx(kK,{})}),s.jsx(we,{path:"details",element:s.jsx(jS,{})}),s.jsx(we,{path:"invite",element:s.jsx(AK,{})}),s.jsx(we,{path:"users",element:s.jsx(zK,{})}),s.jsx(we,{path:"project",element:s.jsx(jS,{})}),s.jsx(we,{path:"secrets",element:s.jsx(LK,{})}),s.jsx(we,{path:"sites",element:s.jsx($K,{})}),s.jsx(we,{path:"members/:membershipId",element:s.jsx(IK,{})})]}),s.jsx(we,{path:"/lab/assays",element:s.jsx(BK,{})}),s.jsx(we,{path:"/lab/panels",element:s.jsx(UK,{})}),s.jsx(we,{path:"/:resourceType/:id/_history/:versionId/:tab",element:s.jsx(PS,{})}),s.jsx(we,{path:"/:resourceType/:id/_history/:versionId",element:s.jsx(PS,{})}),s.jsxs(we,{path:"/:resourceType/new",element:s.jsx(ZQ,{}),children:[s.jsx(we,{index:!0,element:s.jsx(im,{})}),s.jsx(we,{path:"form",element:s.jsx(im,{})}),s.jsx(we,{path:"json",element:s.jsx(dY,{})}),s.jsx(we,{path:"profiles",element:s.jsx(im,{})})]}),s.jsxs(we,{path:"/:resourceType/:id",element:s.jsx(MY,{}),children:[s.jsx(we,{index:!0,element:s.jsx(kS,{})}),s.jsx(we,{path:"apply",element:s.jsx(WK,{})}),s.jsx(we,{path:"apps",element:s.jsx(HK,{})}),s.jsx(we,{path:"event",element:s.jsx(GK,{})}),s.jsx(we,{path:"blame",element:s.jsx(QK,{})}),s.jsx(we,{path:"bots",element:s.jsx(gY,{})}),s.jsx(we,{path:"builder",element:s.jsx(rY,{})}),s.jsx(we,{path:"checklist",element:s.jsx(oY,{})}),s.jsx(we,{path:"delete",element:s.jsx(iY,{})}),s.jsx(we,{path:"details",element:s.jsx(lY,{})}),s.jsx(we,{path:"edit",element:s.jsx(cY,{})}),s.jsx(we,{path:"editor",element:s.jsx(tY,{})}),s.jsx(we,{path:"history",element:s.jsx(uY,{})}),s.jsx(we,{path:"json",element:s.jsx(fY,{})}),s.jsx(we,{path:"preview",element:s.jsx(hY,{})}),s.jsx(we,{path:"responses",element:s.jsx(yY,{})}),s.jsx(we,{path:"report",element:s.jsx(bY,{})}),s.jsx(we,{path:"ranges",element:s.jsx(xY,{})}),s.jsx(we,{path:"subscriptions",element:s.jsx(OY,{})}),s.jsx(we,{path:"timeline",element:s.jsx(kS,{})}),s.jsx(we,{path:"tools",element:s.jsx($Y,{})}),s.jsx(we,{path:"profiles",element:s.jsx(pY,{})})]}),s.jsx(we,{path:"/:resourceType",element:s.jsx(SS,{})}),s.jsx(we,{path:"/",element:s.jsx(SS,{})})]})})}function zY(){const e=se(),t=e.getUserConfiguration(),n=oi(),[r]=b0();return e.isLoading()?s.jsx(Jr,{}):s.jsx(RB,{logo:s.jsx(ro,{size:24}),pathname:n.pathname,searchParams:r,version:b8,menus:BY(t),displayAddBookmark:!!(t!=null&&t.id),children:s.jsx(p.Suspense,{fallback:s.jsx(Jr,{}),children:s.jsx(FY,{})})})}function BY(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:UY(i.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:s.jsx(vz,{})}]}),t}const RS={Patient:Az,Practitioner:mz,Organization:sz,ServiceRequest:Tz,DiagnosticReport:Rz,Questionnaire:pz,admin:rz,AccessPolicy:gz,Subscription:Lz,batch:wz,Observation:bz};function UY(e){try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in RS){const n=RS[t];return s.jsx(n,{})}}catch{}return s.jsx(Rh,{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 VY(){const e=Eu(),t=new Ck({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=VG([{path:"*",element:s.jsx(zY,{})}]),o=a=>r.navigate(a);ZR(document.getElementById("root")).render(s.jsx(p.StrictMode,{children:s.jsx(B8,{medplum:t,navigate:o,children:s.jsxs(dj,{theme:n,children:[s.jsx(ti,{position:"bottom-right"}),s.jsx(JG,{router:r})]})})}))}VY().catch(console.error);
583
+ //# sourceMappingURL=index-CbCZr6Sf.js.map