@medplum/app 4.1.14 → 4.1.16
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.
package/LICENSE.txt
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
@@ -83,7 +83,7 @@ function f3(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
|
|
|
83
83
|
*
|
|
84
84
|
* Copy of "partysocket" from Partykit team, a fork of the original "Reconnecting WebSocket"
|
|
85
85
|
* https://github.com/partykit/partykit/blob/main/packages/partysocket
|
|
86
|
-
*/const ac={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let SE=!1;function WB(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");ac.Event=globalThis.Event,ac.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},ac.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function YB(e,t){if(!e)throw new Error(t)}function oh(e){return new e.constructor(e.type,e)}const bs={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let wE=!1;class Mo extends Zp{constructor(t,n,r={}){SE||(WB(),SE=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._closeCalled=!1,this._messageQueue=[],this._debugLogger=console.log.bind(console),this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=i=>{this._debug("open event");const{minUptime:s=bs.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),YB(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(c=>{var u;return(u=this._ws)==null?void 0:u.send(c)}),this._messageQueue=[],this.onopen&&this.onopen(i),this.dispatchEvent(oh(i))},this._handleMessage=i=>{this._debug("message event"),this.onmessage&&this.onmessage(i),this.dispatchEvent(oh(i))},this._handleError=i=>{this._debug("error event",i.message),this._disconnect(void 0,i.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(i),this._debug("exec error listeners"),this.dispatchEvent(oh(i)),this._connect()},this._handleClose=i=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(i),this.dispatchEvent(oh(i))},this._url=t,this._protocols=n,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._options.binaryType?this._binaryType=this._options.binaryType:this._binaryType="blob",this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return Mo.CONNECTING}get OPEN(){return Mo.OPEN}get CLOSING(){return Mo.CLOSING}get CLOSED(){return Mo.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){var n;return this._messageQueue.reduce((r,i)=>(typeof i=="string"?r+=i.length:i instanceof Blob?r+=i.size:r+=i.byteLength,r),0)+(((n=this._ws)==null?void 0:n.bufferedAmount)??0)}get extensions(){var t;return((t=this._ws)==null?void 0:t.extensions)??""}get protocol(){var t;return((t=this._ws)==null?void 0:t.protocol)??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?Mo.CLOSED:Mo.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}close(t=1e3,n){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(t,n)}reconnect(t,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(t,n),this._connect())}send(t){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{const{maxEnqueuedMessages:n=bs.maxEnqueuedMessages}=this._options;this._messageQueue.length<n&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){const{reconnectionDelayGrowFactor:t=bs.reconnectionDelayGrowFactor,minReconnectionDelay:n=bs.minReconnectionDelay,maxReconnectionDelay:r=bs.maxReconnectionDelay}=this._options;let i=0;return this._retryCount>0&&(i=n*Math.pow(t,this._retryCount-1),i>r&&(i=r)),this._debug("next delay",i),i}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=bs.maxRetries,connectionTimeout:n=bs.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!wE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),wE=!0);const r=this._options.WebSocket||WebSocket;this._debug("connect",{url:this._url,protocols:this._protocols}),this._ws=this._protocols?new r(this._url,this._protocols):new r(this._url),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),n)}).catch(r=>{this._connectLock=!1,this._handleError(new ac.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new ac.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new ac.CloseEvent(t,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}}const KB=5e3;class $y extends Zp{constructor(...t){super(),this.criteria=new Set(t)}getCriteria(){return this.criteria}_addCriteria(t){this.criteria.add(t)}_removeCriteria(t){this.criteria.delete(t)}}class XB{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new $y(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class ZB{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof HA))throw new dt(yn("First arg of constructor should be a `MedplumClient`"));let i;try{i=new URL(n).toString()}catch{throw new dt(yn("Not a valid URL"))}const s=r!=null&&r.ReconnectingWebSocket?new r.ReconnectingWebSocket(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger}):new Mo(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new $y,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??KB,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,i,s,c,u,f;try{const h=JSON.parse(n.data);if(h.type==="pong"){this.waitingForPong=!1;return}const m=h,g=(i=(r=m==null?void 0:m.entry)==null?void 0:r[0])==null?void 0:i.resource;if(g.type==="heartbeat"){(s=this.masterSubEmitter)==null||s.dispatchEvent({type:"heartbeat",payload:m});return}if(g.type==="handshake"){const b=Bs(g.subscription),S={type:"connect",payload:{subscriptionId:b}};(c=this.masterSubEmitter)==null||c.dispatchEvent(S);const j=this.criteriaEntriesBySubscriptionId.get(b);if(!j){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}j.connecting=!1,j.emitter.dispatchEvent({...S});return}(u=this.masterSubEmitter)==null||u.dispatchEvent({type:"message",payload:m});const y=this.criteriaEntriesBySubscriptionId.get(Bs(g.subscription));if(!y){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}y.emitter.dispatchEvent({type:"message",payload:m})}catch(h){console.error(h);const m={type:"error",payload:h};(f=this.masterSubEmitter)==null||f.dispatchEvent(m);for(const g of this.getAllCriteriaEmitters())g.dispatchEvent({...m})}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new dt(l8(new Error("WebSocket error")))};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.dispatchEvent({...n})}),t.addEventListener("close",()=>{var r,i;const n={type:"close"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const s of this.getAllCriteriaEmitters())s.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),(i=this.masterSubEmitter)==null||i.removeAllListeners())}),t.addEventListener("open",()=>{var r;const n={type:"open"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{var r;const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&((r=this.currentProfile)==null?void 0:r.id)!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){var i;const r={type:"error",payload:n};(i=this.masterSubEmitter)==null||i.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){var r;const{subscriptionId:n}=t;if(n){const i={type:"disconnect",payload:{subscriptionId:n}};(r=this.masterSubEmitter)==null||r.dispatchEvent(i),t.emitter.dispatchEvent({...i})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){var c,u;let n=t==null?void 0:t.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${zt(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),i=(c=r==null?void 0:r.find(f=>f.name==="token"))==null?void 0:c.valueString,s=(u=r==null?void 0:r.find(f=>f.name==="websocket-url"))==null?void 0:u.valueUrl;if(!i)throw new dt(yn("Failed to get token"));if(!s)throw new dt(yn("Failed to get URL from $get-ws-binding-token"));return[n,i]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const i of r.criteriaWithProps)if(sa(n,i.subscriptionProps))return i}}getAllCriteriaEmitters(){const t=[];for(const n of this.criteriaEntries.values()){n.bareCriteria&&t.push(n.bareCriteria.emitter);for(const r of n.criteriaWithProps)t.push(r.emitter)}return t}addCriteriaEntry(t){const{criteria:n,subscriptionProps:r}=t;let i;this.criteriaEntries.has(n)?i=this.criteriaEntries.get(n):(i={criteriaWithProps:[]},this.criteriaEntries.set(n,i)),r?i.criteriaWithProps.push(t):i.bareCriteria=t}removeCriteriaEntry(t){var u;const{criteria:n,subscriptionProps:r,subscriptionId:i,token:s}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(f=>{const h=f.subscriptionProps;return!sa(r,h)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),(u=this.masterSubEmitter)==null||u._removeCriteria(n)),i&&this.criteriaEntriesBySubscriptionId.delete(i),s&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:s}}))}async subscribeToCriteria(t){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(Ye(n)),this.emitError(t,n),this.removeCriteriaEntry(t)}}}async refreshAllSubscriptions(){this.criteriaEntriesBySubscriptionId.clear();for(const t of this.criteriaEntries.values())for(const n of[...t.bareCriteria?[t.bareCriteria]:[],...t.criteriaWithProps])n.clearAttachedSubscription(),await this.subscribeToCriteria(n)}addCriteria(t,n){this.masterSubEmitter&&this.masterSubEmitter._addCriteria(t);const r=this.maybeGetCriteriaEntry(t,n);if(r)return r.refCount+=1,r.emitter;const i=new XB(t,n);return this.addCriteriaEntry(i),this.subscribeToCriteria(i).catch(console.error),i.emitter}removeCriteria(t,n){const r=this.maybeGetCriteriaEntry(t,n);if(!r){console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times.");return}r.refCount-=1,!(r.refCount>0)&&(this.maybeEmitDisconnect(r),this.removeCriteriaEntry(r))}getWebSocket(){return this.ws}closeWebSocket(){this.wsClosed||(this.wsClosed=!0,this.ws.close())}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new $y(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const FA="4.1.14-8896f73",JB=hn.FHIR_JSON+", */*; q=0.1",eV="https://api.medplum.com/",tV=1e3,nV=6e4,rV=0,iV=3e5,aV="Binary/",jE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Xl={ClientCredentials:"client_credentials",AuthorizationCode:"authorization_code",RefreshToken:"refresh_token",JwtBearer:"urn:ietf:params:oauth:grant-type:jwt-bearer",TokenExchange:"urn:ietf:params:oauth:grant-type:token-exchange"},oV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},sV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class HA extends Zp{constructor(t){if(super(),this.initComplete=!0,t!=null&&t.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=(t==null?void 0:t.fetch)??lV(),this.storage=(t==null?void 0:t.storage)??new GB,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=tb((t==null?void 0:t.baseUrl)??eV),this.fhirBaseUrl=Xi(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Xi(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Xi(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Xi(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=Xi(this.baseUrl,(t==null?void 0:t.fhircastHubUrl)??"fhircast/STU3"),this.clientId=(t==null?void 0:t.clientId)??"",this.clientSecret=(t==null?void 0:t.clientSecret)??"",this.credentialsInHeader=(t==null?void 0:t.authCredentialsMethod)==="header",this.defaultHeaders=(t==null?void 0:t.defaultHeaders)??{},this.onUnauthenticated=t==null?void 0:t.onUnauthenticated,this.refreshGracePeriod=(t==null?void 0:t.refreshGracePeriod)??iV,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?rV:nV),this.cacheTime>0?this.requestCache=new iA((t==null?void 0:t.resourceCacheSize)??tV):this.requestCache=void 0,t!=null&&t.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t!=null&&t.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),typeof window<"u"&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){var t;this.storage.setString("activeLogin",void 0),(t=this.requestCache)==null||t.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){var n;t=t.toString(),(n=this.requestCache)==null||n.delete(t)}invalidateAll(){var t;(t=this.requestCache)==null||t.clear()}invalidateSearches(t){const n=Xi(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let i;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?i=new Promise((c,u)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:u}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):i=this.request("GET",t,n);const s=new Ai(i);return this.setCacheEntry(t,s),s}post(t,n,r,i={}){return t=t.toString(),this.setRequestBody(i,n),r&&this.setRequestContentType(i,r),this.invalidateUrl(t),this.request("POST",t,i)}put(t,n,r,i={}){return t=t.toString(),this.setRequestBody(i,n),r&&this.setRequestContentType(i,r),this.invalidateUrl(t),this.request("PUT",t,i)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,hn.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,r)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){const{codeChallengeMethod:r,codeChallenge:i}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:i},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){const r=new URLSearchParams(window.location.search).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,i,s=!0){let c=i;s&&(c=await this.ensureCodeChallenge(i)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,c,s))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:Xl.TokenExchange,subject_token_type:oV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,i,s=!0){const c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",n),c.searchParams.set("redirect_uri",r),c.searchParams.set("scope",i.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(i)),s){const{codeChallenge:u,codeChallengeMethod:f}=i;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!u)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",u)}return c.toString()}fhirUrl(...t){return new URL(Xi(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=tU(n)),r}search(t,n,r){const i=this.fhirSearchUrl(t,n),s="search-"+i.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=this.getBundle(i,r);return this.setCacheEntry(s,u),u}searchOne(t,n,r){const i=this.fhirSearchUrl(t,n);i.searchParams.set("_count","1"),i.searchParams.sort();const s="searchOne-"+i.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=new Ai(this.search(t,i.searchParams,r).then(f=>{var h,m;return(m=(h=f.entry)==null?void 0:h[0])==null?void 0:m.resource}));return this.setCacheEntry(s,u),u}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=new Ai(this.search(t,n,r).then(TE));return this.setCacheEntry(s,u),u}async*searchResourcePages(t,n,r){var s,c;let i=this.fhirSearchUrl(t,n);for(;i;){const u=new URL(i).searchParams;u.has("_count")||u.set("_count","1000");const f=await this.search(t,u,r),h=(s=f.link)==null?void 0:s.find(m=>m.relation==="next");if(!((c=f.entry)!=null&&c.length)&&!h)break;yield TE(f),i=h!=null&&h.url?new URL(h.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){var i,s;const r=(s=(i=this.requestCache)==null?void 0:i.get(this.fhirUrl(t,n).toString()))==null?void 0:s.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return jE;const[r,i]=n.split("/");if(!(!r||!i))return this.getCached(r,i)}readResource(t,n,r){if(!n)throw new Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(t,n),r)}readReference(t,n){const r=t.reference;if(!r)return new Ai(Promise.reject(new Error("Missing reference")));if(r==="system")return new Ai(Promise.resolve(jE));const[i,s]=r.split("/");return!i||!s?new Ai(Promise.reject(new Error("Invalid reference"))):this.readResource(i,s,n)}requestSchema(t){if(dA(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const i=new Ai((async()=>{const s=`{
|
|
86
|
+
*/const ac={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let SE=!1;function WB(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");ac.Event=globalThis.Event,ac.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},ac.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function YB(e,t){if(!e)throw new Error(t)}function oh(e){return new e.constructor(e.type,e)}const bs={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let wE=!1;class Mo extends Zp{constructor(t,n,r={}){SE||(WB(),SE=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._closeCalled=!1,this._messageQueue=[],this._debugLogger=console.log.bind(console),this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=i=>{this._debug("open event");const{minUptime:s=bs.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),YB(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(c=>{var u;return(u=this._ws)==null?void 0:u.send(c)}),this._messageQueue=[],this.onopen&&this.onopen(i),this.dispatchEvent(oh(i))},this._handleMessage=i=>{this._debug("message event"),this.onmessage&&this.onmessage(i),this.dispatchEvent(oh(i))},this._handleError=i=>{this._debug("error event",i.message),this._disconnect(void 0,i.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(i),this._debug("exec error listeners"),this.dispatchEvent(oh(i)),this._connect()},this._handleClose=i=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(i),this.dispatchEvent(oh(i))},this._url=t,this._protocols=n,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._options.binaryType?this._binaryType=this._options.binaryType:this._binaryType="blob",this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return Mo.CONNECTING}get OPEN(){return Mo.OPEN}get CLOSING(){return Mo.CLOSING}get CLOSED(){return Mo.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){var n;return this._messageQueue.reduce((r,i)=>(typeof i=="string"?r+=i.length:i instanceof Blob?r+=i.size:r+=i.byteLength,r),0)+(((n=this._ws)==null?void 0:n.bufferedAmount)??0)}get extensions(){var t;return((t=this._ws)==null?void 0:t.extensions)??""}get protocol(){var t;return((t=this._ws)==null?void 0:t.protocol)??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?Mo.CLOSED:Mo.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}close(t=1e3,n){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(t,n)}reconnect(t,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(t,n),this._connect())}send(t){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{const{maxEnqueuedMessages:n=bs.maxEnqueuedMessages}=this._options;this._messageQueue.length<n&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){const{reconnectionDelayGrowFactor:t=bs.reconnectionDelayGrowFactor,minReconnectionDelay:n=bs.minReconnectionDelay,maxReconnectionDelay:r=bs.maxReconnectionDelay}=this._options;let i=0;return this._retryCount>0&&(i=n*Math.pow(t,this._retryCount-1),i>r&&(i=r)),this._debug("next delay",i),i}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=bs.maxRetries,connectionTimeout:n=bs.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!wE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),wE=!0);const r=this._options.WebSocket||WebSocket;this._debug("connect",{url:this._url,protocols:this._protocols}),this._ws=this._protocols?new r(this._url,this._protocols):new r(this._url),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),n)}).catch(r=>{this._connectLock=!1,this._handleError(new ac.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new ac.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new ac.CloseEvent(t,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}}const KB=5e3;class $y extends Zp{constructor(...t){super(),this.criteria=new Set(t)}getCriteria(){return this.criteria}_addCriteria(t){this.criteria.add(t)}_removeCriteria(t){this.criteria.delete(t)}}class XB{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new $y(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class ZB{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof HA))throw new dt(yn("First arg of constructor should be a `MedplumClient`"));let i;try{i=new URL(n).toString()}catch{throw new dt(yn("Not a valid URL"))}const s=r!=null&&r.ReconnectingWebSocket?new r.ReconnectingWebSocket(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger}):new Mo(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new $y,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??KB,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,i,s,c,u,f;try{const h=JSON.parse(n.data);if(h.type==="pong"){this.waitingForPong=!1;return}const m=h,g=(i=(r=m==null?void 0:m.entry)==null?void 0:r[0])==null?void 0:i.resource;if(g.type==="heartbeat"){(s=this.masterSubEmitter)==null||s.dispatchEvent({type:"heartbeat",payload:m});return}if(g.type==="handshake"){const b=Bs(g.subscription),S={type:"connect",payload:{subscriptionId:b}};(c=this.masterSubEmitter)==null||c.dispatchEvent(S);const j=this.criteriaEntriesBySubscriptionId.get(b);if(!j){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}j.connecting=!1,j.emitter.dispatchEvent({...S});return}(u=this.masterSubEmitter)==null||u.dispatchEvent({type:"message",payload:m});const y=this.criteriaEntriesBySubscriptionId.get(Bs(g.subscription));if(!y){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}y.emitter.dispatchEvent({type:"message",payload:m})}catch(h){console.error(h);const m={type:"error",payload:h};(f=this.masterSubEmitter)==null||f.dispatchEvent(m);for(const g of this.getAllCriteriaEmitters())g.dispatchEvent({...m})}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new dt(l8(new Error("WebSocket error")))};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.dispatchEvent({...n})}),t.addEventListener("close",()=>{var r,i;const n={type:"close"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const s of this.getAllCriteriaEmitters())s.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),(i=this.masterSubEmitter)==null||i.removeAllListeners())}),t.addEventListener("open",()=>{var r;const n={type:"open"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{var r;const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&((r=this.currentProfile)==null?void 0:r.id)!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){var i;const r={type:"error",payload:n};(i=this.masterSubEmitter)==null||i.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){var r;const{subscriptionId:n}=t;if(n){const i={type:"disconnect",payload:{subscriptionId:n}};(r=this.masterSubEmitter)==null||r.dispatchEvent(i),t.emitter.dispatchEvent({...i})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){var c,u;let n=t==null?void 0:t.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${zt(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),i=(c=r==null?void 0:r.find(f=>f.name==="token"))==null?void 0:c.valueString,s=(u=r==null?void 0:r.find(f=>f.name==="websocket-url"))==null?void 0:u.valueUrl;if(!i)throw new dt(yn("Failed to get token"));if(!s)throw new dt(yn("Failed to get URL from $get-ws-binding-token"));return[n,i]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const i of r.criteriaWithProps)if(sa(n,i.subscriptionProps))return i}}getAllCriteriaEmitters(){const t=[];for(const n of this.criteriaEntries.values()){n.bareCriteria&&t.push(n.bareCriteria.emitter);for(const r of n.criteriaWithProps)t.push(r.emitter)}return t}addCriteriaEntry(t){const{criteria:n,subscriptionProps:r}=t;let i;this.criteriaEntries.has(n)?i=this.criteriaEntries.get(n):(i={criteriaWithProps:[]},this.criteriaEntries.set(n,i)),r?i.criteriaWithProps.push(t):i.bareCriteria=t}removeCriteriaEntry(t){var u;const{criteria:n,subscriptionProps:r,subscriptionId:i,token:s}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(f=>{const h=f.subscriptionProps;return!sa(r,h)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),(u=this.masterSubEmitter)==null||u._removeCriteria(n)),i&&this.criteriaEntriesBySubscriptionId.delete(i),s&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:s}}))}async subscribeToCriteria(t){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(Ye(n)),this.emitError(t,n),this.removeCriteriaEntry(t)}}}async refreshAllSubscriptions(){this.criteriaEntriesBySubscriptionId.clear();for(const t of this.criteriaEntries.values())for(const n of[...t.bareCriteria?[t.bareCriteria]:[],...t.criteriaWithProps])n.clearAttachedSubscription(),await this.subscribeToCriteria(n)}addCriteria(t,n){this.masterSubEmitter&&this.masterSubEmitter._addCriteria(t);const r=this.maybeGetCriteriaEntry(t,n);if(r)return r.refCount+=1,r.emitter;const i=new XB(t,n);return this.addCriteriaEntry(i),this.subscribeToCriteria(i).catch(console.error),i.emitter}removeCriteria(t,n){const r=this.maybeGetCriteriaEntry(t,n);if(!r){console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times.");return}r.refCount-=1,!(r.refCount>0)&&(this.maybeEmitDisconnect(r),this.removeCriteriaEntry(r))}getWebSocket(){return this.ws}closeWebSocket(){this.wsClosed||(this.wsClosed=!0,this.ws.close())}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new $y(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const FA="4.1.16-5f9948e",JB=hn.FHIR_JSON+", */*; q=0.1",eV="https://api.medplum.com/",tV=1e3,nV=6e4,rV=0,iV=3e5,aV="Binary/",jE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Xl={ClientCredentials:"client_credentials",AuthorizationCode:"authorization_code",RefreshToken:"refresh_token",JwtBearer:"urn:ietf:params:oauth:grant-type:jwt-bearer",TokenExchange:"urn:ietf:params:oauth:grant-type:token-exchange"},oV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},sV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class HA extends Zp{constructor(t){if(super(),this.initComplete=!0,t!=null&&t.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=(t==null?void 0:t.fetch)??lV(),this.storage=(t==null?void 0:t.storage)??new GB,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=tb((t==null?void 0:t.baseUrl)??eV),this.fhirBaseUrl=Xi(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Xi(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Xi(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Xi(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=Xi(this.baseUrl,(t==null?void 0:t.fhircastHubUrl)??"fhircast/STU3"),this.clientId=(t==null?void 0:t.clientId)??"",this.clientSecret=(t==null?void 0:t.clientSecret)??"",this.credentialsInHeader=(t==null?void 0:t.authCredentialsMethod)==="header",this.defaultHeaders=(t==null?void 0:t.defaultHeaders)??{},this.onUnauthenticated=t==null?void 0:t.onUnauthenticated,this.refreshGracePeriod=(t==null?void 0:t.refreshGracePeriod)??iV,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?rV:nV),this.cacheTime>0?this.requestCache=new iA((t==null?void 0:t.resourceCacheSize)??tV):this.requestCache=void 0,t!=null&&t.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t!=null&&t.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),typeof window<"u"&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){var t;this.storage.setString("activeLogin",void 0),(t=this.requestCache)==null||t.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){var n;t=t.toString(),(n=this.requestCache)==null||n.delete(t)}invalidateAll(){var t;(t=this.requestCache)==null||t.clear()}invalidateSearches(t){const n=Xi(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let i;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?i=new Promise((c,u)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:u}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):i=this.request("GET",t,n);const s=new Ai(i);return this.setCacheEntry(t,s),s}post(t,n,r,i={}){return t=t.toString(),this.setRequestBody(i,n),r&&this.setRequestContentType(i,r),this.invalidateUrl(t),this.request("POST",t,i)}put(t,n,r,i={}){return t=t.toString(),this.setRequestBody(i,n),r&&this.setRequestContentType(i,r),this.invalidateUrl(t),this.request("PUT",t,i)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,hn.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,r)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){const{codeChallengeMethod:r,codeChallenge:i}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:i},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){const r=new URLSearchParams(window.location.search).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,i,s=!0){let c=i;s&&(c=await this.ensureCodeChallenge(i)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,c,s))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:Xl.TokenExchange,subject_token_type:oV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,i,s=!0){const c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",n),c.searchParams.set("redirect_uri",r),c.searchParams.set("scope",i.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(i)),s){const{codeChallenge:u,codeChallengeMethod:f}=i;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!u)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",u)}return c.toString()}fhirUrl(...t){return new URL(Xi(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=tU(n)),r}search(t,n,r){const i=this.fhirSearchUrl(t,n),s="search-"+i.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=this.getBundle(i,r);return this.setCacheEntry(s,u),u}searchOne(t,n,r){const i=this.fhirSearchUrl(t,n);i.searchParams.set("_count","1"),i.searchParams.sort();const s="searchOne-"+i.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=new Ai(this.search(t,i.searchParams,r).then(f=>{var h,m;return(m=(h=f.entry)==null?void 0:h[0])==null?void 0:m.resource}));return this.setCacheEntry(s,u),u}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=new Ai(this.search(t,n,r).then(TE));return this.setCacheEntry(s,u),u}async*searchResourcePages(t,n,r){var s,c;let i=this.fhirSearchUrl(t,n);for(;i;){const u=new URL(i).searchParams;u.has("_count")||u.set("_count","1000");const f=await this.search(t,u,r),h=(s=f.link)==null?void 0:s.find(m=>m.relation==="next");if(!((c=f.entry)!=null&&c.length)&&!h)break;yield TE(f),i=h!=null&&h.url?new URL(h.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){var i,s;const r=(s=(i=this.requestCache)==null?void 0:i.get(this.fhirUrl(t,n).toString()))==null?void 0:s.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return jE;const[r,i]=n.split("/");if(!(!r||!i))return this.getCached(r,i)}readResource(t,n,r){if(!n)throw new Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(t,n),r)}readReference(t,n){const r=t.reference;if(!r)return new Ai(Promise.reject(new Error("Missing reference")));if(r==="system")return new Ai(Promise.resolve(jE));const[i,s]=r.split("/");return!i||!s?new Ai(Promise.reject(new Error("Invalid reference"))):this.readResource(i,s,n)}requestSchema(t){if(dA(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const i=new Ai((async()=>{const s=`{
|
|
87
87
|
StructureDefinitionList(_filter: "name eq ${t}") {
|
|
88
88
|
resourceType,
|
|
89
89
|
name,
|
|
@@ -583,4 +583,4 @@ Please change the parent <Route path="${D}"> to <Route path="${D==="/"?"*":`${D}
|
|
|
583
583
|
}
|
|
584
584
|
]
|
|
585
585
|
}`,YJ="MSH|^~\\&|ADT1|MCM|LABADT|MCM|198808181126|SECURITY|ADT|MSG00001|P|2.1\rPID|||PATID1234^5^M11||JONES^WILLIAM^A^III||19610615|M-||C|1200 N ELM STREET^^GREENSBORO^NC^27401-1020|GL|(919)379-1212|(919)271-3434||S||PATID12345001^2^M10|123456789|987654^NC\rNK1|1|JONES^BARBARA^K|SPO|||||20011105\rPV1|1|I|2000^2012^01||||004777^LEBAUER^SIDNEY^J.|||SUR||-||1|A0-";function KJ(){const e=_e(),{id:t}=qt(),[n,r]=v.useState(),[i,s]=v.useState(),[c,u]=v.useState(WJ),[f,h]=v.useState(YJ),[m,g]=v.useState(hn.FHIR_JSON),y=v.useRef(null),b=v.useRef(null),[S,j]=v.useState(!1);v.useEffect(()=>{e.readResource("Bot",t).then(async k=>{r(k),s(await XJ(e,k))}).catch(k=>Oe({color:"red",message:Ye(k),autoClose:!1}))},[e,t]);const C=v.useCallback(async()=>Yu(y.current,{command:"getValue"}),[]),T=v.useCallback(async()=>Yu(y.current,{command:"getOutput"}),[]),D=v.useCallback(async()=>m===hn.FHIR_JSON?JSON.parse(c):f,[m,c,f]),E=v.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),j(!0);try{const M=await C(),I=await T(),$=await e.createAttachment({data:M,filename:"index.ts",contentType:"text/typescript"}),V=await e.createAttachment({data:I,filename:"index.js",contentType:"text/typescript"}),Y=[{op:"add",path:"/sourceCode",value:$},{op:"add",path:"/executableCode",value:V}];await e.patchResource("Bot",t,Y),Oe({color:"green",message:"Saved"})}catch(M){Oe({color:"red",message:Ye(M),autoClose:!1})}finally{j(!1)}},[e,t,C,T]),R=v.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),j(!0);try{await e.post(e.fhirUrl("Bot",t,"$deploy")),Oe({color:"green",message:"Deployed"})}catch(M){Oe({color:"red",message:Ye(M),autoClose:!1})}finally{j(!1)}},[e,t]),A=v.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),j(!0);try{const M=await D(),I=await e.post(e.fhirUrl("Bot",t,"$execute"),M,m);await Yu(b.current,{command:"setValue",value:I}),Oe({color:"green",message:"Success"})}catch(M){Oe({color:"red",message:Ye(M),autoClose:!1})}finally{j(!1)}},[e,t,D,m]);return!n||i===void 0?null:o.jsxs(or,{m:0,gutter:0,style:{overflow:"hidden"},children:[o.jsx(or.Col,{span:8,children:o.jsxs(mr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[o.jsx(QJ,{iframeRef:y,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:i,minHeight:"528px"}),o.jsxs(Ce,{justify:"flex-end",gap:"xs",children:[o.jsx(Ne,{type:"button",onClick:E,loading:S,leftSection:o.jsx(JV,{size:"1rem"}),children:"Save"}),o.jsx(Ne,{type:"button",onClick:R,loading:S,leftSection:o.jsx(gb,{size:"1rem"}),children:"Deploy"}),o.jsx(Ne,{type:"button",onClick:A,loading:S,leftSection:o.jsx(pF,{size:"1rem"}),children:"Execute"})]})]})}),o.jsxs(or.Col,{span:4,children:[o.jsxs(mr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[o.jsx(ln,{data:[{label:"FHIR",value:hn.FHIR_JSON},{label:"HL7",value:hn.HL7_V2}],onChange:k=>g(k.currentTarget.value)}),m===hn.FHIR_JSON?o.jsx(Dc,{value:c,onChange:k=>u(k),autosize:!0,minRows:15}):o.jsx("textarea",{className:qJ.hl7Input,value:f,onChange:k=>h(k.currentTarget.value),rows:15})]}),o.jsx(mr,{m:2,p:"xs",shadow:"md",children:o.jsx(GJ,{iframeRef:b,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function XJ(e,t){var n,r,i;if((n=t.sourceCode)!=null&&n.url){const s=(i=(r=t.sourceCode.url)==null?void 0:r.split("/"))==null?void 0:i.find(SA);return(await e.download(e.fhirUrl("Binary",s))).text()}return t.code??""}function sl(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function ZJ(){const e=_e(),{resourceType:t,id:n}=qt(),r={reference:t+"/"+n},i=v.useCallback(s=>{e.updateResource(sl(s)).then(()=>{Oe({color:"green",message:"Success"})}).catch(c=>{Oe({color:"red",message:Ye(c),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return o.jsx(ot,{children:o.jsx(WQ,{value:r,onSubmit:i})});case"Questionnaire":return o.jsx(ot,{children:o.jsx(MW,{questionnaire:r,onSubmit:i})});default:return null}}function JJ(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t}),r=wn();return n?o.jsx(ot,{children:o.jsx(oY,{value:n,onStart:(i,s)=>{var c;return(c=r(`/forms/${Bs(s)}`))==null?void 0:c.catch(console.error)},onEdit:(i,s,c)=>{var u;return(u=r(`/${c.reference}}`))==null?void 0:u.catch(console.error)}})}):null}function eee(){const e=_e(),{resourceType:t,id:n}=qt(),r=wn();return o.jsxs(ot,{children:[o.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),o.jsx(Ne,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>{var i;return(i=r(`/${t}`))==null?void 0:i.catch(console.error)}).catch(i=>Oe({color:"red",message:Ye(i),autoClose:!1}))},children:"Delete"})]})}const tee="_selectProfileBtn_tbaz6_1",nee="_chevron_tbaz6_13",JT={selectProfileBtn:tee,chevron:nee};function ree(){var f,h;const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t}),[r,i]=v.useState(),s=xd({onDropdownClose:()=>s.resetSelectedOption()}),c=v.useMemo(()=>{var m;if(Tn((m=n==null?void 0:n.meta)==null?void 0:m.profile))return[o.jsx(ct.Option,{value:"",children:"None"},""),...n.meta.profile.map(g=>o.jsx(ct.Option,{value:g,children:g},g))]},[(f=n==null?void 0:n.meta)==null?void 0:f.profile]);if(v.useEffect(()=>{var m,g;((g=(m=n==null?void 0:n.meta)==null?void 0:m.profile)==null?void 0:g.length)===1&&i(n.meta.profile[0])},[(h=n==null?void 0:n.meta)==null?void 0:h.profile]),!n)return null;let u;return Tn(c)&&(u=o.jsx(Ce,{justify:"flex-end",children:o.jsxs(Ge,{align:"flex-end",gap:"xs",children:[o.jsxs(ct,{store:s,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:m=>{i(m),s.closeDropdown()},children:[o.jsx(ct.Target,{children:o.jsx(tr,{onClick:()=>s.toggleDropdown(),children:o.jsxs(f0,{fw:"bold",fs:"sm",className:JT.selectProfileBtn,children:[o.jsx("span",{children:"Pick profile"}),o.jsx(mb,{stroke:1.5,className:JT.chevron})]})})}),o.jsx(ct.Dropdown,{w:"max-content",children:o.jsx(ct.Options,{children:c})})]}),o.jsx(ce,{children:r?o.jsxs(o.Fragment,{children:[o.jsx(Ae,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),o.jsx(Ae,{span:!0,size:"sm",children:r||"Nothing selected"})]}):o.jsx(Ae,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),o.jsx(ot,{children:o.jsxs(Ge,{gap:"xl",children:[u,o.jsx(Nb,{value:n,profileUrl:r})]})})}function iee(){const e=_e(),{resourceType:t,id:n}=qt(),[r,i]=v.useState(),[s,c]=v.useState(),u=wn(),[f,h]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(b=>{i(Qr(b)),c(Qr(b))}).catch(b=>{h(Zt(b)),Oe({color:"red",message:Ye(b),autoClose:!1})})},[e,t,n]);const m=v.useCallback(b=>{h(void 0),e.updateResource(sl(b)).then(()=>{var S;(S=u(`/${t}/${n}/details`))==null||S.catch(console.error),Oe({id:"succes",color:"green",message:"Success"})}).catch(S=>{h(Zt(S)),Oe({color:"red",message:Ye(S),autoClose:!1})})},[e,t,n,u]),g=v.useCallback(b=>{h(void 0);const S=L_.createPatch(r,b);e.patchResource(t,n,S).then(()=>{var j;(j=u(`/${t}/${n}/details`))==null||j.catch(console.error),Oe({id:"succes",color:"green",message:"Success"})}).catch(j=>{h(Zt(j)),Oe({color:"red",message:Ye(j),autoClose:!1})})},[e,t,n,r,u]),y=v.useCallback(()=>{var b;return(b=u(`/${t}/${n}/delete`))==null?void 0:b.catch(console.error)},[u,t,n]);return s?o.jsx(ot,{children:o.jsx(Yh,{defaultValue:s,onSubmit:m,onPatch:g,onDelete:y,outcome:f})}):null}function aee(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t});return n?o.jsx(ot,{maw:700,children:n.resourceType==="Patient"?o.jsx(VQ,{patient:n}):o.jsx(Ya,{icon:o.jsx(rl,{size:16}),title:"Unsupported export type",color:"red",children:"This page is only supported for Patient resources"})}):null}function n4({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,i=_e(),[s,c]=v.useState();return v.useEffect(()=>{i.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(u=>{c(u.filter(cq))}).catch(console.error)},[i,n,r]),o.jsx(Et,{value:t==null?void 0:t.url,onChange:u=>{const f=s==null?void 0:s.find(h=>h.url===u);f&&n(f)},children:o.jsx(Et.List,{children:s==null?void 0:s.map(u=>{var m,g;const f=(g=(m=e.meta)==null?void 0:m.profile)==null?void 0:g.includes(u.url),h=f?"This profile is present in this resource's meta.profile property.":"This profile is not included in this resource's meta.profile property.";return o.jsx(Et.Tab,{value:u.url,title:h,rightSection:f&&o.jsx(G0,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:o.jsx(TF,{size:"90%"})}),children:u.title||u.name},u.url)})})})}function r4(e,t){const n=_e(),r=wn();return{defaultValue:{resourceType:e},handleSubmit:c=>{t&&t(void 0),n.createResource(c).then(u=>r("/"+u.resourceType+"/"+u.id)).catch(u=>{t&&t(Zt(u)),Oe({color:"red",message:Ye(u),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function py(){const{resourceType:e}=qt(),t=Mr(),[n,r]=v.useState(),{defaultValue:i,handleSubmit:s}=r4(e,r),[c,u]=v.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),h=v.useCallback(m=>{const g=sl(m);c&&TA(g,c.url),s(g)},[c,s]);return f?o.jsx(ot,{children:o.jsxs(Ge,{children:[o.jsx(n4,{resource:i,currentProfile:c,onChange:u}),c?o.jsx(Yh,{defaultValue:i,onSubmit:h,outcome:n,profileUrl:c.url},c.url):o.jsx(Ae,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):o.jsx(ot,{children:o.jsx(Yh,{defaultValue:i,onSubmit:s,outcome:n})})}function oee(){const e=_e(),{resourceType:t,id:n}=qt(),r=e.readHistory(t,n).read();return o.jsx(ot,{children:o.jsx(kY,{history:r})})}function see(){const{resourceType:e}=qt(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:i}=r4(e,n),s=v.useCallback(c=>{i(JSON.parse(c["new-resource"]))},[i]);return o.jsxs(ot,{children:[t&&o.jsx(Kr,{outcome:t}),o.jsxs(pt,{onSubmit:s,children:[o.jsx(Dc,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:Ii(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),o.jsx(Ce,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:o.jsx(Ne,{type:"submit",children:"OK"})})]})]})}function lee(){const e=_e(),{resourceType:t,id:n}=qt(),r=Qt({reference:t+"/"+n}),i=wn(),[s,c]=v.useState(),u=v.useCallback(f=>{e.updateResource(sl(JSON.parse(f.resource))).then(()=>{var h;c(void 0),(h=i(`/${t}/${n}/details`))==null||h.catch(console.error),Oe({color:"green",message:"Success"})}).catch(h=>{Oe({color:"red",message:Ye(h),autoClose:!1})})},[e,t,n,i]);return r?o.jsxs(ot,{children:[s&&o.jsx(Kr,{outcome:s}),o.jsxs(pt,{onSubmit:u,children:[o.jsx(Dc,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:Ii(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),o.jsx(Ce,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:o.jsx(Ne,{type:"submit",children:"OK"})})]})]}):null}function cee(){const{resourceType:e,id:t}=qt();return Qt({reference:e+"/"+t})?o.jsxs(ot,{children:[o.jsxs(Ya,{icon:o.jsx(rl,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",o.jsx("br",{}),o.jsx(Nt,{href:`/forms/${t}`,children:`/forms/${t}`})]}),o.jsx(ck,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function uee(){const e=_e(),{resourceType:t,id:n}=qt(),[r,i]=v.useState(),[s,c]=v.useState();return v.useEffect(()=>{e.readResource(t,n).then(u=>i(Qr(u))).catch(u=>{Oe({color:"red",message:Ye(u)})})},[e,t,n]),r?o.jsxs(ot,{children:[o.jsxs(Le,{order:2,children:["Available ",t," profiles"]}),o.jsx(Ge,{children:o.jsxs(o.Fragment,{children:[o.jsx(n4,{resource:r,currentProfile:s,onChange:c}),s?o.jsx(dee,{profile:s,resource:r,onResourceUpdated:u=>i(u)},s.url):o.jsx(Ae,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const dee=({profile:e,resource:t,onResourceUpdated:n})=>{const r=_e(),[i,s]=v.useState(),[c,u]=v.useState(()=>{var h,m;return(m=(h=t.meta)==null?void 0:h.profile)==null?void 0:m.includes(e.url)}),f=v.useCallback(h=>{s(void 0);const m=sl(h);c?TA(m,e.url):nU(m,e.url),r.updateResource(m).then(g=>{n(g),Oe({color:"green",message:"Success"})}).catch(g=>{s(Zt(g)),Oe({color:"red",message:Ye(g),autoClose:!1})})},[r,e.url,n,c]);return o.jsxs(Ge,{children:[o.jsx(Cd,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:h=>u(h.currentTarget.checked),"data-testid":"profile-toggle"}),c?o.jsx(Yh,{profileUrl:e.url,defaultValue:t,onSubmit:f,outcome:i}):o.jsx("form",{noValidate:!0,onSubmit:h=>{h.preventDefault(),f(t)},children:o.jsx(Ce,{justify:"flex-end",mt:"xl",children:o.jsx(Ne,{type:"submit",children:"OK"})})})]})},i4={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},fee=Object.keys(i4);function hee(){const e=_e(),{id:t}=qt(),n=Qt({reference:`Questionnaire/${t}`}),[r,i]=v.useState(),[s,c]=v.useState("create"),[u,f]=v.useState(0),h=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>pee(g,n));function m(){r&&n&&e.createResource({resourceType:"Subscription",status:"active",reason:`Connect bot ${r.name} to questionnaire responses`,criteria:`QuestionnaireResponse?questionnaire=${n.url?`${n.url},${zt(n)}`:zt(n)}`,channel:{type:"rest-hook",endpoint:zt(r)},...s?{extension:[{url:"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",valueCode:s}]}:void 0}).then(()=>{i(void 0),f(Date.now()),e.invalidateSearches("Subscription"),Oe({color:"green",message:"Success"})}).catch(g=>Oe({color:"red",message:Ye(g),autoClose:!1}))}return o.jsxs(ot,{children:[o.jsx(Le,{children:"Bots"}),o.jsxs(Ge,{children:[h.length===0&&o.jsx("p",{children:"No bots found."}),h.map(g=>{var y;return o.jsxs("div",{children:[o.jsx("h3",{children:o.jsx(Lc,{value:{reference:(y=g.channel)==null?void 0:y.endpoint},link:!0})}),o.jsxs("p",{children:["Criteria: ",g.criteria]})]},g.id)})]}),o.jsx(Cn,{}),o.jsxs(Ge,{mt:10,children:[o.jsx(md,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),o.jsxs(Ce,{children:[o.jsx(il,{name:"bot",resourceType:"Bot",onChange:g=>i(g)}),o.jsx(Ne,{onClick:m,children:"Connect"})]}),o.jsx(Ce,{children:o.jsx(ln,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:fee,onChange:g=>c(i4[g.target.value])})})]}),o.jsx("div",{style:{display:"none"},children:u})]})}function pee(e,t){var i;if(!t)return!1;const n=e.criteria||"",r=((i=e.channel)==null?void 0:i.endpoint)||"";return n.startsWith("QuestionnaireResponse?")&&r.startsWith("Bot/")&&(n.includes(zt(t))||(t.url?n.includes(t.url):!1))}function mee(){const{id:e}=qt(),t=wn(),r=_e().readReference({reference:`Questionnaire/${e}`}).read(),[i,s]=v.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:ue.EQUALS,value:r.url?`${r.url},Questionnaire/${e}`:`Questionnaire/${e}`}],fields:["id","_lastUpdated"]});return o.jsx(ot,{children:o.jsx(zc,{search:i,onClick:c=>{var u;return(u=t(`/${c.resource.resourceType}/${c.resource.id}`))==null?void 0:u.catch(console.error)},onChange:c=>s(c.definition),hideFilters:!0,hideToolbar:!0})})}function gee(){const e=_e(),{resourceType:t,id:n}=qt(),r=Qt({reference:t+"/"+n}),i=v.useCallback(s=>{e.updateResource(sl(s)).then(()=>{Oe({color:"green",message:"Success"})}).catch(c=>{Oe({color:"red",message:Ye(c),autoClose:!1})})},[e]);return r?o.jsx(ot,{children:o.jsx(ZW,{onSubmit:i,definition:r})}):null}function vee(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t});return n?o.jsx(ot,{children:e==="MeasureReport"?o.jsx(UQ,{measureReport:n}):o.jsx(Pb,{value:n})}):null}const yee="_container_1ue98_1",xee="_entry_1ue98_14",bee="_active_1ue98_21",my={container:yee,entry:xee,active:bee};function See(e){const t=_e(),n=Qt(e.value),[r,i]=v.useState();return v.useEffect(()=>{if(!n)return;const s=r1(n);if(!s)return;const c="reference"in s?s.reference:zt(s);t.search("ServiceRequest","subject="+c).then(u=>{const h=(u.entry??[]).map(m=>m.resource);z_(h),h.reverse(),i(h)}).catch(u=>Oe({color:"red",message:Ye(u),autoClose:!1}))},[t,n]),r?o.jsx("div",{"data-testid":"quick-service-requests",className:my.container,children:r.map(s=>{var c,u,f,h,m,g,y;return o.jsxs("div",{className:Ut(my.entry,{[my.active]:s.id===(n==null?void 0:n.id)}),children:[o.jsx("p",{children:o.jsx(mt,{to:s,children:wee(s)})}),((u=(c=s.category)==null?void 0:c[0])==null?void 0:u.text)&&o.jsx("p",{children:(f=s.category[0])==null?void 0:f.text}),((g=(m=(h=s.code)==null?void 0:h.coding)==null?void 0:m[0])==null?void 0:g.code)&&o.jsx("p",{children:(y=s.code.coding[0])==null?void 0:y.code}),o.jsx("p",{children:jee(s)})]},s.id)})}):null}function wee(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function jee(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const Cee="_container_1l2dh_1",Eee={container:Cee};function Tee(e){var i,s,c,u;const t=Qt(e.valueSet);if(!t)return null;const n=[""],r=(u=(c=(s=(i=t.compose)==null?void 0:i.include)==null?void 0:s[0])==null?void 0:c.concept)==null?void 0:u.map(f=>f.code);return r&&n.push(...r),e.defaultValue&&!n.includes(e.defaultValue)&&n.push(e.defaultValue),o.jsx("div",{className:Eee.container,children:o.jsx(ln,{defaultValue:e.defaultValue,onChange:f=>e.onChange(f.currentTarget.value),data:n})})}function Ree(e){var n,r;const t=Qt(e.specimen);return t?o.jsxs(ht,{children:[o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Type"}),o.jsx(ht.Value,{children:"Specimen"})]}),o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Collected"}),o.jsx(ht.Value,{children:gr((n=t.collection)==null?void 0:n.collectedDateTime)})]}),o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Specimen Age"}),o.jsx(ht.Value,{children:Dee(t)})]}),(r=t.collection)!=null&&r.collectedDateTime&&t.receivedTime?o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Specimen Stability"}),o.jsx(ht.Value,{children:Aee(t)})]}):o.jsx(o.Fragment,{})]}):null}function Dee(e){var i;const t=(i=e.collection)==null?void 0:i.collectedDateTime;if(!t)return;const n=new Date(t);return a4(o4(n,new Date))}function Aee(e){var r;if(!((r=e.collection)!=null&&r.collectedDateTime)||!e.receivedTime)return;const t=new Date(e.collection.collectedDateTime),n=new Date(e.receivedTime);return a4(o4(t,n))}function a4(e){return e.toString().padStart(3,"0")+"D"}function o4(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function _ee(e){const t=["Timeline"];return e==="Bot"&&t.push("Editor","Subscriptions"),e==="PlanDefinition"&&t.push("Apply","Builder"),e==="Questionnaire"&&t.push("Preview","Builder","Bots","Responses"),(e==="DiagnosticReport"||e==="MeasureReport")&&t.push("Report"),e==="RequestGroup"&&t.push("Checklist"),e==="ObservationDefinition"&&t.push("Ranges"),e==="Agent"&&t.push("Tools"),t.push("Details","Edit","Event","History","Blame","JSON","Apps","Profiles"),e==="Patient"&&t.push("Export"),t}function kee(){var D,E,R,A,k,M,I;const e=_e(),{resourceType:t,id:n}=qt(),r={reference:t+"/"+n},i=wn(),[s,c]=v.useState(),u=Qt(r,c),f=_ee(t),[h,m]=v.useState(()=>{const $=window.location.pathname.split("/").pop();return $&&f.map(V=>V.toLowerCase()).includes($)?$:f[0].toLowerCase()});async function g(){var Y,Q;const V=(Q=(Y=(await e.readHistory(t,n)).entry)==null?void 0:Y.find(J=>!!J.resource))==null?void 0:Q.resource;V?y(V):Oe({color:"red",message:"No history to restore",autoClose:!1})}function y($){e.updateResource(sl($)).then(()=>{c(void 0),Oe({color:"green",message:"Success"})}).catch(V=>{Oe({color:"red",message:Ye(V),autoClose:!1})})}if(s)return u8(s)?o.jsxs(ot,{children:[o.jsx(Le,{children:"Deleted"}),o.jsx("p",{children:"The resource was deleted."}),o.jsx(Ne,{color:"red",onClick:g,children:"Restore"})]}):o.jsx(Kr,{outcome:s});function b($){var V;$||($=f[0].toLowerCase()),m($),(V=i(`/${t}/${n}/${$}`))==null||V.catch(console.error)}function S($){const V=u,Y=V.orderDetail||[];Y.length===0&&Y.push({}),Y[0].text!==$&&(Y[0].text=$,y({...V,orderDetail:Y}))}const j=u&&r1(u),C=u&&YZ(u),T=(R=(E=(D=e.getUserConfiguration())==null?void 0:D.option)==null?void 0:E.find($=>$.id==="statusValueSet"))==null?void 0:R.valueString;return o.jsxs(o.Fragment,{children:[(u==null?void 0:u.resourceType)==="ServiceRequest"&&T&&o.jsx(Tee,{valueSet:{reference:T},defaultValue:(k=(A=u.orderDetail)==null?void 0:A[0])==null?void 0:k.text,onChange:S},zt(u)+"-"+((I=(M=u.orderDetail)==null?void 0:M[0])==null?void 0:I.text)),u&&o.jsx(See,{value:u}),u&&o.jsxs(mr,{children:[j&&o.jsx(G_,{patient:j}),C&&o.jsx(Ree,{specimen:C}),t!=="Patient"&&o.jsx(Yk,{resource:r}),o.jsx(Yr,{children:o.jsx(Et,{value:h.toLowerCase(),onChange:b,children:o.jsx(Et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:f.map($=>o.jsx(Et.Tab,{value:$.toLowerCase(),children:$},$))})})})]}),o.jsx(Kb,{})]})}function eR(){var T,D,E,R;const e=wn(),{resourceType:t,id:n,versionId:r,tab:i}=qt(),s=_e(),[c,u]=v.useState(!0),[f,h]=v.useState(),[m,g]=v.useState();if(v.useEffect(()=>{g(void 0),u(!0),s.readHistory(t,n).then(A=>h(A)).then(()=>u(!1)).catch(A=>{g(A),u(!1)})},[s,t,n]),c)return o.jsx(gi,{});if(!f)return o.jsxs(ot,{children:[o.jsx(Le,{children:"Resource not found"}),o.jsx(mt,{to:`/${t}`,children:"Return to search page"})]});const y=f.entry??[],b=y.findIndex(A=>{var k,M;return((M=(k=A.resource)==null?void 0:k.meta)==null?void 0:M.versionId)===r});if(b===-1)return o.jsxs(ot,{children:[o.jsx(Le,{children:"Version not found"}),o.jsx(mt,{to:`/${t}/${n}`,children:"Return to resource"})]});const S=y[b].resource,j=b<y.length-1?y[b+1].resource:void 0,C="diff";return o.jsxs(Et,{value:i||C,onChange:A=>{var k;return(k=e(`/${t}/${n}/_history/${r}/${A||C}`))==null?void 0:k.catch(console.error)},children:[o.jsxs(mr,{children:[o.jsx(Ic,{fluid:!0,p:"md",children:o.jsx(Ae,{children:`${t} ${n}`})}),o.jsxs(Et.List,{children:[o.jsx(Et.Tab,{value:"diff",children:"Diff"}),o.jsx(Et.Tab,{value:"raw",children:"Raw"})]})]}),o.jsxs(ot,{children:[m&&o.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)}),o.jsx(Et.Panel,{value:"diff",children:j?o.jsxs(o.Fragment,{children:[o.jsxs("ul",{children:[o.jsxs("li",{children:["Current: ",(T=S.meta)==null?void 0:T.versionId]}),o.jsxs("li",{children:["Previous:"," ",o.jsx(mt,{to:`/${t}/${n}/_history/${(D=j.meta)==null?void 0:D.versionId}`,children:(E=j.meta)==null?void 0:E.versionId})]})]}),o.jsx(RY,{original:j,revised:S})]}):o.jsxs(o.Fragment,{children:[o.jsxs("ul",{children:[o.jsxs("li",{children:["Current: ",(R=S.meta)==null?void 0:R.versionId]}),o.jsx("li",{children:"Previous: (none)"})]}),o.jsx("pre",{children:JSON.stringify(S,void 0,2)})]})}),o.jsx(Et.Panel,{value:"raw",children:o.jsx("pre",{children:JSON.stringify(S,void 0,2)})})]})]})}function Pee(){const{resourceType:e,id:t}=qt(),n=wn(),[r,i]=v.useState({resourceType:"Subscription",filters:[{code:"url",operator:ue.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return o.jsx(ot,{children:o.jsx(CQ,{search:r,onClick:s=>{var c;return(c=n(`/${s.resource.resourceType}/${s.resource.id}`))==null?void 0:c.catch(console.error)},onChange:s=>i(s.definition),hideFilters:!0})})}function Nee(e){const t=_e(),{resource:n,opened:r,onClose:i}=e,[s,c]=v.useState(!1),[u,f]=v.useState(),[h,m]=v.useState(!1),g=v.useCallback(async()=>{if(n!=null&&n.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:s&&u?zt(u):void 0,verbose:h}),Oe({color:"green",message:"Done"}),i()}catch(y){Oe({color:"red",message:Ye(y),autoClose:!1})}},[t,n,i,s,u,h]);return o.jsx($n,{opened:r,onClose:i,title:"Resend Subscriptions",children:o.jsx(pt,{onSubmit:g,children:o.jsxs(Ge,{children:[o.jsx(Fn,{label:"Choose subscription (all subscriptions by default)",onChange:y=>c(y.currentTarget.checked)}),s&&o.jsx(il,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:f}),o.jsx(Fn,{label:"Verbose mode",onChange:y=>m(y.currentTarget.checked)}),o.jsx(Ce,{justify:"flex-end",children:o.jsx(Ne,{type:"submit",children:"Resend"})})]})})})}function tR(){const e=_e(),t=em(),{resourceType:n,id:r}=qt(),i={reference:n+"/"+r},[s,c]=v.useState(),u=op(!1);function f(D,E){return e.updateResource({...D,priority:E})}function h(D,E){f(D,"stat").then(E).catch(console.error)}function m(D,E){f(D,"routine").then(E).catch(console.error)}function g(D){t(`/${D.resourceType}/${D.id}`)}function y(D){t(`/${D.resourceType}/${D.id}/edit`)}function b(D){t(`/${D.resourceType}/${D.id}/delete`)}function S(D){c(D),u[1].open()}function j(D){var E;t(`/${D.resourceType}/${D.id}/_history/${(E=D.meta)==null?void 0:E.versionId}`)}function C(D,E){const R="aws-textract";Oe({id:R,title:"AWS Textract in Progress",message:"Extracting text... This may take a moment...",loading:!0,autoClose:!1}),e.post(e.fhirUrl(D.resourceType,D.id,"$aws-textract"),{}).then(()=>{E(),As({id:R,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:o.jsx(eo,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(A=>As({id:R,title:"AWS Textract Error",color:"red",message:Ye(A),icon:o.jsx(Hs,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function T(D){var P;const{primaryResource:E,currentResource:R,reloadTimeline:A}=D,k=R.resourceType===E.resourceType&&R.id===E.id,M=R.resourceType==="Communication"&&R.priority!=="stat",I=R.resourceType==="Communication"&&R.priority==="stat",$=k,V=!k,Y=!k,Q=!k,J=(P=e.getProjectMembership())==null?void 0:P.admin,G=J,Z=sJ()&&(R.resourceType==="DocumentReference"||R.resourceType==="Media");return o.jsxs(je.Dropdown,{children:[o.jsx(je.Label,{children:"Resource"}),M&&o.jsx(je.Item,{leftSection:o.jsx(fF,{size:14}),onClick:()=>h(R,A),"aria-label":`Pin ${zt(R)}`,children:"Pin"}),I&&o.jsx(je.Item,{leftSection:o.jsx(hF,{size:14}),onClick:()=>m(R,A),"aria-label":`Unpin ${zt(R)}`,children:"Unpin"}),V&&o.jsx(je.Item,{leftSection:o.jsx(ME,{size:14}),onClick:()=>g(R),"aria-label":`Details ${zt(R)}`,children:"Details"}),$&&o.jsx(je.Item,{leftSection:o.jsx(ME,{size:14}),onClick:()=>j(R),"aria-label":`Details ${zt(R)}`,children:"Details"}),Y&&o.jsx(je.Item,{leftSection:o.jsx(e_,{size:14}),onClick:()=>y(R),"aria-label":`Edit ${zt(R)}`,children:"Edit"}),J&&o.jsxs(o.Fragment,{children:[o.jsx(je.Divider,{}),o.jsx(je.Label,{children:"Admin"}),G&&o.jsx(je.Item,{leftSection:o.jsx(gF,{size:14}),onClick:()=>S(R),"aria-label":`Resend Subscriptions ${zt(R)}`,children:"Resend Subscriptions"})]}),Z&&o.jsxs(o.Fragment,{children:[o.jsx(je.Divider,{}),o.jsx(je.Label,{children:"AWS AI"}),o.jsx(je.Item,{leftSection:o.jsx(CF,{size:14}),onClick:()=>C(R,A),"aria-label":`AWS Textract ${zt(R)}`,children:"AWS Textract"})]}),Q&&o.jsxs(o.Fragment,{children:[o.jsx(je.Divider,{}),o.jsx(je.Label,{children:"Danger zone"}),o.jsx(je.Item,{color:"red",leftSection:o.jsx(xb,{size:14}),onClick:()=>b(R),"aria-label":`Delete ${zt(R)}`,children:"Delete"})]})]})}return o.jsxs(o.Fragment,{children:[n==="Encounter"&&o.jsx(PG,{encounter:i,getMenu:T}),n==="Patient"&&o.jsx(qQ,{patient:i,getMenu:T}),n==="ServiceRequest"&&o.jsx(OY,{serviceRequest:i,getMenu:T}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&o.jsx(kG,{resource:i,getMenu:T}),o.jsx(Nee,{resource:s,opened:u[0],onClose:u[1].close},`resend-subscriptions-${s==null?void 0:s.id}`)]})}function Oee(e){const{opened:t,close:n,version:r,loadingStatus:i,handleStatus:s,handleUpgrade:c}=e,[u,f]=v.useState();return v.useEffect(()=>{t&&(u||EV("app-tools-page").then(f).catch(console.error),s())},[t,u,s]),u&&r&&!i?r==="unknown"?o.jsx("p",{children:"Unable to determine the current version of the agent. Check the network connectivity of the agent."}):r.startsWith(u)?o.jsxs("p",{children:["This agent is already on the latest version (",u,")."]}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["Are you sure you want to upgrade this agent from version ",r," to version ",u,"?"]}),o.jsx(Ne,{onClick:()=>{c(),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"})]}):o.jsx(gi,{})}function Mee(){const e=_e(),{id:t}=qt(),n=v.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,i]=v.useState(!1),[s,c]=v.useState(!1),[u,f]=v.useState(!1),[h,m]=v.useState(),[g,y]=v.useState(),[b,S]=v.useState(),[j,C]=v.useState(),[T,D]=v.useState(!1),[E,R]=v.useState(!1),[A,{open:k,close:M}]=op(!1);v.useEffect(()=>{if(r||s||u||T){R(!0);return}R(!1)},[r,s,u,T]);const I=v.useCallback(()=>{i(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(G=>{var Z,P,L,z,H,O;m((P=(Z=G.parameter)==null?void 0:Z.find(U=>U.name==="status"))==null?void 0:P.valueCode),y((z=(L=G.parameter)==null?void 0:L.find(U=>U.name==="version"))==null?void 0:z.valueString),S((O=(H=G.parameter)==null?void 0:H.find(U=>U.name==="lastUpdated"))==null?void 0:O.valueInstant)}).catch(G=>J(Ye(G))).finally(()=>i(!1))},[e,t]),$=v.useCallback(G=>{const Z=G.host,P=G.pingCount||1;Z&&(D(!0),e.pushToAgent(n,Z,`PING ${P}`,hn.PING,!0).then(L=>C(L)).catch(L=>J(Ye(L))).finally(()=>D(!1)))},[e,n]),V=v.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(G=>{Q("Agent config reloaded successfully.")}).catch(G=>J(Ye(G))).finally(()=>c(!1))},[e,t]),Y=v.useCallback(()=>{f(!0),e.get(e.fhirUrl("Agent",t,"$upgrade"),{cache:"reload"}).then(G=>{Q("Agent upgraded successfully.")}).catch(G=>J(Ye(G))).finally(()=>f(!1))},[e,t]);function Q(G){Oe({color:"green",title:"Success",icon:o.jsx(eo,{size:"1rem"}),message:G})}function J(G){Oe({color:"red",title:"Error",message:G,autoClose:!1})}return o.jsxs(ot,{children:[o.jsx($n,{opened:A,onClose:M,title:"Upgrade Agent",centered:!0,children:o.jsx(Oee,{opened:A,close:M,version:g,loadingStatus:r,handleStatus:I,handleUpgrade:Y})}),o.jsx(Le,{order:1,children:"Agent Tools"}),o.jsxs("div",{style:{marginBottom:10},children:["Agent: ",o.jsx(Lc,{value:n,link:!0})]}),o.jsx(Cn,{my:"lg"}),o.jsx(Le,{order:2,children:"Agent Status"}),o.jsx("p",{children:"Retrieve the status of the agent. This tests whether the agent is connected to the Medplum server, and the last time it was able to communicate."}),o.jsx(Ne,{onClick:I,loading:r,disabled:E&&!r,children:"Get Status"}),!r&&h&&o.jsx(ye,{children:o.jsxs(ye.Tbody,{children:[o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:"Status"}),o.jsx(ye.Td,{children:o.jsx(om,{status:h})})]}),o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:"Version"}),o.jsx(ye.Td,{children:g})]}),o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:"Last Updated"}),o.jsx(ye.Td,{children:gr(b,void 0,{timeZoneName:"longOffset"})})]})]})}),o.jsx(Cn,{my:"lg"}),o.jsx(Le,{order:2,children:"Reload Config"}),o.jsx("p",{children:"Reload the configuration of this agent, syncing it with the current version of the Agent resource on the Medplum server."}),o.jsx(Ne,{onClick:V,loading:s,disabled:E&&!s,"aria-label":"Reload config",children:"Reload Config"}),o.jsx(Cn,{my:"lg"}),o.jsx(Le,{order:2,children:"Upgrade Agent"}),o.jsx("p",{children:"Upgrade the version of this agent, to either the latest (default) or a specified version."}),o.jsx(Ne,{onClick:k,loading:u,disabled:E&&!u,"aria-label":"Upgrade agent",children:"Upgrade"}),o.jsx(Cn,{my:"lg"}),o.jsx(Le,{order:2,children:"Ping from Agent"}),o.jsx("p",{children:"Send a ping command from the agent to a valid IP address or hostname. Use this tool to troubleshoot local network connectivity."}),o.jsx(pt,{onSubmit:$,children:o.jsxs(Ce,{children:[o.jsx(ze,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:o.jsx(_n,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:T,disabled:E&&!T,children:o.jsx(yF,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),o.jsx(Ip,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!T&&j&&o.jsxs(o.Fragment,{children:[o.jsx(Le,{order:5,mt:"sm",mb:0,children:"Last Ping"}),o.jsx("pre",{children:j})]})]})}function Iee(){return o.jsx(fX,{children:o.jsxs(Fe,{errorElement:o.jsx(WZ,{}),children:[o.jsx(Fe,{path:"/signin",element:o.jsx(hJ,{})}),o.jsx(Fe,{path:"/oauth",element:o.jsx(lJ,{})}),o.jsx(Fe,{path:"/resetpassword",element:o.jsx(uJ,{})}),o.jsx(Fe,{path:"/setpassword/:id/:secret",element:o.jsx(fJ,{})}),o.jsx(Fe,{path:"/register",element:o.jsx(cJ,{})}),o.jsx(Fe,{path:"/changepassword",element:o.jsx(qZ,{})}),o.jsx(Fe,{path:"/security",element:o.jsx(dJ,{})}),o.jsx(Fe,{path:"/mfa",element:o.jsx(oJ,{})}),o.jsx(Fe,{path:"/batch",element:o.jsx(FZ,{})}),o.jsx(Fe,{path:"/bulk/:resourceType",element:o.jsx(HZ,{})}),o.jsx(Fe,{path:"/smart",element:o.jsx(pJ,{})}),o.jsx(Fe,{path:"/forms/:id",element:o.jsx(KZ,{})}),o.jsx(Fe,{path:"/admin/super",element:o.jsx(NJ,{})}),o.jsx(Fe,{path:"/admin/super/asyncjob",element:o.jsx(RJ,{})}),o.jsx(Fe,{path:"/admin/config",element:o.jsx(jJ,{})}),o.jsxs(Fe,{path:"/admin",element:o.jsx(CJ,{}),children:[o.jsx(Fe,{path:"patients",element:o.jsx(wJ,{})}),o.jsx(Fe,{path:"bots/new",element:o.jsx(vJ,{})}),o.jsx(Fe,{path:"bots",element:o.jsx(mJ,{})}),o.jsx(Fe,{path:"clients/new",element:o.jsx(yJ,{})}),o.jsx(Fe,{path:"clients",element:o.jsx(gJ,{})}),o.jsx(Fe,{path:"details",element:o.jsx(WT,{})}),o.jsx(Fe,{path:"invite",element:o.jsx(SJ,{})}),o.jsx(Fe,{path:"users",element:o.jsx(MJ,{})}),o.jsx(Fe,{path:"project",element:o.jsx(WT,{})}),o.jsx(Fe,{path:"secrets",element:o.jsx(EJ,{})}),o.jsx(Fe,{path:"sites",element:o.jsx(TJ,{})}),o.jsx(Fe,{path:"members/:membershipId",element:o.jsx(bJ,{})})]}),o.jsx(Fe,{path:"/lab/assays",element:o.jsx(IJ,{})}),o.jsx(Fe,{path:"/lab/panels",element:o.jsx(LJ,{})}),o.jsx(Fe,{path:"/:resourceType/:id/_history/:versionId/:tab",element:o.jsx(eR,{})}),o.jsx(Fe,{path:"/:resourceType/:id/_history/:versionId",element:o.jsx(eR,{})}),o.jsxs(Fe,{path:"/:resourceType/new",element:o.jsx(QZ,{}),children:[o.jsx(Fe,{index:!0,element:o.jsx(py,{})}),o.jsx(Fe,{path:"form",element:o.jsx(py,{})}),o.jsx(Fe,{path:"json",element:o.jsx(see,{})}),o.jsx(Fe,{path:"profiles",element:o.jsx(py,{})})]}),o.jsxs(Fe,{path:"/:resourceType/:id",element:o.jsx(kee,{}),children:[o.jsx(Fe,{index:!0,element:o.jsx(tR,{})}),o.jsx(Fe,{path:"apply",element:o.jsx($J,{})}),o.jsx(Fe,{path:"apps",element:o.jsx(UJ,{})}),o.jsx(Fe,{path:"event",element:o.jsx(VJ,{})}),o.jsx(Fe,{path:"blame",element:o.jsx(FJ,{})}),o.jsx(Fe,{path:"bots",element:o.jsx(hee,{})}),o.jsx(Fe,{path:"builder",element:o.jsx(ZJ,{})}),o.jsx(Fe,{path:"checklist",element:o.jsx(JJ,{})}),o.jsx(Fe,{path:"delete",element:o.jsx(eee,{})}),o.jsx(Fe,{path:"details",element:o.jsx(ree,{})}),o.jsx(Fe,{path:"edit",element:o.jsx(iee,{})}),o.jsx(Fe,{path:"editor",element:o.jsx(KJ,{})}),o.jsx(Fe,{path:"history",element:o.jsx(oee,{})}),o.jsx(Fe,{path:"json",element:o.jsx(lee,{})}),o.jsx(Fe,{path:"preview",element:o.jsx(cee,{})}),o.jsx(Fe,{path:"responses",element:o.jsx(mee,{})}),o.jsx(Fe,{path:"report",element:o.jsx(vee,{})}),o.jsx(Fe,{path:"ranges",element:o.jsx(gee,{})}),o.jsx(Fe,{path:"subscriptions",element:o.jsx(Pee,{})}),o.jsx(Fe,{path:"timeline",element:o.jsx(tR,{})}),o.jsx(Fe,{path:"tools",element:o.jsx(Mee,{})}),o.jsx(Fe,{path:"profiles",element:o.jsx(uee,{})}),o.jsx(Fe,{path:"export",element:o.jsx(aee,{})})]}),o.jsx(Fe,{path:"/:resourceType",element:o.jsx(QT,{})}),o.jsx(Fe,{path:"/",element:o.jsx(QT,{})})]})})}function Lee(){const e=_e(),t=e.getUserConfiguration(),n=Mr(),[r]=Jb();return e.isLoading()?o.jsx(gi,{}):o.jsx(yH,{logo:o.jsx(Ui,{size:24}),pathname:n.pathname,searchParams:r,version:FA,menus:zee(t),displayAddBookmark:!!(t!=null&&t.id),children:o.jsx(v.Suspense,{fallback:o.jsx(gi,{}),children:o.jsx(Iee,{})})})}function zee(e){var n;const t=((n=e==null?void 0:e.menu)==null?void 0:n.map(r=>{var i;return{title:r.title,links:((i=r.link)==null?void 0:i.map(s=>({label:s.name,href:s.target,icon:$ee(s.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:o.jsx(oF,{})}]}),t}const nR={Patient:SF,Practitioner:iF,Organization:WV,ServiceRequest:mF,DiagnosticReport:vF,Questionnaire:rF,admin:qV,AccessPolicy:aF,Subscription:EF,batch:dF,Observation:cF};function $ee(e){try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in nR){const n=nR[t];return o.jsx(n,{})}}catch{}return o.jsx(Hp,{w:30})}"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.getRegistrations().then(e=>Promise.all(e.map(t=>t.unregister()))).catch(e=>console.error("SW registration failed: ",e))});async function Uee(){const e=Vd(),t=new HA({baseUrl:e.baseUrl,clientId:e.clientId,cacheTime:6e4,autoBatchTime:100,onUnauthenticated:()=>{window.location.pathname!=="/signin"&&window.location.pathname!=="/oauth"&&(window.location.href="/signin?next="+encodeURIComponent(window.location.pathname+window.location.search))}}),n={headings:{sizes:{h1:{fontSize:"1.125rem",fontWeight:"500",lineHeight:"2.0"}}},fontSizes:{xs:"0.6875rem",sm:"0.875rem",md:"0.875rem",lg:"1.0rem",xl:"1.125rem"}},r=LX([{path:"*",element:o.jsx(Lee,{})}]),i=c=>r.navigate(c);UY.createRoot(document.getElementById("root")).render(o.jsx(v.StrictMode,{children:o.jsx(TV,{medplum:t,navigate:i,children:o.jsxs(RR,{theme:n,children:[o.jsx(Za,{position:"bottom-right"}),o.jsx(lX,{router:r})]})})}))}Uee().catch(console.error);
|
|
586
|
-
//# sourceMappingURL=index-
|
|
586
|
+
//# sourceMappingURL=index-CY_bDLT5.js.map
|