@medplum/cli 4.0.2 → 4.0.4

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.
@@ -1,25 +1,25 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var xi=Object.create;var ve=Object.defineProperty;var $i=Object.getOwnPropertyDescriptor;var Ni=Object.getOwnPropertyNames;var Li=Object.getPrototypeOf,Di=Object.prototype.hasOwnProperty;var ki=(t,e,r)=>e in t?ve(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var w=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Mi=(t,e)=>{for(var r in e)ve(t,r,{get:e[r],enumerable:!0})},Mr=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ni(e))!Di.call(t,n)&&n!==r&&ve(t,n,{get:()=>e[n],enumerable:!(o=$i(e,n))||o.enumerable});return t};var N=(t,e,r)=>(r=t!=null?xi(Li(t)):{},Mr(e||!t||!t.__esModule?ve(r,"default",{value:t,enumerable:!0}):r,t)),_i=t=>Mr(ve({},"__esModule",{value:!0}),t);var b=(t,e,r)=>ki(t,typeof e!="symbol"?e+"":e,r);var Le=w((Bd,$o)=>{"use strict";var Sa="2.0.0",Ra=Number.MAX_SAFE_INTEGER||9007199254740991,Aa=16,Ia=250,ba=["major","premajor","minor","preminor","patch","prepatch","prerelease"];$o.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Aa,MAX_SAFE_BUILD_LENGTH:Ia,MAX_SAFE_INTEGER:Ra,RELEASE_TYPES:ba,SEMVER_SPEC_VERSION:Sa,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var De=w((Kd,No)=>{"use strict";var va=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};No.exports=va});var he=w((K,Lo)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:or,MAX_SAFE_BUILD_LENGTH:Pa,MAX_LENGTH:Ca}=Le(),Ta=De();K=Lo.exports={};var Oa=K.re=[],xa=K.safeRe=[],d=K.src=[],$a=K.safeSrc=[],m=K.t={},Na=0,nr="[a-zA-Z0-9-]",La=[["\\s",1],["\\d",Ca],[nr,Pa]],Da=t=>{for(let[e,r]of La)t=t.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return t},E=(t,e,r)=>{let o=Da(e),n=Na++;Ta(t,n,e),m[t]=n,d[n]=e,$a[n]=o,Oa[n]=new RegExp(e,r?"g":void 0),xa[n]=new RegExp(o,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${nr}*`);E("MAINVERSION",`(${d[m.NUMERICIDENTIFIER]})\\.(${d[m.NUMERICIDENTIFIER]})\\.(${d[m.NUMERICIDENTIFIER]})`);E("MAINVERSIONLOOSE",`(${d[m.NUMERICIDENTIFIERLOOSE]})\\.(${d[m.NUMERICIDENTIFIERLOOSE]})\\.(${d[m.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASEIDENTIFIER",`(?:${d[m.NUMERICIDENTIFIER]}|${d[m.NONNUMERICIDENTIFIER]})`);E("PRERELEASEIDENTIFIERLOOSE",`(?:${d[m.NUMERICIDENTIFIERLOOSE]}|${d[m.NONNUMERICIDENTIFIER]})`);E("PRERELEASE",`(?:-(${d[m.PRERELEASEIDENTIFIER]}(?:\\.${d[m.PRERELEASEIDENTIFIER]})*))`);E("PRERELEASELOOSE",`(?:-?(${d[m.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${d[m.PRERELEASEIDENTIFIERLOOSE]})*))`);E("BUILDIDENTIFIER",`${nr}+`);E("BUILD",`(?:\\+(${d[m.BUILDIDENTIFIER]}(?:\\.${d[m.BUILDIDENTIFIER]})*))`);E("FULLPLAIN",`v?${d[m.MAINVERSION]}${d[m.PRERELEASE]}?${d[m.BUILD]}?`);E("FULL",`^${d[m.FULLPLAIN]}$`);E("LOOSEPLAIN",`[v=\\s]*${d[m.MAINVERSIONLOOSE]}${d[m.PRERELEASELOOSE]}?${d[m.BUILD]}?`);E("LOOSE",`^${d[m.LOOSEPLAIN]}$`);E("GTLT","((?:<|>)?=?)");E("XRANGEIDENTIFIERLOOSE",`${d[m.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);E("XRANGEIDENTIFIER",`${d[m.NUMERICIDENTIFIER]}|x|X|\\*`);E("XRANGEPLAIN",`[v=\\s]*(${d[m.XRANGEIDENTIFIER]})(?:\\.(${d[m.XRANGEIDENTIFIER]})(?:\\.(${d[m.XRANGEIDENTIFIER]})(?:${d[m.PRERELEASE]})?${d[m.BUILD]}?)?)?`);E("XRANGEPLAINLOOSE",`[v=\\s]*(${d[m.XRANGEIDENTIFIERLOOSE]})(?:\\.(${d[m.XRANGEIDENTIFIERLOOSE]})(?:\\.(${d[m.XRANGEIDENTIFIERLOOSE]})(?:${d[m.PRERELEASELOOSE]})?${d[m.BUILD]}?)?)?`);E("XRANGE",`^${d[m.GTLT]}\\s*${d[m.XRANGEPLAIN]}$`);E("XRANGELOOSE",`^${d[m.GTLT]}\\s*${d[m.XRANGEPLAINLOOSE]}$`);E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${or}})(?:\\.(\\d{1,${or}}))?(?:\\.(\\d{1,${or}}))?`);E("COERCE",`${d[m.COERCEPLAIN]}(?:$|[^\\d])`);E("COERCEFULL",d[m.COERCEPLAIN]+`(?:${d[m.PRERELEASE]})?(?:${d[m.BUILD]})?(?:$|[^\\d])`);E("COERCERTL",d[m.COERCE],!0);E("COERCERTLFULL",d[m.COERCEFULL],!0);E("LONETILDE","(?:~>?)");E("TILDETRIM",`(\\s*)${d[m.LONETILDE]}\\s+`,!0);K.tildeTrimReplace="$1~";E("TILDE",`^${d[m.LONETILDE]}${d[m.XRANGEPLAIN]}$`);E("TILDELOOSE",`^${d[m.LONETILDE]}${d[m.XRANGEPLAINLOOSE]}$`);E("LONECARET","(?:\\^)");E("CARETTRIM",`(\\s*)${d[m.LONECARET]}\\s+`,!0);K.caretTrimReplace="$1^";E("CARET",`^${d[m.LONECARET]}${d[m.XRANGEPLAIN]}$`);E("CARETLOOSE",`^${d[m.LONECARET]}${d[m.XRANGEPLAINLOOSE]}$`);E("COMPARATORLOOSE",`^${d[m.GTLT]}\\s*(${d[m.LOOSEPLAIN]})$|^$`);E("COMPARATOR",`^${d[m.GTLT]}\\s*(${d[m.FULLPLAIN]})$|^$`);E("COMPARATORTRIM",`(\\s*)${d[m.GTLT]}\\s*(${d[m.LOOSEPLAIN]}|${d[m.XRANGEPLAIN]})`,!0);K.comparatorTrimReplace="$1$2$3";E("HYPHENRANGE",`^\\s*(${d[m.XRANGEPLAIN]})\\s+-\\s+(${d[m.XRANGEPLAIN]})\\s*$`);E("HYPHENRANGELOOSE",`^\\s*(${d[m.XRANGEPLAINLOOSE]})\\s+-\\s+(${d[m.XRANGEPLAINLOOSE]})\\s*$`);E("STAR","(<|>)?=?\\s*\\*");E("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");E("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var rt=w((Wd,Do)=>{"use strict";var ka=Object.freeze({loose:!0}),Ma=Object.freeze({}),_a=t=>t?typeof t!="object"?ka:t:Ma;Do.exports=_a});var sr=w((qd,_o)=>{"use strict";var ko=/^[0-9]+$/,Mo=(t,e)=>{let r=ko.test(t),o=ko.test(e);return r&&o&&(t=+t,e=+e),t===e?0:r&&!o?-1:o&&!r?1:t<e?-1:1},Ua=(t,e)=>Mo(e,t);_o.exports={compareIdentifiers:Mo,rcompareIdentifiers:Ua}});var P=w((Hd,Bo)=>{"use strict";var ot=De(),{MAX_LENGTH:Uo,MAX_SAFE_INTEGER:nt}=Le(),{safeRe:jo,safeSrc:Fo,t:st}=he(),ja=rt(),{compareIdentifiers:ge}=sr(),ir=class t{constructor(e,r){if(r=ja(r),e instanceof t){if(e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Uo)throw new TypeError(`version is longer than ${Uo} characters`);ot("SemVer",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let o=e.trim().match(r.loose?jo[st.LOOSE]:jo[st.FULL]);if(!o)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+o[1],this.minor=+o[2],this.patch=+o[3],this.major>nt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>nt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>nt||this.patch<0)throw new TypeError("Invalid patch version");o[4]?this.prerelease=o[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let s=+n;if(s>=0&&s<nt)return s}return n}):this.prerelease=[],this.build=o[5]?o[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(ot("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),ge(this.major,e.major)||ge(this.minor,e.minor)||ge(this.patch,e.patch)}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let r=0;do{let o=this.prerelease[r],n=e.prerelease[r];if(ot("prerelease compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return ge(o,n)}while(++r)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let r=0;do{let o=this.build[r],n=e.build[r];if(ot("build compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return ge(o,n)}while(++r)}inc(e,r,o){if(e.startsWith("pre")){if(!r&&o===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let n=new RegExp(`^${this.options.loose?Fo[st.PRERELEASELOOSE]:Fo[st.PRERELEASE]}$`),s=`-${r}`.match(n);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,o);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,o);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,o),this.inc("pre",r,o);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,o),this.inc("pre",r,o);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let n=Number(o)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(r===this.prerelease.join(".")&&o===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(r){let s=[r,n];o===!1&&(s=[r]),ge(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Bo.exports=ir});var ce=w((Gd,Wo)=>{"use strict";var Ko=P(),Fa=(t,e,r=!1)=>{if(t instanceof Ko)return t;try{return new Ko(t,e)}catch(o){if(!r)return null;throw o}};Wo.exports=Fa});var Ho=w((Vd,qo)=>{"use strict";var Ba=ce(),Ka=(t,e)=>{let r=Ba(t,e);return r?r.version:null};qo.exports=Ka});var Vo=w((Jd,Go)=>{"use strict";var Wa=ce(),qa=(t,e)=>{let r=Wa(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};Go.exports=qa});var zo=w((Xd,Xo)=>{"use strict";var Jo=P(),Ha=(t,e,r,o,n)=>{typeof r=="string"&&(n=o,o=r,r=void 0);try{return new Jo(t instanceof Jo?t.version:t,r).inc(e,o,n).version}catch{return null}};Xo.exports=Ha});var Qo=w((zd,Zo)=>{"use strict";var Yo=ce(),Ga=(t,e)=>{let r=Yo(t,null,!0),o=Yo(e,null,!0),n=r.compare(o);if(n===0)return null;let s=n>0,i=s?r:o,c=s?o:r,l=!!i.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(c.compareMain(i)===0)return c.minor&&!c.patch?"minor":"patch"}let h=l?"pre":"";return r.major!==o.major?h+"major":r.minor!==o.minor?h+"minor":r.patch!==o.patch?h+"patch":"prerelease"};Zo.exports=Ga});var tn=w((Yd,en)=>{"use strict";var Va=P(),Ja=(t,e)=>new Va(t,e).major;en.exports=Ja});var on=w((Zd,rn)=>{"use strict";var Xa=P(),za=(t,e)=>new Xa(t,e).minor;rn.exports=za});var sn=w((Qd,nn)=>{"use strict";var Ya=P(),Za=(t,e)=>new Ya(t,e).patch;nn.exports=Za});var cn=w((em,an)=>{"use strict";var Qa=ce(),ec=(t,e)=>{let r=Qa(t,e);return r&&r.prerelease.length?r.prerelease:null};an.exports=ec});var L=w((tm,un)=>{"use strict";var ln=P(),tc=(t,e,r)=>new ln(t,r).compare(new ln(e,r));un.exports=tc});var dn=w((rm,pn)=>{"use strict";var rc=L(),oc=(t,e,r)=>rc(e,t,r);pn.exports=oc});var fn=w((om,mn)=>{"use strict";var nc=L(),sc=(t,e)=>nc(t,e,!0);mn.exports=sc});var it=w((nm,gn)=>{"use strict";var hn=P(),ic=(t,e,r)=>{let o=new hn(t,r),n=new hn(e,r);return o.compare(n)||o.compareBuild(n)};gn.exports=ic});var wn=w((sm,yn)=>{"use strict";var ac=it(),cc=(t,e)=>t.sort((r,o)=>ac(r,o,e));yn.exports=cc});var Sn=w((im,En)=>{"use strict";var lc=it(),uc=(t,e)=>t.sort((r,o)=>lc(o,r,e));En.exports=uc});var ke=w((am,Rn)=>{"use strict";var pc=L(),dc=(t,e,r)=>pc(t,e,r)>0;Rn.exports=dc});var at=w((cm,An)=>{"use strict";var mc=L(),fc=(t,e,r)=>mc(t,e,r)<0;An.exports=fc});var ar=w((lm,In)=>{"use strict";var hc=L(),gc=(t,e,r)=>hc(t,e,r)===0;In.exports=gc});var cr=w((um,bn)=>{"use strict";var yc=L(),wc=(t,e,r)=>yc(t,e,r)!==0;bn.exports=wc});var ct=w((pm,vn)=>{"use strict";var Ec=L(),Sc=(t,e,r)=>Ec(t,e,r)>=0;vn.exports=Sc});var lt=w((dm,Pn)=>{"use strict";var Rc=L(),Ac=(t,e,r)=>Rc(t,e,r)<=0;Pn.exports=Ac});var lr=w((mm,Cn)=>{"use strict";var Ic=ar(),bc=cr(),vc=ke(),Pc=ct(),Cc=at(),Tc=lt(),Oc=(t,e,r,o)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t===r;case"!==":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t!==r;case"":case"=":case"==":return Ic(t,r,o);case"!=":return bc(t,r,o);case">":return vc(t,r,o);case">=":return Pc(t,r,o);case"<":return Cc(t,r,o);case"<=":return Tc(t,r,o);default:throw new TypeError(`Invalid operator: ${e}`)}};Cn.exports=Oc});var On=w((fm,Tn)=>{"use strict";var xc=P(),$c=ce(),{safeRe:ut,t:pt}=he(),Nc=(t,e)=>{if(t instanceof xc)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let r=null;if(!e.rtl)r=t.match(e.includePrerelease?ut[pt.COERCEFULL]:ut[pt.COERCE]);else{let l=e.includePrerelease?ut[pt.COERCERTLFULL]:ut[pt.COERCERTL],u;for(;(u=l.exec(t))&&(!r||r.index+r[0].length!==t.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let o=r[2],n=r[3]||"0",s=r[4]||"0",i=e.includePrerelease&&r[5]?`-${r[5]}`:"",c=e.includePrerelease&&r[6]?`+${r[6]}`:"";return $c(`${o}.${n}.${s}${i}${c}`,e)};Tn.exports=Nc});var $n=w((hm,xn)=>{"use strict";var ur=class{constructor(){this.max=1e3,this.map=new Map}get(e){let r=this.map.get(e);if(r!==void 0)return this.map.delete(e),this.map.set(e,r),r}delete(e){return this.map.delete(e)}set(e,r){if(!this.delete(e)&&r!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(e,r)}return this}};xn.exports=ur});var D=w((gm,kn)=>{"use strict";var Lc=/\s+/g,pr=class t{constructor(e,r){if(r=kc(r),e instanceof t)return e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease?e:new t(e.raw,r);if(e instanceof dr)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=e.trim().replace(Lc," "),this.set=this.raw.split("||").map(o=>this.parseRange(o.trim())).filter(o=>o.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let o=this.set[0];if(this.set=this.set.filter(n=>!Ln(n[0])),this.set.length===0)this.set=[o];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&Kc(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let r=this.set[e];for(let o=0;o<r.length;o++)o>0&&(this.formatted+=" "),this.formatted+=r[o].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let o=((this.options.includePrerelease&&Fc)|(this.options.loose&&Bc))+":"+e,n=Nn.get(o);if(n)return n;let s=this.options.loose,i=s?O[C.HYPHENRANGELOOSE]:O[C.HYPHENRANGE];e=e.replace(i,Zc(this.options.includePrerelease)),A("hyphen replace",e),e=e.replace(O[C.COMPARATORTRIM],_c),A("comparator trim",e),e=e.replace(O[C.TILDETRIM],Uc),A("tilde trim",e),e=e.replace(O[C.CARETTRIM],jc),A("caret trim",e);let c=e.split(" ").map(f=>Wc(f,this.options)).join(" ").split(/\s+/).map(f=>Yc(f,this.options));s&&(c=c.filter(f=>(A("loose invalid filter",f,this.options),!!f.match(O[C.COMPARATORLOOSE])))),A("range list",c);let l=new Map,u=c.map(f=>new dr(f,this.options));for(let f of u){if(Ln(f))return[f];l.set(f.value,f)}l.size>1&&l.has("")&&l.delete("");let h=[...l.values()];return Nn.set(o,h),h}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(o=>Dn(o,r)&&e.set.some(n=>Dn(n,r)&&o.every(s=>n.every(i=>s.intersects(i,r)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new Mc(e,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(Qc(this.set[r],e,this.options))return!0;return!1}};kn.exports=pr;var Dc=$n(),Nn=new Dc,kc=rt(),dr=Me(),A=De(),Mc=P(),{safeRe:O,t:C,comparatorTrimReplace:_c,tildeTrimReplace:Uc,caretTrimReplace:jc}=he(),{FLAG_INCLUDE_PRERELEASE:Fc,FLAG_LOOSE:Bc}=Le(),Ln=t=>t.value==="<0.0.0-0",Kc=t=>t.value==="",Dn=(t,e)=>{let r=!0,o=t.slice(),n=o.pop();for(;r&&o.length;)r=o.every(s=>n.intersects(s,e)),n=o.pop();return r},Wc=(t,e)=>(A("comp",t,e),t=Gc(t,e),A("caret",t),t=qc(t,e),A("tildes",t),t=Jc(t,e),A("xrange",t),t=zc(t,e),A("stars",t),t),T=t=>!t||t.toLowerCase()==="x"||t==="*",qc=(t,e)=>t.trim().split(/\s+/).map(r=>Hc(r,e)).join(" "),Hc=(t,e)=>{let r=e.loose?O[C.TILDELOOSE]:O[C.TILDE];return t.replace(r,(o,n,s,i,c)=>{A("tilde",t,o,n,s,i,c);let l;return T(n)?l="":T(s)?l=`>=${n}.0.0 <${+n+1}.0.0-0`:T(i)?l=`>=${n}.${s}.0 <${n}.${+s+1}.0-0`:c?(A("replaceTilde pr",c),l=`>=${n}.${s}.${i}-${c} <${n}.${+s+1}.0-0`):l=`>=${n}.${s}.${i} <${n}.${+s+1}.0-0`,A("tilde return",l),l})},Gc=(t,e)=>t.trim().split(/\s+/).map(r=>Vc(r,e)).join(" "),Vc=(t,e)=>{A("caret",t,e);let r=e.loose?O[C.CARETLOOSE]:O[C.CARET],o=e.includePrerelease?"-0":"";return t.replace(r,(n,s,i,c,l)=>{A("caret",t,n,s,i,c,l);let u;return T(s)?u="":T(i)?u=`>=${s}.0.0${o} <${+s+1}.0.0-0`:T(c)?s==="0"?u=`>=${s}.${i}.0${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${o} <${+s+1}.0.0-0`:l?(A("replaceCaret pr",l),s==="0"?i==="0"?u=`>=${s}.${i}.${c}-${l} <${s}.${i}.${+c+1}-0`:u=`>=${s}.${i}.${c}-${l} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${c}-${l} <${+s+1}.0.0-0`):(A("no pr"),s==="0"?i==="0"?u=`>=${s}.${i}.${c}${o} <${s}.${i}.${+c+1}-0`:u=`>=${s}.${i}.${c}${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${c} <${+s+1}.0.0-0`),A("caret return",u),u})},Jc=(t,e)=>(A("replaceXRanges",t,e),t.split(/\s+/).map(r=>Xc(r,e)).join(" ")),Xc=(t,e)=>{t=t.trim();let r=e.loose?O[C.XRANGELOOSE]:O[C.XRANGE];return t.replace(r,(o,n,s,i,c,l)=>{A("xRange",t,o,n,s,i,c,l);let u=T(s),h=u||T(i),f=h||T(c),S=f;return n==="="&&S&&(n=""),l=e.includePrerelease?"-0":"",u?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&S?(h&&(i=0),c=0,n===">"?(n=">=",h?(s=+s+1,i=0,c=0):(i=+i+1,c=0)):n==="<="&&(n="<",h?s=+s+1:i=+i+1),n==="<"&&(l="-0"),o=`${n+s}.${i}.${c}${l}`):h?o=`>=${s}.0.0${l} <${+s+1}.0.0-0`:f&&(o=`>=${s}.${i}.0${l} <${s}.${+i+1}.0-0`),A("xRange return",o),o})},zc=(t,e)=>(A("replaceStars",t,e),t.trim().replace(O[C.STAR],"")),Yc=(t,e)=>(A("replaceGTE0",t,e),t.trim().replace(O[e.includePrerelease?C.GTE0PRE:C.GTE0],"")),Zc=t=>(e,r,o,n,s,i,c,l,u,h,f,S)=>(T(o)?r="":T(n)?r=`>=${o}.0.0${t?"-0":""}`:T(s)?r=`>=${o}.${n}.0${t?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${t?"-0":""}`,T(u)?l="":T(h)?l=`<${+u+1}.0.0-0`:T(f)?l=`<${u}.${+h+1}.0-0`:S?l=`<=${u}.${h}.${f}-${S}`:t?l=`<${u}.${h}.${+f+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),Qc=(t,e,r)=>{for(let o=0;o<t.length;o++)if(!t[o].test(e))return!1;if(e.prerelease.length&&!r.includePrerelease){for(let o=0;o<t.length;o++)if(A(t[o].semver),t[o].semver!==dr.ANY&&t[o].semver.prerelease.length>0){let n=t[o].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0}});var Me=w((ym,Bn)=>{"use strict";var _e=Symbol("SemVer ANY"),hr=class t{static get ANY(){return _e}constructor(e,r){if(r=Mn(r),e instanceof t){if(e.loose===!!r.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),fr("comparator",e,r),this.options=r,this.loose=!!r.loose,this.parse(e),this.semver===_e?this.value="":this.value=this.operator+this.semver.version,fr("comp",this)}parse(e){let r=this.options.loose?_n[Un.COMPARATORLOOSE]:_n[Un.COMPARATOR],o=e.match(r);if(!o)throw new TypeError(`Invalid comparator: ${e}`);this.operator=o[1]!==void 0?o[1]:"",this.operator==="="&&(this.operator=""),o[2]?this.semver=new jn(o[2],this.options.loose):this.semver=_e}toString(){return this.value}test(e){if(fr("Comparator.test",e,this.options.loose),this.semver===_e||e===_e)return!0;if(typeof e=="string")try{e=new jn(e,this.options)}catch{return!1}return mr(e,this.operator,this.semver,this.options)}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Fn(e.value,r).test(this.value):e.operator===""?e.value===""?!0:new Fn(this.value,r).test(e.semver):(r=Mn(r),r.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||mr(this.semver,"<",e.semver,r)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||mr(this.semver,">",e.semver,r)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Bn.exports=hr;var Mn=rt(),{safeRe:_n,t:Un}=he(),mr=lr(),fr=De(),jn=P(),Fn=D()});var Ue=w((wm,Kn)=>{"use strict";var el=D(),tl=(t,e,r)=>{try{e=new el(e,r)}catch{return!1}return e.test(t)};Kn.exports=tl});var qn=w((Em,Wn)=>{"use strict";var rl=D(),ol=(t,e)=>new rl(t,e).set.map(r=>r.map(o=>o.value).join(" ").trim().split(" "));Wn.exports=ol});var Gn=w((Sm,Hn)=>{"use strict";var nl=P(),sl=D(),il=(t,e,r)=>{let o=null,n=null,s=null;try{s=new sl(e,r)}catch{return null}return t.forEach(i=>{s.test(i)&&(!o||n.compare(i)===-1)&&(o=i,n=new nl(o,r))}),o};Hn.exports=il});var Jn=w((Rm,Vn)=>{"use strict";var al=P(),cl=D(),ll=(t,e,r)=>{let o=null,n=null,s=null;try{s=new cl(e,r)}catch{return null}return t.forEach(i=>{s.test(i)&&(!o||n.compare(i)===1)&&(o=i,n=new al(o,r))}),o};Vn.exports=ll});var Yn=w((Am,zn)=>{"use strict";var gr=P(),ul=D(),Xn=ke(),pl=(t,e)=>{t=new ul(t,e);let r=new gr("0.0.0");if(t.test(r)||(r=new gr("0.0.0-0"),t.test(r)))return r;r=null;for(let o=0;o<t.set.length;++o){let n=t.set[o],s=null;n.forEach(i=>{let c=new gr(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!s||Xn(c,s))&&(s=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||Xn(r,s))&&(r=s)}return r&&t.test(r)?r:null};zn.exports=pl});var Qn=w((Im,Zn)=>{"use strict";var dl=D(),ml=(t,e)=>{try{return new dl(t,e).range||"*"}catch{return null}};Zn.exports=ml});var dt=w((bm,os)=>{"use strict";var fl=P(),rs=Me(),{ANY:hl}=rs,gl=D(),yl=Ue(),es=ke(),ts=at(),wl=lt(),El=ct(),Sl=(t,e,r,o)=>{t=new fl(t,o),e=new gl(e,o);let n,s,i,c,l;switch(r){case">":n=es,s=wl,i=ts,c=">",l=">=";break;case"<":n=ts,s=El,i=es,c="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(yl(t,e,o))return!1;for(let u=0;u<e.set.length;++u){let h=e.set[u],f=null,S=null;if(h.forEach(p=>{p.semver===hl&&(p=new rs(">=0.0.0")),f=f||p,S=S||p,n(p.semver,f.semver,o)?f=p:i(p.semver,S.semver,o)&&(S=p)}),f.operator===c||f.operator===l||(!S.operator||S.operator===c)&&s(t,S.semver))return!1;if(S.operator===l&&i(t,S.semver))return!1}return!0};os.exports=Sl});var ss=w((vm,ns)=>{"use strict";var Rl=dt(),Al=(t,e,r)=>Rl(t,e,">",r);ns.exports=Al});var as=w((Pm,is)=>{"use strict";var Il=dt(),bl=(t,e,r)=>Il(t,e,"<",r);is.exports=bl});var us=w((Cm,ls)=>{"use strict";var cs=D(),vl=(t,e,r)=>(t=new cs(t,r),e=new cs(e,r),t.intersects(e,r));ls.exports=vl});var ds=w((Tm,ps)=>{"use strict";var Pl=Ue(),Cl=L();ps.exports=(t,e,r)=>{let o=[],n=null,s=null,i=t.sort((h,f)=>Cl(h,f,r));for(let h of i)Pl(h,e,r)?(s=h,n||(n=h)):(s&&o.push([n,s]),s=null,n=null);n&&o.push([n,null]);let c=[];for(let[h,f]of o)h===f?c.push(h):!f&&h===i[0]?c.push("*"):f?h===i[0]?c.push(`<=${f}`):c.push(`${h} - ${f}`):c.push(`>=${h}`);let l=c.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var ws=w((Om,ys)=>{"use strict";var ms=D(),wr=Me(),{ANY:yr}=wr,je=Ue(),Er=L(),Tl=(t,e,r={})=>{if(t===e)return!0;t=new ms(t,r),e=new ms(e,r);let o=!1;e:for(let n of t.set){for(let s of e.set){let i=xl(n,s,r);if(o=o||i!==null,i)continue e}if(o)return!1}return!0},Ol=[new wr(">=0.0.0-0")],fs=[new wr(">=0.0.0")],xl=(t,e,r)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===yr){if(e.length===1&&e[0].semver===yr)return!0;r.includePrerelease?t=Ol:t=fs}if(e.length===1&&e[0].semver===yr){if(r.includePrerelease)return!0;e=fs}let o=new Set,n,s;for(let p of t)p.operator===">"||p.operator===">="?n=hs(n,p,r):p.operator==="<"||p.operator==="<="?s=gs(s,p,r):o.add(p.semver);if(o.size>1)return null;let i;if(n&&s){if(i=Er(n.semver,s.semver,r),i>0)return null;if(i===0&&(n.operator!==">="||s.operator!=="<="))return null}for(let p of o){if(n&&!je(p,String(n),r)||s&&!je(p,String(s),r))return null;for(let W of e)if(!je(p,String(W),r))return!1;return!0}let c,l,u,h,f=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,S=n&&!r.includePrerelease&&n.semver.prerelease.length?n.semver:!1;f&&f.prerelease.length===1&&s.operator==="<"&&f.prerelease[0]===0&&(f=!1);for(let p of e){if(h=h||p.operator===">"||p.operator===">=",u=u||p.operator==="<"||p.operator==="<=",n){if(S&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===S.major&&p.semver.minor===S.minor&&p.semver.patch===S.patch&&(S=!1),p.operator===">"||p.operator===">="){if(c=hs(n,p,r),c===p&&c!==n)return!1}else if(n.operator===">="&&!je(n.semver,String(p),r))return!1}if(s){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator==="<"||p.operator==="<="){if(l=gs(s,p,r),l===p&&l!==s)return!1}else if(s.operator==="<="&&!je(s.semver,String(p),r))return!1}if(!p.operator&&(s||n)&&i!==0)return!1}return!(n&&u&&!s&&i!==0||s&&h&&!n&&i!==0||S||f)},hs=(t,e,r)=>{if(!t)return e;let o=Er(t.semver,e.semver,r);return o>0?t:o<0||e.operator===">"&&t.operator===">="?e:t},gs=(t,e,r)=>{if(!t)return e;let o=Er(t.semver,e.semver,r);return o<0?t:o>0||e.operator==="<"&&t.operator==="<="?e:t};ys.exports=Tl});var Rr=w((xm,Rs)=>{"use strict";var Sr=he(),Es=Le(),$l=P(),Ss=sr(),Nl=ce(),Ll=Ho(),Dl=Vo(),kl=zo(),Ml=Qo(),_l=tn(),Ul=on(),jl=sn(),Fl=cn(),Bl=L(),Kl=dn(),Wl=fn(),ql=it(),Hl=wn(),Gl=Sn(),Vl=ke(),Jl=at(),Xl=ar(),zl=cr(),Yl=ct(),Zl=lt(),Ql=lr(),eu=On(),tu=Me(),ru=D(),ou=Ue(),nu=qn(),su=Gn(),iu=Jn(),au=Yn(),cu=Qn(),lu=dt(),uu=ss(),pu=as(),du=us(),mu=ds(),fu=ws();Rs.exports={parse:Nl,valid:Ll,clean:Dl,inc:kl,diff:Ml,major:_l,minor:Ul,patch:jl,prerelease:Fl,compare:Bl,rcompare:Kl,compareLoose:Wl,compareBuild:ql,sort:Hl,rsort:Gl,gt:Vl,lt:Jl,eq:Xl,neq:zl,gte:Yl,lte:Zl,cmp:Ql,coerce:eu,Comparator:tu,Range:ru,satisfies:ou,toComparators:nu,maxSatisfying:su,minSatisfying:iu,minVersion:au,validRange:cu,outside:lu,gtr:uu,ltr:pu,intersects:du,simplifyRange:mu,subset:fu,SemVer:$l,re:Sr.re,src:Sr.src,tokens:Sr.t,SEMVER_SPEC_VERSION:Es.SEMVER_SPEC_VERSION,RELEASE_TYPES:Es.RELEASE_TYPES,compareIdentifiers:Ss.compareIdentifiers,rcompareIdentifiers:Ss.rcompareIdentifiers}});var Qu={};Mi(Qu,{handleError:()=>Ci,main:()=>Pi,run:()=>Ti});module.exports=_i(Qu);var be=require("@medplum/core"),He=require("commander"),vi=N(require("dotenv"));var se=require("@medplum/core"),tt=require("commander");var jr=require("@medplum/core");var _r=require("@medplum/core"),q=require("node:fs"),Ur=require("node:os"),Mt=require("node:path"),j=class extends _r.ClientStorage{constructor(e){super(),this.dirName=(0,Mt.resolve)((0,Ur.homedir)(),".medplum"),this.fileName=(0,Mt.resolve)(this.dirName,e+".json")}clear(){this.writeFile({})}getString(e){return this.readFile()?.[e]}setString(e,r){let o=this.readFile()??{};r?o[e]=r:delete o[e],this.writeFile(o)}getObject(e){let r=this.getString(e);return r?JSON.parse(r):void 0}setObject(e,r){this.setString(e,r?JSON.stringify(r):void 0)}readFile(){if((0,q.existsSync)(this.fileName))return JSON.parse((0,q.readFileSync)(this.fileName,"utf8"))}writeFile(e){(0,q.existsSync)(this.dirName)||(0,q.mkdirSync)(this.dirName),(0,q.writeFileSync)(this.fileName,JSON.stringify(e,null,2),"utf8")}};async function R(t,e=!0){let r=t.profile??"default",o=new j(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:s,fhirUrlPath:i,accessToken:c,tokenUrl:l,authorizeUrl:u,clientId:h,clientSecret:f}=Ui(t,o),S=t.fetch??fetch,p=new jr.MedplumClient({fetch:S,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:o,onUnauthenticated:ji,verbose:t.verbose});return e&&(c?p.setAccessToken(c):h&&f&&(p.setBasicAuth(h,f),n?.authType!=="basic"&&await p.startClientLogin(h,f))),p}function Ui(t,e){let r=e.getObject("options"),o=t.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=t.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,s=t.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,i=t.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=t.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,l=t.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,u=t.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:s,tokenUrl:i,authorizeUrl:c,clientId:l,clientSecret:u}}function ji(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var ne=require("@medplum/core"),lo=require("commander");var Br=require("node:buffer");var te=new TextEncoder,_t=new TextDecoder,sp=2**32;function Fr(...t){let e=t.reduce((n,{length:s})=>n+s,0),r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}var Ge=t=>Br.Buffer.from(t).toString("base64url");var re=class extends Error{constructor(r,o){super(r,o);b(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};b(re,"code","ERR_JOSE_GENERIC");var $=class extends re{constructor(){super(...arguments);b(this,"code","ERR_JOSE_NOT_SUPPORTED")}};b($,"code","ERR_JOSE_NOT_SUPPORTED");var H=class extends re{constructor(){super(...arguments);b(this,"code","ERR_JWS_INVALID")}};b(H,"code","ERR_JWS_INVALID");var Pe=class extends re{constructor(){super(...arguments);b(this,"code","ERR_JWT_INVALID")}};b(Pe,"code","ERR_JWT_INVALID");var Kr,Wr,Ut=class extends(Wr=re,Kr=Symbol.asyncIterator,Wr){constructor(r="multiple matching keys found in the JSON Web Key Set",o){super(r,o);b(this,Kr);b(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};b(Ut,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var qr=N(require("node:util"),1),Ve=t=>qr.types.isKeyObject(t);var Hr=N(require("node:crypto"),1),Gr=N(require("node:util"),1),Bi=Hr.webcrypto,Vr=Bi,pe=t=>Gr.types.isCryptoKey(t);function F(t,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`)}function Ce(t,e){return t.name===e}function jt(t){return parseInt(t.name.slice(4),10)}function Ki(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Wi(t,e){if(e.length&&!e.some(r=>t.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){let o=e.pop();r+=`one of ${e.join(", ")}, or ${o}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function Jr(t,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Ce(t.algorithm,"HMAC"))throw F("HMAC");let o=parseInt(e.slice(2),10);if(jt(t.algorithm.hash)!==o)throw F(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Ce(t.algorithm,"RSASSA-PKCS1-v1_5"))throw F("RSASSA-PKCS1-v1_5");let o=parseInt(e.slice(2),10);if(jt(t.algorithm.hash)!==o)throw F(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Ce(t.algorithm,"RSA-PSS"))throw F("RSA-PSS");let o=parseInt(e.slice(2),10);if(jt(t.algorithm.hash)!==o)throw F(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(t.algorithm.name!=="Ed25519"&&t.algorithm.name!=="Ed448")throw F("Ed25519 or Ed448");break}case"Ed25519":{if(!Ce(t.algorithm,"Ed25519"))throw F("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Ce(t.algorithm,"ECDSA"))throw F("ECDSA");let o=Ki(e);if(t.algorithm.namedCurve!==o)throw F(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Wi(t,r)}function Xr(t,e,...r){if(r=r.filter(Boolean),r.length>2){let o=r.pop();t+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Te=(t,...e)=>Xr("Key must be ",t,...e);function Ft(t,e,...r){return Xr(`Key for the ${t} algorithm must be `,e,...r)}var Bt=t=>Ve(t)||pe(t),G=["KeyObject"];(globalThis.CryptoKey||Vr?.CryptoKey)&&G.push("CryptoKey");var qi=(...t)=>{let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let o of e){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let s of n){if(r.has(s))return!1;r.add(s)}}return!0},zr=qi;function Hi(t){return typeof t=="object"&&t!==null}function Oe(t){if(!Hi(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}var to=require("node:crypto");function z(t){return Oe(t)&&typeof t.kty=="string"}function Yr(t){return t.kty!=="oct"&&typeof t.d=="string"}function Zr(t){return t.kty!=="oct"&&typeof t.d>"u"}function Qr(t){return z(t)&&t.kty==="oct"&&typeof t.k=="string"}var Gi=t=>{switch(t){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new $("Unsupported key curve for this operation")}},Vi=(t,e)=>{let r;if(pe(t))r=to.KeyObject.from(t);else if(Ve(t))r=t;else{if(z(t))return t.crv;throw new TypeError(Te(t,...G))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let o=r.asymmetricKeyDetails.namedCurve;return e?o:Gi(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},ro=Vi;var oo=require("node:crypto"),Kt=(t,e)=>{let r;try{t instanceof oo.KeyObject?r=t.asymmetricKeyDetails?.modulusLength:r=Buffer.from(t.n,"base64url").byteLength<<3}catch{}if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)};var de=t=>t?.[Symbol.toStringTag],Wt=(t,e,r)=>{if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&e.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, when present its alg must be ${t}`);return!0},Ji=(t,e,r,o)=>{if(!(e instanceof Uint8Array)){if(o&&z(e)){if(Qr(e)&&Wt(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Bt(e))throw new TypeError(Ft(t,e,...G,"Uint8Array",o?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${de(e)} instances for symmetric algorithms must be of type "secret"`)}},Xi=(t,e,r,o)=>{if(o&&z(e))switch(r){case"sign":if(Yr(e)&&Wt(t,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Zr(e)&&Wt(t,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Bt(e))throw new TypeError(Ft(t,e,...G,o?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${de(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${de(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${de(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${de(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${de(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function no(t,e,r,o){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Ji(e,r,o,t):Xi(e,r,o,t)}var Op=no.bind(void 0,!1),so=no.bind(void 0,!0);function zi(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(i=>typeof i!="string"||i.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let i of o.crit){if(!s.has(i))throw new $(`Extension Header Parameter "${i}" is not recognized`);if(n[i]===void 0)throw new t(`Extension Header Parameter "${i}" is missing`);if(s.get(i)&&o[i]===void 0)throw new t(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(o.crit)}var io=zi;function qt(t){switch(t){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new $(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var xe=require("node:crypto");var Yi=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Ht(t,e){let r,o,n;if(e instanceof xe.KeyObject)r=e.asymmetricKeyType,o=e.asymmetricKeyDetails;else switch(n=!0,e.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(e.crv==="Ed25519"){r="ed25519";break}if(e.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let s;switch(t){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Kt(e,t);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:i,mgf1HashAlgorithm:c,saltLength:l}=o,u=parseInt(t.slice(-3),10);if(i!==void 0&&(i!==`sha${u}`||c!==i))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${t}`);if(l!==void 0&&l>u>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${t}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Kt(e,t),s={padding:xe.constants.RSA_PKCS1_PSS_PADDING,saltLength:xe.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(r!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let i=ro(e),c=Yi.get(t);if(i!==c)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${c}, got ${i}`);s={dsaEncoding:"ieee-p1363"};break}default:throw new $(`alg ${t} is not supported either by JOSE or your javascript runtime`)}return n?{format:"jwk",key:e,...s}:s?{...s,key:e}:e}var Je=N(require("node:crypto"),1),ao=require("node:util");function Gt(t){switch(t){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new $(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var me=require("node:crypto");function Vt(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Te(e,...G));return(0,me.createSecretKey)(e)}if(e instanceof me.KeyObject)return e;if(pe(e))return Jr(e,t,r),me.KeyObject.from(e);if(z(e))return t.startsWith("HS")?(0,me.createSecretKey)(Buffer.from(e.k,"base64url")):e;throw new TypeError(Te(e,...G,"Uint8Array","JSON Web Key"))}var Zi=(0,ao.promisify)(Je.sign),Qi=async(t,e,r)=>{let o=Vt(t,e,"sign");if(t.startsWith("HS")){let n=Je.createHmac(Gt(t),o);return n.update(r),n.digest()}return Zi(qt(t),r,Ht(t,o))},co=Qi;var Y=t=>Math.floor(t.getTime()/1e3);var ea=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Xe=t=>{let e=ea.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),o=e[3].toLowerCase(),n;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*3600);break;case"day":case"days":case"d":n=Math.round(r*86400);break;case"week":case"weeks":case"w":n=Math.round(r*604800);break;default:n=Math.round(r*31557600);break}return e[1]==="-"||e[4]==="ago"?-n:n};var ze=class{constructor(e){b(this,"_payload");b(this,"_protectedHeader");b(this,"_unprotectedHeader");if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new H("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!zr(this._protectedHeader,this._unprotectedHeader))throw new H("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=io(H,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),s=!0;if(n.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new H('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=o;if(typeof i!="string"||!i)throw new H('JWS "alg" (Algorithm) Header Parameter missing or invalid');so(i,e,"sign");let c=this._payload;s&&(c=te.encode(Ge(c)));let l;this._protectedHeader?l=te.encode(Ge(JSON.stringify(this._protectedHeader))):l=te.encode("");let u=Fr(l,te.encode("."),c),h=await co(i,e,u),f={signature:Ge(h),payload:""};return s&&(f.payload=_t.decode(c)),this._unprotectedHeader&&(f.header=this._unprotectedHeader),this._protectedHeader&&(f.protected=_t.decode(l)),f}};var Ye=class{constructor(e){b(this,"_flattened");this._flattened=new ze(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,r){let o=await this._flattened.sign(e,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function oe(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var Ze=class{constructor(e={}){b(this,"_payload");if(!Oe(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:oe("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:oe("setNotBefore",Y(e))}:this._payload={...this._payload,nbf:Y(new Date)+Xe(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:oe("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:oe("setExpirationTime",Y(e))}:this._payload={...this._payload,exp:Y(new Date)+Xe(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:Y(new Date)}:e instanceof Date?this._payload={...this._payload,iat:oe("setIssuedAt",Y(e))}:typeof e=="string"?this._payload={...this._payload,iat:oe("setIssuedAt",Y(new Date)+Xe(e))}:this._payload={...this._payload,iat:oe("setIssuedAt",e)},this}};var $e=class extends Ze{constructor(){super(...arguments);b(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new Ye(te.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new Pe("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var fe=require("node:crypto"),Z=require("node:fs"),V=require("node:path"),uo=require("node:util/types"),po=require("tar");function J(t){console.log(JSON.stringify(t,null,2))}async function Jt(t,e,r){let o=e.source,n=Qe(o);if(!n)return;console.log("Saving source code...");let s=await t.createAttachment({data:n,filename:(0,V.basename)(o),contentType:oa(o)});console.log("Updating bot...");let i=await t.updateResource({...r,sourceCode:s});console.log("Success! New bot version: "+i.meta?.versionId)}async function Xt(t,e,r){let o=e.dist??e.source,n=Qe(o);if(!n)return;console.log("Deploying bot...");let s=await t.post(t.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,V.basename)(o)});console.log("Deploy result: "+s.issue?.[0]?.details?.text)}async function zt(t,e,r,o,n,s,i){let c={name:e,description:"",runtimeVersion:s},l=await t.post("admin/projects/"+r+"/bot",c),u=await t.readResource("Bot",l.id),h={name:e,id:l.id,source:o,dist:n};await Jt(t,h,u),await Xt(t,h,u),console.log(`Success! Bot created: ${u.id}`),i&&ta(h)}function mo(t){let e=new RegExp("^"+ra(t).replace(/\\\*/g,".*")+"$"),r=B()?.bots?.filter(o=>e.test(o.name));return r||[]}function M(t,e){if(e?.file)return e.file;let r=["medplum"];return t&&r.push(t),r.push("config"),e?.server&&r.push("server"),r.push("json"),r.join(".")}function v(t,e){(0,Z.writeFileSync)((0,V.resolve)(t),JSON.stringify(e,void 0,2),"utf-8")}function B(t,e){let r=M(t,e),o=Qe(r);if(o)return JSON.parse(o)}function fo(t){let e=Qe(M(t,{server:!0}));if(e)return JSON.parse(e)}function Qe(t){let e=(0,V.resolve)(t);return(0,Z.existsSync)(e)?(0,Z.readFileSync)(e,"utf8"):""}function ta(t){let e=B()??{};e.bots||(e.bots=[]),e.bots.push(t),(0,Z.writeFileSync)("medplum.config.json",JSON.stringify(e,null,2),"utf8"),console.log(`Bot added to config: ${t.id}`)}function ra(t){return t.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function ho(t){let o=0,n=0;return(0,po.extract)({cwd:t,filter:(s,i)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=i.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Yt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function oa(t){let e=(0,V.extname)(t).toLowerCase();return[".cjs",".mjs",".js"].includes(e)?ne.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(e)?ne.ContentType.TYPESCRIPT:ne.ContentType.TEXT}function et(t,e){let r=new j(t),o={name:t,...e};return r.setObject("options",o),o}function go(t){return new j(t).getObject("options")}async function yo(t,e){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),n={aud:`${e.baseUrl}${e.audience}`,iss:e.issuer,sub:e.subject,nbf:o,iat:o,exp:o+604800},s=(0,ne.encodeBase64)(JSON.stringify(r)),i=(0,ne.encodeBase64)(JSON.stringify(n)),c=`${s}.${i}`,l=(0,fe.createHmac)("sha256",e.clientSecret).update(c).digest("base64url"),u=`${c}.${l}`;await t.startJwtBearerLogin(e.clientId,u,e.scope??"")}async function wo(t,e){let r=(0,fe.createPrivateKey)((0,Z.readFileSync)((0,V.resolve)(e.privateKeyPath))),o=await new $e({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(e.clientId).setSubject(e.clientId).setAudience(`${e.baseUrl}${e.audience}`).setJti((0,fe.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await t.startJwtAssertionLogin(o)}function y(t,e){e.configureHelp({showGlobalOptions:!0}),t.addCommand(e)}var g=class extends lo.Command{action(e){let r=na(this,e);return super._actionHandler=r,this}resetOptionDefaults(){this._optionValues={};for(let e of this.options)e.defaultValue!==void 0&&(this._optionValues[e.attributeName()]=e.defaultValue)}};function na(t,e){return async r=>{let o=t.registeredArguments.length,n=r.slice(0,o);n[o]=t.optsWithGlobals();try{let s=e(...n);(0,uo.isPromise)(s)&&await s}finally{t.resetOptionDefaults()}}}var Eo=new g("status").aliases(["info","list","ls"]),So=new g("ping"),Ro=new g("push"),Ao=new g("reload-config"),Io=new g("upgrade"),ie=new g("agent");y(ie,Eo);y(ie,So);y(ie,Ro);y(ie,Ao);y(ie,Io);Eo.description("Get the status of a specified agent").argument("[agentIds...]","The ID(s) of the agent(s) to get the status of").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to get the status of. Mutually exclusive with [agentIds...] arg").addOption(new tt.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(t,e)=>{await Zt({operation:"$bulk-status",agentIds:t,options:e,parseSuccessfulResponse:r=>{let o=aa(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:o.version,connectionStatus:o.status,statusLastUpdated:o.lastUpdated??"N/A"}}})});So.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(t,e,r)=>{let o=await R(r),n=await bo(o,e,r),s=Number.parseInt(r.count,10);if(Number.isNaN(s))throw new Error("--count <count> must be an integer if specified");try{let i=await o.pushToAgent(n,t,`PING ${s}`,se.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});Ro.description("Push a message to a target device via a specified agent").argument("<deviceId>","The ID of the device to push the message to").argument("<message>","The message to send to the destination device").argument("[agentId]","Conditionally optional ID of the agent to send the message from. Mutually exclusive with --criteria <criteria> option").option("--content-type <contentType>","The content type of the message",se.ContentType.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(t,e,r,o)=>{let n=await R(o),s=await bo(n,r,o),i;try{i=await n.pushToAgent(s,{reference:`Device/${t}`},e,o.contentType,o.wait!==!1,{maxRetries:0})}catch(c){throw new Error("Unexpected response from agent while pushing message to agent",{cause:c})}console.info(i)});Ao.description("Reload the config for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) for which the config should be reloaded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) for which to notify to reload their config. Mutually exclusive with [agentIds...] arg").addOption(new tt.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(t,e)=>{await Zt({operation:"$reload-config",agentIds:t,options:e,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Io.description("Upgrade the version for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) that should be upgraded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to upgrade. Mutually exclusive with [agentIds...] arg").option("--version <version>","An optional version to upgrade to. Defaults to the latest version if flag not included").addOption(new tt.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(t,e)=>{await Zt({operation:"$upgrade",agentIds:t,options:e,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name,version:e.version??"latest"})})});async function Zt({operation:t,agentIds:e,options:r,parseSuccessfulResponse:o}){let n=la(e,r),s=await R(r),i=n.type==="criteria"?n.criteria:`Agent?_id=${n.ids.join(",")}`,c=new URLSearchParams(i.split("?")[1]),l;try{let p=s.fhirUrl("Agent",t);p.search=c.toString(),l=await s.get(p,{cache:"reload"})}catch(p){throw new Error(`Operation '${t}' failed`,{cause:p})}if(r.output==="json"){console.info(JSON.stringify(l,null,2));return}let u=[],h=[];switch(l.resourceType){case"Bundle":{let p=sa(l);for(let W of p)W.result.resourceType==="Parameters"||(0,se.isOk)(W.result)?u.push(W):h.push(W);break}case"Parameters":case"OperationOutcome":{let p=await s.searchOne("Agent",c,{cache:"reload"});if(!p)throw new Error("Agent not found");l.resourceType==="Parameters"?u.push({agent:p,result:l}):h.push({agent:p,result:l});break}default:throw new Error(`Invalid result received for '${t}' operation: ${JSON.stringify(l)}`)}let f=[];for(let p of u){let W=o(p);f.push(W)}let S=[];for(let p of h){let kt=p.result.issue?.[0],Oi={id:p.agent.id,name:p.agent.name,severity:kt.severity,code:kt.code,details:kt.details?.text??"No details to show"};S.push(Oi)}console.info(`
2
+ "use strict";var xi=Object.create;var ve=Object.defineProperty;var $i=Object.getOwnPropertyDescriptor;var Ni=Object.getOwnPropertyNames;var Li=Object.getPrototypeOf,Di=Object.prototype.hasOwnProperty;var ki=(t,e,r)=>e in t?ve(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var w=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Mi=(t,e)=>{for(var r in e)ve(t,r,{get:e[r],enumerable:!0})},Mr=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ni(e))!Di.call(t,n)&&n!==r&&ve(t,n,{get:()=>e[n],enumerable:!(o=$i(e,n))||o.enumerable});return t};var $=(t,e,r)=>(r=t!=null?xi(Li(t)):{},Mr(e||!t||!t.__esModule?ve(r,"default",{value:t,enumerable:!0}):r,t)),_i=t=>Mr(ve({},"__esModule",{value:!0}),t);var b=(t,e,r)=>ki(t,typeof e!="symbol"?e+"":e,r);var Le=w((Kd,$o)=>{"use strict";var Sa="2.0.0",Ra=Number.MAX_SAFE_INTEGER||9007199254740991,Aa=16,Ia=250,ba=["major","premajor","minor","preminor","patch","prepatch","prerelease"];$o.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Aa,MAX_SAFE_BUILD_LENGTH:Ia,MAX_SAFE_INTEGER:Ra,RELEASE_TYPES:ba,SEMVER_SPEC_VERSION:Sa,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var De=w((qd,No)=>{"use strict";var va=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};No.exports=va});var he=w((W,Lo)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:rr,MAX_SAFE_BUILD_LENGTH:Pa,MAX_LENGTH:Ca}=Le(),Ta=De();W=Lo.exports={};var Oa=W.re=[],xa=W.safeRe=[],d=W.src=[],$a=W.safeSrc=[],m=W.t={},Na=0,or="[a-zA-Z0-9-]",La=[["\\s",1],["\\d",Ca],[or,Pa]],Da=t=>{for(let[e,r]of La)t=t.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return t},E=(t,e,r)=>{let o=Da(e),n=Na++;Ta(t,n,e),m[t]=n,d[n]=e,$a[n]=o,Oa[n]=new RegExp(e,r?"g":void 0),xa[n]=new RegExp(o,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${or}*`);E("MAINVERSION",`(${d[m.NUMERICIDENTIFIER]})\\.(${d[m.NUMERICIDENTIFIER]})\\.(${d[m.NUMERICIDENTIFIER]})`);E("MAINVERSIONLOOSE",`(${d[m.NUMERICIDENTIFIERLOOSE]})\\.(${d[m.NUMERICIDENTIFIERLOOSE]})\\.(${d[m.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASEIDENTIFIER",`(?:${d[m.NUMERICIDENTIFIER]}|${d[m.NONNUMERICIDENTIFIER]})`);E("PRERELEASEIDENTIFIERLOOSE",`(?:${d[m.NUMERICIDENTIFIERLOOSE]}|${d[m.NONNUMERICIDENTIFIER]})`);E("PRERELEASE",`(?:-(${d[m.PRERELEASEIDENTIFIER]}(?:\\.${d[m.PRERELEASEIDENTIFIER]})*))`);E("PRERELEASELOOSE",`(?:-?(${d[m.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${d[m.PRERELEASEIDENTIFIERLOOSE]})*))`);E("BUILDIDENTIFIER",`${or}+`);E("BUILD",`(?:\\+(${d[m.BUILDIDENTIFIER]}(?:\\.${d[m.BUILDIDENTIFIER]})*))`);E("FULLPLAIN",`v?${d[m.MAINVERSION]}${d[m.PRERELEASE]}?${d[m.BUILD]}?`);E("FULL",`^${d[m.FULLPLAIN]}$`);E("LOOSEPLAIN",`[v=\\s]*${d[m.MAINVERSIONLOOSE]}${d[m.PRERELEASELOOSE]}?${d[m.BUILD]}?`);E("LOOSE",`^${d[m.LOOSEPLAIN]}$`);E("GTLT","((?:<|>)?=?)");E("XRANGEIDENTIFIERLOOSE",`${d[m.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);E("XRANGEIDENTIFIER",`${d[m.NUMERICIDENTIFIER]}|x|X|\\*`);E("XRANGEPLAIN",`[v=\\s]*(${d[m.XRANGEIDENTIFIER]})(?:\\.(${d[m.XRANGEIDENTIFIER]})(?:\\.(${d[m.XRANGEIDENTIFIER]})(?:${d[m.PRERELEASE]})?${d[m.BUILD]}?)?)?`);E("XRANGEPLAINLOOSE",`[v=\\s]*(${d[m.XRANGEIDENTIFIERLOOSE]})(?:\\.(${d[m.XRANGEIDENTIFIERLOOSE]})(?:\\.(${d[m.XRANGEIDENTIFIERLOOSE]})(?:${d[m.PRERELEASELOOSE]})?${d[m.BUILD]}?)?)?`);E("XRANGE",`^${d[m.GTLT]}\\s*${d[m.XRANGEPLAIN]}$`);E("XRANGELOOSE",`^${d[m.GTLT]}\\s*${d[m.XRANGEPLAINLOOSE]}$`);E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${rr}})(?:\\.(\\d{1,${rr}}))?(?:\\.(\\d{1,${rr}}))?`);E("COERCE",`${d[m.COERCEPLAIN]}(?:$|[^\\d])`);E("COERCEFULL",d[m.COERCEPLAIN]+`(?:${d[m.PRERELEASE]})?(?:${d[m.BUILD]})?(?:$|[^\\d])`);E("COERCERTL",d[m.COERCE],!0);E("COERCERTLFULL",d[m.COERCEFULL],!0);E("LONETILDE","(?:~>?)");E("TILDETRIM",`(\\s*)${d[m.LONETILDE]}\\s+`,!0);W.tildeTrimReplace="$1~";E("TILDE",`^${d[m.LONETILDE]}${d[m.XRANGEPLAIN]}$`);E("TILDELOOSE",`^${d[m.LONETILDE]}${d[m.XRANGEPLAINLOOSE]}$`);E("LONECARET","(?:\\^)");E("CARETTRIM",`(\\s*)${d[m.LONECARET]}\\s+`,!0);W.caretTrimReplace="$1^";E("CARET",`^${d[m.LONECARET]}${d[m.XRANGEPLAIN]}$`);E("CARETLOOSE",`^${d[m.LONECARET]}${d[m.XRANGEPLAINLOOSE]}$`);E("COMPARATORLOOSE",`^${d[m.GTLT]}\\s*(${d[m.LOOSEPLAIN]})$|^$`);E("COMPARATOR",`^${d[m.GTLT]}\\s*(${d[m.FULLPLAIN]})$|^$`);E("COMPARATORTRIM",`(\\s*)${d[m.GTLT]}\\s*(${d[m.LOOSEPLAIN]}|${d[m.XRANGEPLAIN]})`,!0);W.comparatorTrimReplace="$1$2$3";E("HYPHENRANGE",`^\\s*(${d[m.XRANGEPLAIN]})\\s+-\\s+(${d[m.XRANGEPLAIN]})\\s*$`);E("HYPHENRANGELOOSE",`^\\s*(${d[m.XRANGEPLAINLOOSE]})\\s+-\\s+(${d[m.XRANGEPLAINLOOSE]})\\s*$`);E("STAR","(<|>)?=?\\s*\\*");E("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");E("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var rt=w((Hd,Do)=>{"use strict";var ka=Object.freeze({loose:!0}),Ma=Object.freeze({}),_a=t=>t?typeof t!="object"?ka:t:Ma;Do.exports=_a});var nr=w((Gd,_o)=>{"use strict";var ko=/^[0-9]+$/,Mo=(t,e)=>{let r=ko.test(t),o=ko.test(e);return r&&o&&(t=+t,e=+e),t===e?0:r&&!o?-1:o&&!r?1:t<e?-1:1},Ua=(t,e)=>Mo(e,t);_o.exports={compareIdentifiers:Mo,rcompareIdentifiers:Ua}});var P=w((Vd,Bo)=>{"use strict";var ot=De(),{MAX_LENGTH:Uo,MAX_SAFE_INTEGER:nt}=Le(),{safeRe:jo,safeSrc:Fo,t:st}=he(),ja=rt(),{compareIdentifiers:ge}=nr(),sr=class t{constructor(e,r){if(r=ja(r),e instanceof t){if(e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Uo)throw new TypeError(`version is longer than ${Uo} characters`);ot("SemVer",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let o=e.trim().match(r.loose?jo[st.LOOSE]:jo[st.FULL]);if(!o)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+o[1],this.minor=+o[2],this.patch=+o[3],this.major>nt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>nt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>nt||this.patch<0)throw new TypeError("Invalid patch version");o[4]?this.prerelease=o[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let s=+n;if(s>=0&&s<nt)return s}return n}):this.prerelease=[],this.build=o[5]?o[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(ot("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),ge(this.major,e.major)||ge(this.minor,e.minor)||ge(this.patch,e.patch)}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let r=0;do{let o=this.prerelease[r],n=e.prerelease[r];if(ot("prerelease compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return ge(o,n)}while(++r)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let r=0;do{let o=this.build[r],n=e.build[r];if(ot("build compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return ge(o,n)}while(++r)}inc(e,r,o){if(e.startsWith("pre")){if(!r&&o===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let n=new RegExp(`^${this.options.loose?Fo[st.PRERELEASELOOSE]:Fo[st.PRERELEASE]}$`),s=`-${r}`.match(n);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,o);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,o);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,o),this.inc("pre",r,o);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,o),this.inc("pre",r,o);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let n=Number(o)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(r===this.prerelease.join(".")&&o===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(r){let s=[r,n];o===!1&&(s=[r]),ge(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Bo.exports=sr});var ce=w((Jd,Ko)=>{"use strict";var Wo=P(),Fa=(t,e,r=!1)=>{if(t instanceof Wo)return t;try{return new Wo(t,e)}catch(o){if(!r)return null;throw o}};Ko.exports=Fa});var Ho=w((Xd,qo)=>{"use strict";var Ba=ce(),Wa=(t,e)=>{let r=Ba(t,e);return r?r.version:null};qo.exports=Wa});var Vo=w((zd,Go)=>{"use strict";var Ka=ce(),qa=(t,e)=>{let r=Ka(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};Go.exports=qa});var zo=w((Yd,Xo)=>{"use strict";var Jo=P(),Ha=(t,e,r,o,n)=>{typeof r=="string"&&(n=o,o=r,r=void 0);try{return new Jo(t instanceof Jo?t.version:t,r).inc(e,o,n).version}catch{return null}};Xo.exports=Ha});var Qo=w((Zd,Zo)=>{"use strict";var Yo=ce(),Ga=(t,e)=>{let r=Yo(t,null,!0),o=Yo(e,null,!0),n=r.compare(o);if(n===0)return null;let s=n>0,i=s?r:o,c=s?o:r,l=!!i.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(c.compareMain(i)===0)return c.minor&&!c.patch?"minor":"patch"}let h=l?"pre":"";return r.major!==o.major?h+"major":r.minor!==o.minor?h+"minor":r.patch!==o.patch?h+"patch":"prerelease"};Zo.exports=Ga});var tn=w((Qd,en)=>{"use strict";var Va=P(),Ja=(t,e)=>new Va(t,e).major;en.exports=Ja});var on=w((em,rn)=>{"use strict";var Xa=P(),za=(t,e)=>new Xa(t,e).minor;rn.exports=za});var sn=w((tm,nn)=>{"use strict";var Ya=P(),Za=(t,e)=>new Ya(t,e).patch;nn.exports=Za});var cn=w((rm,an)=>{"use strict";var Qa=ce(),ec=(t,e)=>{let r=Qa(t,e);return r&&r.prerelease.length?r.prerelease:null};an.exports=ec});var L=w((om,un)=>{"use strict";var ln=P(),tc=(t,e,r)=>new ln(t,r).compare(new ln(e,r));un.exports=tc});var dn=w((nm,pn)=>{"use strict";var rc=L(),oc=(t,e,r)=>rc(e,t,r);pn.exports=oc});var fn=w((sm,mn)=>{"use strict";var nc=L(),sc=(t,e)=>nc(t,e,!0);mn.exports=sc});var it=w((im,gn)=>{"use strict";var hn=P(),ic=(t,e,r)=>{let o=new hn(t,r),n=new hn(e,r);return o.compare(n)||o.compareBuild(n)};gn.exports=ic});var wn=w((am,yn)=>{"use strict";var ac=it(),cc=(t,e)=>t.sort((r,o)=>ac(r,o,e));yn.exports=cc});var Sn=w((cm,En)=>{"use strict";var lc=it(),uc=(t,e)=>t.sort((r,o)=>lc(o,r,e));En.exports=uc});var ke=w((lm,Rn)=>{"use strict";var pc=L(),dc=(t,e,r)=>pc(t,e,r)>0;Rn.exports=dc});var at=w((um,An)=>{"use strict";var mc=L(),fc=(t,e,r)=>mc(t,e,r)<0;An.exports=fc});var ir=w((pm,In)=>{"use strict";var hc=L(),gc=(t,e,r)=>hc(t,e,r)===0;In.exports=gc});var ar=w((dm,bn)=>{"use strict";var yc=L(),wc=(t,e,r)=>yc(t,e,r)!==0;bn.exports=wc});var ct=w((mm,vn)=>{"use strict";var Ec=L(),Sc=(t,e,r)=>Ec(t,e,r)>=0;vn.exports=Sc});var lt=w((fm,Pn)=>{"use strict";var Rc=L(),Ac=(t,e,r)=>Rc(t,e,r)<=0;Pn.exports=Ac});var cr=w((hm,Cn)=>{"use strict";var Ic=ir(),bc=ar(),vc=ke(),Pc=ct(),Cc=at(),Tc=lt(),Oc=(t,e,r,o)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t===r;case"!==":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t!==r;case"":case"=":case"==":return Ic(t,r,o);case"!=":return bc(t,r,o);case">":return vc(t,r,o);case">=":return Pc(t,r,o);case"<":return Cc(t,r,o);case"<=":return Tc(t,r,o);default:throw new TypeError(`Invalid operator: ${e}`)}};Cn.exports=Oc});var On=w((gm,Tn)=>{"use strict";var xc=P(),$c=ce(),{safeRe:ut,t:pt}=he(),Nc=(t,e)=>{if(t instanceof xc)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let r=null;if(!e.rtl)r=t.match(e.includePrerelease?ut[pt.COERCEFULL]:ut[pt.COERCE]);else{let l=e.includePrerelease?ut[pt.COERCERTLFULL]:ut[pt.COERCERTL],u;for(;(u=l.exec(t))&&(!r||r.index+r[0].length!==t.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let o=r[2],n=r[3]||"0",s=r[4]||"0",i=e.includePrerelease&&r[5]?`-${r[5]}`:"",c=e.includePrerelease&&r[6]?`+${r[6]}`:"";return $c(`${o}.${n}.${s}${i}${c}`,e)};Tn.exports=Nc});var $n=w((ym,xn)=>{"use strict";var lr=class{constructor(){this.max=1e3,this.map=new Map}get(e){let r=this.map.get(e);if(r!==void 0)return this.map.delete(e),this.map.set(e,r),r}delete(e){return this.map.delete(e)}set(e,r){if(!this.delete(e)&&r!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(e,r)}return this}};xn.exports=lr});var D=w((wm,kn)=>{"use strict";var Lc=/\s+/g,ur=class t{constructor(e,r){if(r=kc(r),e instanceof t)return e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease?e:new t(e.raw,r);if(e instanceof pr)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=e.trim().replace(Lc," "),this.set=this.raw.split("||").map(o=>this.parseRange(o.trim())).filter(o=>o.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let o=this.set[0];if(this.set=this.set.filter(n=>!Ln(n[0])),this.set.length===0)this.set=[o];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&Wc(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let r=this.set[e];for(let o=0;o<r.length;o++)o>0&&(this.formatted+=" "),this.formatted+=r[o].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let o=((this.options.includePrerelease&&Fc)|(this.options.loose&&Bc))+":"+e,n=Nn.get(o);if(n)return n;let s=this.options.loose,i=s?O[C.HYPHENRANGELOOSE]:O[C.HYPHENRANGE];e=e.replace(i,Zc(this.options.includePrerelease)),A("hyphen replace",e),e=e.replace(O[C.COMPARATORTRIM],_c),A("comparator trim",e),e=e.replace(O[C.TILDETRIM],Uc),A("tilde trim",e),e=e.replace(O[C.CARETTRIM],jc),A("caret trim",e);let c=e.split(" ").map(f=>Kc(f,this.options)).join(" ").split(/\s+/).map(f=>Yc(f,this.options));s&&(c=c.filter(f=>(A("loose invalid filter",f,this.options),!!f.match(O[C.COMPARATORLOOSE])))),A("range list",c);let l=new Map,u=c.map(f=>new pr(f,this.options));for(let f of u){if(Ln(f))return[f];l.set(f.value,f)}l.size>1&&l.has("")&&l.delete("");let h=[...l.values()];return Nn.set(o,h),h}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(o=>Dn(o,r)&&e.set.some(n=>Dn(n,r)&&o.every(s=>n.every(i=>s.intersects(i,r)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new Mc(e,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(Qc(this.set[r],e,this.options))return!0;return!1}};kn.exports=ur;var Dc=$n(),Nn=new Dc,kc=rt(),pr=Me(),A=De(),Mc=P(),{safeRe:O,t:C,comparatorTrimReplace:_c,tildeTrimReplace:Uc,caretTrimReplace:jc}=he(),{FLAG_INCLUDE_PRERELEASE:Fc,FLAG_LOOSE:Bc}=Le(),Ln=t=>t.value==="<0.0.0-0",Wc=t=>t.value==="",Dn=(t,e)=>{let r=!0,o=t.slice(),n=o.pop();for(;r&&o.length;)r=o.every(s=>n.intersects(s,e)),n=o.pop();return r},Kc=(t,e)=>(A("comp",t,e),t=Gc(t,e),A("caret",t),t=qc(t,e),A("tildes",t),t=Jc(t,e),A("xrange",t),t=zc(t,e),A("stars",t),t),T=t=>!t||t.toLowerCase()==="x"||t==="*",qc=(t,e)=>t.trim().split(/\s+/).map(r=>Hc(r,e)).join(" "),Hc=(t,e)=>{let r=e.loose?O[C.TILDELOOSE]:O[C.TILDE];return t.replace(r,(o,n,s,i,c)=>{A("tilde",t,o,n,s,i,c);let l;return T(n)?l="":T(s)?l=`>=${n}.0.0 <${+n+1}.0.0-0`:T(i)?l=`>=${n}.${s}.0 <${n}.${+s+1}.0-0`:c?(A("replaceTilde pr",c),l=`>=${n}.${s}.${i}-${c} <${n}.${+s+1}.0-0`):l=`>=${n}.${s}.${i} <${n}.${+s+1}.0-0`,A("tilde return",l),l})},Gc=(t,e)=>t.trim().split(/\s+/).map(r=>Vc(r,e)).join(" "),Vc=(t,e)=>{A("caret",t,e);let r=e.loose?O[C.CARETLOOSE]:O[C.CARET],o=e.includePrerelease?"-0":"";return t.replace(r,(n,s,i,c,l)=>{A("caret",t,n,s,i,c,l);let u;return T(s)?u="":T(i)?u=`>=${s}.0.0${o} <${+s+1}.0.0-0`:T(c)?s==="0"?u=`>=${s}.${i}.0${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${o} <${+s+1}.0.0-0`:l?(A("replaceCaret pr",l),s==="0"?i==="0"?u=`>=${s}.${i}.${c}-${l} <${s}.${i}.${+c+1}-0`:u=`>=${s}.${i}.${c}-${l} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${c}-${l} <${+s+1}.0.0-0`):(A("no pr"),s==="0"?i==="0"?u=`>=${s}.${i}.${c}${o} <${s}.${i}.${+c+1}-0`:u=`>=${s}.${i}.${c}${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${c} <${+s+1}.0.0-0`),A("caret return",u),u})},Jc=(t,e)=>(A("replaceXRanges",t,e),t.split(/\s+/).map(r=>Xc(r,e)).join(" ")),Xc=(t,e)=>{t=t.trim();let r=e.loose?O[C.XRANGELOOSE]:O[C.XRANGE];return t.replace(r,(o,n,s,i,c,l)=>{A("xRange",t,o,n,s,i,c,l);let u=T(s),h=u||T(i),f=h||T(c),S=f;return n==="="&&S&&(n=""),l=e.includePrerelease?"-0":"",u?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&S?(h&&(i=0),c=0,n===">"?(n=">=",h?(s=+s+1,i=0,c=0):(i=+i+1,c=0)):n==="<="&&(n="<",h?s=+s+1:i=+i+1),n==="<"&&(l="-0"),o=`${n+s}.${i}.${c}${l}`):h?o=`>=${s}.0.0${l} <${+s+1}.0.0-0`:f&&(o=`>=${s}.${i}.0${l} <${s}.${+i+1}.0-0`),A("xRange return",o),o})},zc=(t,e)=>(A("replaceStars",t,e),t.trim().replace(O[C.STAR],"")),Yc=(t,e)=>(A("replaceGTE0",t,e),t.trim().replace(O[e.includePrerelease?C.GTE0PRE:C.GTE0],"")),Zc=t=>(e,r,o,n,s,i,c,l,u,h,f,S)=>(T(o)?r="":T(n)?r=`>=${o}.0.0${t?"-0":""}`:T(s)?r=`>=${o}.${n}.0${t?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${t?"-0":""}`,T(u)?l="":T(h)?l=`<${+u+1}.0.0-0`:T(f)?l=`<${u}.${+h+1}.0-0`:S?l=`<=${u}.${h}.${f}-${S}`:t?l=`<${u}.${h}.${+f+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),Qc=(t,e,r)=>{for(let o=0;o<t.length;o++)if(!t[o].test(e))return!1;if(e.prerelease.length&&!r.includePrerelease){for(let o=0;o<t.length;o++)if(A(t[o].semver),t[o].semver!==pr.ANY&&t[o].semver.prerelease.length>0){let n=t[o].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0}});var Me=w((Em,Bn)=>{"use strict";var _e=Symbol("SemVer ANY"),fr=class t{static get ANY(){return _e}constructor(e,r){if(r=Mn(r),e instanceof t){if(e.loose===!!r.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),mr("comparator",e,r),this.options=r,this.loose=!!r.loose,this.parse(e),this.semver===_e?this.value="":this.value=this.operator+this.semver.version,mr("comp",this)}parse(e){let r=this.options.loose?_n[Un.COMPARATORLOOSE]:_n[Un.COMPARATOR],o=e.match(r);if(!o)throw new TypeError(`Invalid comparator: ${e}`);this.operator=o[1]!==void 0?o[1]:"",this.operator==="="&&(this.operator=""),o[2]?this.semver=new jn(o[2],this.options.loose):this.semver=_e}toString(){return this.value}test(e){if(mr("Comparator.test",e,this.options.loose),this.semver===_e||e===_e)return!0;if(typeof e=="string")try{e=new jn(e,this.options)}catch{return!1}return dr(e,this.operator,this.semver,this.options)}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Fn(e.value,r).test(this.value):e.operator===""?e.value===""?!0:new Fn(this.value,r).test(e.semver):(r=Mn(r),r.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||dr(this.semver,"<",e.semver,r)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||dr(this.semver,">",e.semver,r)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Bn.exports=fr;var Mn=rt(),{safeRe:_n,t:Un}=he(),dr=cr(),mr=De(),jn=P(),Fn=D()});var Ue=w((Sm,Wn)=>{"use strict";var el=D(),tl=(t,e,r)=>{try{e=new el(e,r)}catch{return!1}return e.test(t)};Wn.exports=tl});var qn=w((Rm,Kn)=>{"use strict";var rl=D(),ol=(t,e)=>new rl(t,e).set.map(r=>r.map(o=>o.value).join(" ").trim().split(" "));Kn.exports=ol});var Gn=w((Am,Hn)=>{"use strict";var nl=P(),sl=D(),il=(t,e,r)=>{let o=null,n=null,s=null;try{s=new sl(e,r)}catch{return null}return t.forEach(i=>{s.test(i)&&(!o||n.compare(i)===-1)&&(o=i,n=new nl(o,r))}),o};Hn.exports=il});var Jn=w((Im,Vn)=>{"use strict";var al=P(),cl=D(),ll=(t,e,r)=>{let o=null,n=null,s=null;try{s=new cl(e,r)}catch{return null}return t.forEach(i=>{s.test(i)&&(!o||n.compare(i)===1)&&(o=i,n=new al(o,r))}),o};Vn.exports=ll});var Yn=w((bm,zn)=>{"use strict";var hr=P(),ul=D(),Xn=ke(),pl=(t,e)=>{t=new ul(t,e);let r=new hr("0.0.0");if(t.test(r)||(r=new hr("0.0.0-0"),t.test(r)))return r;r=null;for(let o=0;o<t.set.length;++o){let n=t.set[o],s=null;n.forEach(i=>{let c=new hr(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!s||Xn(c,s))&&(s=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||Xn(r,s))&&(r=s)}return r&&t.test(r)?r:null};zn.exports=pl});var Qn=w((vm,Zn)=>{"use strict";var dl=D(),ml=(t,e)=>{try{return new dl(t,e).range||"*"}catch{return null}};Zn.exports=ml});var dt=w((Pm,os)=>{"use strict";var fl=P(),rs=Me(),{ANY:hl}=rs,gl=D(),yl=Ue(),es=ke(),ts=at(),wl=lt(),El=ct(),Sl=(t,e,r,o)=>{t=new fl(t,o),e=new gl(e,o);let n,s,i,c,l;switch(r){case">":n=es,s=wl,i=ts,c=">",l=">=";break;case"<":n=ts,s=El,i=es,c="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(yl(t,e,o))return!1;for(let u=0;u<e.set.length;++u){let h=e.set[u],f=null,S=null;if(h.forEach(p=>{p.semver===hl&&(p=new rs(">=0.0.0")),f=f||p,S=S||p,n(p.semver,f.semver,o)?f=p:i(p.semver,S.semver,o)&&(S=p)}),f.operator===c||f.operator===l||(!S.operator||S.operator===c)&&s(t,S.semver))return!1;if(S.operator===l&&i(t,S.semver))return!1}return!0};os.exports=Sl});var ss=w((Cm,ns)=>{"use strict";var Rl=dt(),Al=(t,e,r)=>Rl(t,e,">",r);ns.exports=Al});var as=w((Tm,is)=>{"use strict";var Il=dt(),bl=(t,e,r)=>Il(t,e,"<",r);is.exports=bl});var us=w((Om,ls)=>{"use strict";var cs=D(),vl=(t,e,r)=>(t=new cs(t,r),e=new cs(e,r),t.intersects(e,r));ls.exports=vl});var ds=w((xm,ps)=>{"use strict";var Pl=Ue(),Cl=L();ps.exports=(t,e,r)=>{let o=[],n=null,s=null,i=t.sort((h,f)=>Cl(h,f,r));for(let h of i)Pl(h,e,r)?(s=h,n||(n=h)):(s&&o.push([n,s]),s=null,n=null);n&&o.push([n,null]);let c=[];for(let[h,f]of o)h===f?c.push(h):!f&&h===i[0]?c.push("*"):f?h===i[0]?c.push(`<=${f}`):c.push(`${h} - ${f}`):c.push(`>=${h}`);let l=c.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var ws=w(($m,ys)=>{"use strict";var ms=D(),yr=Me(),{ANY:gr}=yr,je=Ue(),wr=L(),Tl=(t,e,r={})=>{if(t===e)return!0;t=new ms(t,r),e=new ms(e,r);let o=!1;e:for(let n of t.set){for(let s of e.set){let i=xl(n,s,r);if(o=o||i!==null,i)continue e}if(o)return!1}return!0},Ol=[new yr(">=0.0.0-0")],fs=[new yr(">=0.0.0")],xl=(t,e,r)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===gr){if(e.length===1&&e[0].semver===gr)return!0;r.includePrerelease?t=Ol:t=fs}if(e.length===1&&e[0].semver===gr){if(r.includePrerelease)return!0;e=fs}let o=new Set,n,s;for(let p of t)p.operator===">"||p.operator===">="?n=hs(n,p,r):p.operator==="<"||p.operator==="<="?s=gs(s,p,r):o.add(p.semver);if(o.size>1)return null;let i;if(n&&s){if(i=wr(n.semver,s.semver,r),i>0)return null;if(i===0&&(n.operator!==">="||s.operator!=="<="))return null}for(let p of o){if(n&&!je(p,String(n),r)||s&&!je(p,String(s),r))return null;for(let K of e)if(!je(p,String(K),r))return!1;return!0}let c,l,u,h,f=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,S=n&&!r.includePrerelease&&n.semver.prerelease.length?n.semver:!1;f&&f.prerelease.length===1&&s.operator==="<"&&f.prerelease[0]===0&&(f=!1);for(let p of e){if(h=h||p.operator===">"||p.operator===">=",u=u||p.operator==="<"||p.operator==="<=",n){if(S&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===S.major&&p.semver.minor===S.minor&&p.semver.patch===S.patch&&(S=!1),p.operator===">"||p.operator===">="){if(c=hs(n,p,r),c===p&&c!==n)return!1}else if(n.operator===">="&&!je(n.semver,String(p),r))return!1}if(s){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator==="<"||p.operator==="<="){if(l=gs(s,p,r),l===p&&l!==s)return!1}else if(s.operator==="<="&&!je(s.semver,String(p),r))return!1}if(!p.operator&&(s||n)&&i!==0)return!1}return!(n&&u&&!s&&i!==0||s&&h&&!n&&i!==0||S||f)},hs=(t,e,r)=>{if(!t)return e;let o=wr(t.semver,e.semver,r);return o>0?t:o<0||e.operator===">"&&t.operator===">="?e:t},gs=(t,e,r)=>{if(!t)return e;let o=wr(t.semver,e.semver,r);return o<0?t:o>0||e.operator==="<"&&t.operator==="<="?e:t};ys.exports=Tl});var Sr=w((Nm,Rs)=>{"use strict";var Er=he(),Es=Le(),$l=P(),Ss=nr(),Nl=ce(),Ll=Ho(),Dl=Vo(),kl=zo(),Ml=Qo(),_l=tn(),Ul=on(),jl=sn(),Fl=cn(),Bl=L(),Wl=dn(),Kl=fn(),ql=it(),Hl=wn(),Gl=Sn(),Vl=ke(),Jl=at(),Xl=ir(),zl=ar(),Yl=ct(),Zl=lt(),Ql=cr(),eu=On(),tu=Me(),ru=D(),ou=Ue(),nu=qn(),su=Gn(),iu=Jn(),au=Yn(),cu=Qn(),lu=dt(),uu=ss(),pu=as(),du=us(),mu=ds(),fu=ws();Rs.exports={parse:Nl,valid:Ll,clean:Dl,inc:kl,diff:Ml,major:_l,minor:Ul,patch:jl,prerelease:Fl,compare:Bl,rcompare:Wl,compareLoose:Kl,compareBuild:ql,sort:Hl,rsort:Gl,gt:Vl,lt:Jl,eq:Xl,neq:zl,gte:Yl,lte:Zl,cmp:Ql,coerce:eu,Comparator:tu,Range:ru,satisfies:ou,toComparators:nu,maxSatisfying:su,minSatisfying:iu,minVersion:au,validRange:cu,outside:lu,gtr:uu,ltr:pu,intersects:du,simplifyRange:mu,subset:fu,SemVer:$l,re:Er.re,src:Er.src,tokens:Er.t,SEMVER_SPEC_VERSION:Es.SEMVER_SPEC_VERSION,RELEASE_TYPES:Es.RELEASE_TYPES,compareIdentifiers:Ss.compareIdentifiers,rcompareIdentifiers:Ss.rcompareIdentifiers}});var Qu={};Mi(Qu,{handleError:()=>Ci,main:()=>Pi,run:()=>Ti});module.exports=_i(Qu);var be=require("@medplum/core"),He=require("commander"),vi=$(require("dotenv"));var se=require("@medplum/core"),tt=require("commander");var jr=require("@medplum/core");var _r=require("@medplum/core"),q=require("node:fs"),Ur=require("node:os"),kt=require("node:path"),j=class extends _r.ClientStorage{constructor(e){super(),this.dirName=(0,kt.resolve)((0,Ur.homedir)(),".medplum"),this.fileName=(0,kt.resolve)(this.dirName,e+".json")}clear(){this.writeFile({})}getString(e){return this.readFile()?.[e]}setString(e,r){let o=this.readFile()??{};r?o[e]=r:delete o[e],this.writeFile(o)}getObject(e){let r=this.getString(e);return r?JSON.parse(r):void 0}setObject(e,r){this.setString(e,r?JSON.stringify(r):void 0)}readFile(){if((0,q.existsSync)(this.fileName))return JSON.parse((0,q.readFileSync)(this.fileName,"utf8"))}writeFile(e){(0,q.existsSync)(this.dirName)||(0,q.mkdirSync)(this.dirName),(0,q.writeFileSync)(this.fileName,JSON.stringify(e,null,2),"utf8")}};async function R(t,e=!0){let r=t.profile??"default",o=new j(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:s,fhirUrlPath:i,accessToken:c,tokenUrl:l,authorizeUrl:u,clientId:h,clientSecret:f}=Ui(t,o),S=t.fetch??fetch,p=new jr.MedplumClient({fetch:S,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:o,onUnauthenticated:ji,verbose:t.verbose});return e&&(c?p.setAccessToken(c):h&&f&&(p.setBasicAuth(h,f),n?.authType!=="basic"&&await p.startClientLogin(h,f))),p}function Ui(t,e){let r=e.getObject("options"),o=t.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=t.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,s=t.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,i=t.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=t.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,l=t.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,u=t.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:s,tokenUrl:i,authorizeUrl:c,clientId:l,clientSecret:u}}function ji(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var ne=require("@medplum/core"),lo=require("commander");var Br=require("node:buffer");var te=new TextEncoder,Mt=new TextDecoder,sp=2**32;function Fr(...t){let e=t.reduce((n,{length:s})=>n+s,0),r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}var Ge=t=>Br.Buffer.from(t).toString("base64url");var re=class extends Error{constructor(r,o){super(r,o);b(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};b(re,"code","ERR_JOSE_GENERIC");var N=class extends re{constructor(){super(...arguments);b(this,"code","ERR_JOSE_NOT_SUPPORTED")}};b(N,"code","ERR_JOSE_NOT_SUPPORTED");var H=class extends re{constructor(){super(...arguments);b(this,"code","ERR_JWS_INVALID")}};b(H,"code","ERR_JWS_INVALID");var Pe=class extends re{constructor(){super(...arguments);b(this,"code","ERR_JWT_INVALID")}};b(Pe,"code","ERR_JWT_INVALID");var Wr,Kr,_t=class extends(Kr=re,Wr=Symbol.asyncIterator,Kr){constructor(r="multiple matching keys found in the JSON Web Key Set",o){super(r,o);b(this,Wr);b(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};b(_t,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var qr=$(require("node:util"),1),Ve=t=>qr.types.isKeyObject(t);var Hr=$(require("node:crypto"),1),Gr=$(require("node:util"),1),Bi=Hr.webcrypto,Vr=Bi,pe=t=>Gr.types.isCryptoKey(t);function F(t,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`)}function Ce(t,e){return t.name===e}function Ut(t){return parseInt(t.name.slice(4),10)}function Wi(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Ki(t,e){if(e.length&&!e.some(r=>t.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){let o=e.pop();r+=`one of ${e.join(", ")}, or ${o}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function Jr(t,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Ce(t.algorithm,"HMAC"))throw F("HMAC");let o=parseInt(e.slice(2),10);if(Ut(t.algorithm.hash)!==o)throw F(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Ce(t.algorithm,"RSASSA-PKCS1-v1_5"))throw F("RSASSA-PKCS1-v1_5");let o=parseInt(e.slice(2),10);if(Ut(t.algorithm.hash)!==o)throw F(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Ce(t.algorithm,"RSA-PSS"))throw F("RSA-PSS");let o=parseInt(e.slice(2),10);if(Ut(t.algorithm.hash)!==o)throw F(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(t.algorithm.name!=="Ed25519"&&t.algorithm.name!=="Ed448")throw F("Ed25519 or Ed448");break}case"Ed25519":{if(!Ce(t.algorithm,"Ed25519"))throw F("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Ce(t.algorithm,"ECDSA"))throw F("ECDSA");let o=Wi(e);if(t.algorithm.namedCurve!==o)throw F(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Ki(t,r)}function Xr(t,e,...r){if(r=r.filter(Boolean),r.length>2){let o=r.pop();t+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Te=(t,...e)=>Xr("Key must be ",t,...e);function jt(t,e,...r){return Xr(`Key for the ${t} algorithm must be `,e,...r)}var Ft=t=>Ve(t)||pe(t),G=["KeyObject"];(globalThis.CryptoKey||Vr?.CryptoKey)&&G.push("CryptoKey");var qi=(...t)=>{let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let o of e){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let s of n){if(r.has(s))return!1;r.add(s)}}return!0},zr=qi;function Hi(t){return typeof t=="object"&&t!==null}function Oe(t){if(!Hi(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}var to=require("node:crypto");function z(t){return Oe(t)&&typeof t.kty=="string"}function Yr(t){return t.kty!=="oct"&&typeof t.d=="string"}function Zr(t){return t.kty!=="oct"&&typeof t.d>"u"}function Qr(t){return z(t)&&t.kty==="oct"&&typeof t.k=="string"}var Gi=t=>{switch(t){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new N("Unsupported key curve for this operation")}},Vi=(t,e)=>{let r;if(pe(t))r=to.KeyObject.from(t);else if(Ve(t))r=t;else{if(z(t))return t.crv;throw new TypeError(Te(t,...G))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let o=r.asymmetricKeyDetails.namedCurve;return e?o:Gi(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},ro=Vi;var oo=require("node:crypto"),Bt=(t,e)=>{let r;try{t instanceof oo.KeyObject?r=t.asymmetricKeyDetails?.modulusLength:r=Buffer.from(t.n,"base64url").byteLength<<3}catch{}if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)};var de=t=>t?.[Symbol.toStringTag],Wt=(t,e,r)=>{if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&e.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, when present its alg must be ${t}`);return!0},Ji=(t,e,r,o)=>{if(!(e instanceof Uint8Array)){if(o&&z(e)){if(Qr(e)&&Wt(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Ft(e))throw new TypeError(jt(t,e,...G,"Uint8Array",o?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${de(e)} instances for symmetric algorithms must be of type "secret"`)}},Xi=(t,e,r,o)=>{if(o&&z(e))switch(r){case"sign":if(Yr(e)&&Wt(t,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Zr(e)&&Wt(t,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ft(e))throw new TypeError(jt(t,e,...G,o?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${de(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${de(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${de(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${de(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${de(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function no(t,e,r,o){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Ji(e,r,o,t):Xi(e,r,o,t)}var Op=no.bind(void 0,!1),so=no.bind(void 0,!0);function zi(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(i=>typeof i!="string"||i.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let i of o.crit){if(!s.has(i))throw new N(`Extension Header Parameter "${i}" is not recognized`);if(n[i]===void 0)throw new t(`Extension Header Parameter "${i}" is missing`);if(s.get(i)&&o[i]===void 0)throw new t(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(o.crit)}var io=zi;function Kt(t){switch(t){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new N(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var xe=require("node:crypto");var Yi=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function qt(t,e){let r,o,n;if(e instanceof xe.KeyObject)r=e.asymmetricKeyType,o=e.asymmetricKeyDetails;else switch(n=!0,e.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(e.crv==="Ed25519"){r="ed25519";break}if(e.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let s;switch(t){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Bt(e,t);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:i,mgf1HashAlgorithm:c,saltLength:l}=o,u=parseInt(t.slice(-3),10);if(i!==void 0&&(i!==`sha${u}`||c!==i))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${t}`);if(l!==void 0&&l>u>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${t}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Bt(e,t),s={padding:xe.constants.RSA_PKCS1_PSS_PADDING,saltLength:xe.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(r!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let i=ro(e),c=Yi.get(t);if(i!==c)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${c}, got ${i}`);s={dsaEncoding:"ieee-p1363"};break}default:throw new N(`alg ${t} is not supported either by JOSE or your javascript runtime`)}return n?{format:"jwk",key:e,...s}:s?{...s,key:e}:e}var Je=$(require("node:crypto"),1),ao=require("node:util");function Ht(t){switch(t){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new N(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var me=require("node:crypto");function Gt(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Te(e,...G));return(0,me.createSecretKey)(e)}if(e instanceof me.KeyObject)return e;if(pe(e))return Jr(e,t,r),me.KeyObject.from(e);if(z(e))return t.startsWith("HS")?(0,me.createSecretKey)(Buffer.from(e.k,"base64url")):e;throw new TypeError(Te(e,...G,"Uint8Array","JSON Web Key"))}var Zi=(0,ao.promisify)(Je.sign),Qi=async(t,e,r)=>{let o=Gt(t,e,"sign");if(t.startsWith("HS")){let n=Je.createHmac(Ht(t),o);return n.update(r),n.digest()}return Zi(Kt(t),r,qt(t,o))},co=Qi;var Y=t=>Math.floor(t.getTime()/1e3);var ea=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Xe=t=>{let e=ea.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),o=e[3].toLowerCase(),n;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*3600);break;case"day":case"days":case"d":n=Math.round(r*86400);break;case"week":case"weeks":case"w":n=Math.round(r*604800);break;default:n=Math.round(r*31557600);break}return e[1]==="-"||e[4]==="ago"?-n:n};var ze=class{constructor(e){b(this,"_payload");b(this,"_protectedHeader");b(this,"_unprotectedHeader");if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new H("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!zr(this._protectedHeader,this._unprotectedHeader))throw new H("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=io(H,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),s=!0;if(n.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new H('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=o;if(typeof i!="string"||!i)throw new H('JWS "alg" (Algorithm) Header Parameter missing or invalid');so(i,e,"sign");let c=this._payload;s&&(c=te.encode(Ge(c)));let l;this._protectedHeader?l=te.encode(Ge(JSON.stringify(this._protectedHeader))):l=te.encode("");let u=Fr(l,te.encode("."),c),h=await co(i,e,u),f={signature:Ge(h),payload:""};return s&&(f.payload=Mt.decode(c)),this._unprotectedHeader&&(f.header=this._unprotectedHeader),this._protectedHeader&&(f.protected=Mt.decode(l)),f}};var Ye=class{constructor(e){b(this,"_flattened");this._flattened=new ze(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,r){let o=await this._flattened.sign(e,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function oe(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var Ze=class{constructor(e={}){b(this,"_payload");if(!Oe(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:oe("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:oe("setNotBefore",Y(e))}:this._payload={...this._payload,nbf:Y(new Date)+Xe(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:oe("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:oe("setExpirationTime",Y(e))}:this._payload={...this._payload,exp:Y(new Date)+Xe(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:Y(new Date)}:e instanceof Date?this._payload={...this._payload,iat:oe("setIssuedAt",Y(e))}:typeof e=="string"?this._payload={...this._payload,iat:oe("setIssuedAt",Y(new Date)+Xe(e))}:this._payload={...this._payload,iat:oe("setIssuedAt",e)},this}};var $e=class extends Ze{constructor(){super(...arguments);b(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new Ye(te.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new Pe("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var fe=require("node:crypto"),Z=require("node:fs"),V=require("node:path"),uo=require("node:util/types"),po=require("tar");function J(t){console.log(JSON.stringify(t,null,2))}async function Vt(t,e,r){let o=e.source,n=Qe(o);if(!n)return;console.log("Saving source code...");let s=await t.createAttachment({data:n,filename:(0,V.basename)(o),contentType:oa(o)});console.log("Updating bot...");let i=await t.updateResource({...r,sourceCode:s});console.log("Success! New bot version: "+i.meta?.versionId)}async function Jt(t,e,r){let o=e.dist??e.source,n=Qe(o);if(!n)return;console.log("Deploying bot...");let s=await t.post(t.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,V.basename)(o)});console.log("Deploy result: "+s.issue?.[0]?.details?.text)}async function Xt(t,e,r,o,n,s,i){let c={name:e,description:"",runtimeVersion:s},l=await t.post("admin/projects/"+r+"/bot",c),u=await t.readResource("Bot",l.id),h={name:e,id:l.id,source:o,dist:n};await Vt(t,h,u),await Jt(t,h,u),console.log(`Success! Bot created: ${u.id}`),i&&ta(h)}function mo(t){let e=new RegExp("^"+ra(t).replace(/\\\*/g,".*")+"$"),r=B()?.bots?.filter(o=>e.test(o.name));return r||[]}function M(t,e){if(e?.file)return e.file;let r=["medplum"];return t&&r.push(t),r.push("config"),e?.server&&r.push("server"),r.push("json"),r.join(".")}function v(t,e){(0,Z.writeFileSync)((0,V.resolve)(t),JSON.stringify(e,void 0,2),"utf-8")}function B(t,e){let r=M(t,e),o=Qe(r);if(o)return JSON.parse(o)}function fo(t){let e=Qe(M(t,{server:!0}));if(e)return JSON.parse(e)}function Qe(t){let e=(0,V.resolve)(t);return(0,Z.existsSync)(e)?(0,Z.readFileSync)(e,"utf8"):""}function ta(t){let e=B()??{};e.bots||(e.bots=[]),e.bots.push(t),(0,Z.writeFileSync)("medplum.config.json",JSON.stringify(e,null,2),"utf8"),console.log(`Bot added to config: ${t.id}`)}function ra(t){return t.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function ho(t){let o=0,n=0;return(0,po.extract)({cwd:t,filter:(s,i)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=i.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function zt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function oa(t){let e=(0,V.extname)(t).toLowerCase();return[".cjs",".mjs",".js"].includes(e)?ne.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(e)?ne.ContentType.TYPESCRIPT:ne.ContentType.TEXT}function et(t,e){let r=new j(t),o={name:t,...e};return r.setObject("options",o),o}function go(t){return new j(t).getObject("options")}async function yo(t,e){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),n={aud:`${e.baseUrl}${e.audience}`,iss:e.issuer,sub:e.subject,nbf:o,iat:o,exp:o+604800},s=(0,ne.encodeBase64)(JSON.stringify(r)),i=(0,ne.encodeBase64)(JSON.stringify(n)),c=`${s}.${i}`,l=(0,fe.createHmac)("sha256",e.clientSecret).update(c).digest("base64url"),u=`${c}.${l}`;await t.startJwtBearerLogin(e.clientId,u,e.scope??"")}async function wo(t,e){let r=(0,fe.createPrivateKey)((0,Z.readFileSync)((0,V.resolve)(e.privateKeyPath))),o=await new $e({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(e.clientId).setSubject(e.clientId).setAudience(`${e.baseUrl}${e.audience}`).setJti((0,fe.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await t.startJwtAssertionLogin(o)}function y(t,e){e.configureHelp({showGlobalOptions:!0}),t.addCommand(e)}var g=class extends lo.Command{action(e){let r=na(this,e);return super._actionHandler=r,this}resetOptionDefaults(){this._optionValues={};for(let e of this.options)e.defaultValue!==void 0&&(this._optionValues[e.attributeName()]=e.defaultValue)}};function na(t,e){return async r=>{let o=t.registeredArguments.length,n=r.slice(0,o);n[o]=t.optsWithGlobals();try{let s=e(...n);(0,uo.isPromise)(s)&&await s}finally{t.resetOptionDefaults()}}}var Eo=new g("status").aliases(["info","list","ls"]),So=new g("ping"),Ro=new g("push"),Ao=new g("reload-config"),Io=new g("upgrade"),ie=new g("agent");y(ie,Eo);y(ie,So);y(ie,Ro);y(ie,Ao);y(ie,Io);Eo.description("Get the status of a specified agent").argument("[agentIds...]","The ID(s) of the agent(s) to get the status of").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to get the status of. Mutually exclusive with [agentIds...] arg").addOption(new tt.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(t,e)=>{await Yt({operation:"$bulk-status",agentIds:t,options:e,parseSuccessfulResponse:r=>{let o=aa(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:o.version,connectionStatus:o.status,statusLastUpdated:o.lastUpdated??"N/A"}}})});So.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(t,e,r)=>{let o=await R(r),n=await bo(o,e,r),s=Number.parseInt(r.count,10);if(Number.isNaN(s))throw new Error("--count <count> must be an integer if specified");try{let i=await o.pushToAgent(n,t,`PING ${s}`,se.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});Ro.description("Push a message to a target device via a specified agent").argument("<deviceId>","The ID of the device to push the message to").argument("<message>","The message to send to the destination device").argument("[agentId]","Conditionally optional ID of the agent to send the message from. Mutually exclusive with --criteria <criteria> option").option("--content-type <contentType>","The content type of the message",se.ContentType.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(t,e,r,o)=>{let n=await R(o),s=await bo(n,r,o),i;try{i=await n.pushToAgent(s,{reference:`Device/${t}`},e,o.contentType,o.wait!==!1,{maxRetries:0})}catch(c){throw new Error("Unexpected response from agent while pushing message to agent",{cause:c})}console.info(i)});Ao.description("Reload the config for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) for which the config should be reloaded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) for which to notify to reload their config. Mutually exclusive with [agentIds...] arg").addOption(new tt.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(t,e)=>{await Yt({operation:"$reload-config",agentIds:t,options:e,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Io.description("Upgrade the version for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) that should be upgraded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to upgrade. Mutually exclusive with [agentIds...] arg").option("--version <version>","An optional version to upgrade to. Defaults to the latest version if flag not included").addOption(new tt.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(t,e)=>{await Yt({operation:"$upgrade",agentIds:t,options:e,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name,version:e.version??"latest"})})});async function Yt({operation:t,agentIds:e,options:r,parseSuccessfulResponse:o}){let n=la(e,r),s=await R(r),i=n.type==="criteria"?n.criteria:`Agent?_id=${n.ids.join(",")}`,c=new URLSearchParams(i.split("?")[1]),l;try{let p=s.fhirUrl("Agent",t);p.search=c.toString(),l=await s.get(p,{cache:"reload"})}catch(p){throw new Error(`Operation '${t}' failed`,{cause:p})}if(r.output==="json"){console.info(JSON.stringify(l,null,2));return}let u=[],h=[];switch(l.resourceType){case"Bundle":{let p=sa(l);for(let K of p)K.result.resourceType==="Parameters"||(0,se.isOk)(K.result)?u.push(K):h.push(K);break}case"Parameters":case"OperationOutcome":{let p=await s.searchOne("Agent",c,{cache:"reload"});if(!p)throw new Error("Agent not found");l.resourceType==="Parameters"?u.push({agent:p,result:l}):h.push({agent:p,result:l});break}default:throw new Error(`Invalid result received for '${t}' operation: ${JSON.stringify(l)}`)}let f=[];for(let p of u){let K=o(p);f.push(K)}let S=[];for(let p of h){let Dt=p.result.issue?.[0],Oi={id:p.agent.id,name:p.agent.name,severity:Dt.severity,code:Dt.code,details:Dt.details?.text??"No details to show"};S.push(Oi)}console.info(`
3
3
  ${f.length} successful response(s):
4
- `),console.table(f.length?f:"No successful responses received"),console.info(),S.length&&(console.info(`${S.length} failed response(s):`),console.info(),console.table(S))}async function bo(t,e,r){if(!(e||r.criteria))throw new Error("This command requires either an [agentId] or a --criteria <criteria> flag");if(e&&r.criteria)throw new Error("Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive");let o;if(e)o=e;else{vo(r.criteria);let n=await t.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!n?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(n.entry.length!==1)throw new Error("Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent");o=n.entry[0].resource?.id}return{reference:`Agent/${o}`}}function sa(t){let e=[];for(let r of t.entry??[]){if(!r.resource)throw new Error("No Parameter resource found in entry");e.push(ia(r.resource))}return e}function ia(t){let e=t.parameter?.find(o=>o.name==="agent")?.resource;if(!e)throw new Error("Agent bulk operation response missing 'agent'");if(e.resourceType!=="Agent")throw new Error(`Agent bulk operation returned 'agent' with type '${e.resourceType}'`);let r=t.parameter?.find(o=>o.name==="result")?.resource;if(!r)throw new Error("Agent bulk operation response missing result'");if(!(r.resourceType==="Parameters"||r.resourceType==="OperationOutcome"))throw new Error(`Agent bulk operation returned 'result' with type '${r.resourceType}'`);return{agent:e,result:r}}function aa(t,e){let r={},o=e.required,n=e.optional;for(let s of o){let i=t.parameter?.find(l=>l.name===s);if(!i)throw new Error(`Failed to find parameter '${s}'`);let c;for(let l in i)if(l.startsWith("value")){if(c)throw new Error(`Found multiple values for parameter '${s}'`);c=l}if(!c)throw new Error(`Failed to find a value for parameter '${s}'`);r[s]=i[c]}if(n?.length)for(let s of n){let i=t.parameter?.find(l=>l.name===s);if(!i)continue;let c=ca(s,i);r[s]=c}return r}function ca(t,e){let r;for(let o in e)if(o.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${t}'`);r=o}if(!r)throw new Error(`Failed to find a value for parameter '${t}'`);return e[r]}function la(t,e){if(!Array.isArray(t))throw new Error("Invalid agent IDs array");if(t.length){if(e.criteria)throw new Error("Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive");for(let r of t)if(!(0,se.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:t}}if(e.criteria)return vo(e.criteria),{type:"criteria",criteria:e.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function vo(t){let e="Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`";if(typeof t!="string")throw new Error(e);let[r,o]=t.split("?");if(r!=="Agent"||!o)throw new Error(e);try{new URLSearchParams(o)}catch(n){throw new Error(e,{cause:n})}if(!o.includes("="))throw new Error(e,{cause:new Error("Query string lacks at least one `=`")})}var _=require("@medplum/core"),Po=require("node:child_process"),Co=require("node:http"),To=require("node:os");var Oo=_.MEDPLUM_CLI_CLIENT_ID,xo="http://localhost:9615",Qt=new g("login"),er=new g("whoami"),tr=new g("token");Qt.action(async t=>{let e=t.profile??"default",r=et(e,t),o=await R(t,!1);await ua(o,r)});er.action(async t=>{let e=await R(t);ma(e)});tr.action(async t=>{let e=await R(t);await e.getProfileAsync();let r=e.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function ua(t,e){switch(e?.authType??"authorization-code"){case"authorization-code":await fa(t);break;case"basic":t.setBasicAuth(e.clientId,e.clientSecret);break;case"client-credentials":t.setBasicAuth(e.clientId,e.clientSecret),await t.startClientLogin(e.clientId,e.clientSecret);break;case"jwt-bearer":await yo(t,e);break;case"jwt-assertion":await wo(t,e);break}}async function pa(t){let e=(0,Co.createServer)(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),s=n.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":_.ContentType.TEXT}),o.end("OK");return}if(n.pathname==="/"&&s)try{let i=await t.processCode(s,{clientId:Oo,redirectUri:xo});o.writeHead(200,{"Content-Type":_.ContentType.TEXT}),o.end(`Signed in as ${(0,_.getDisplayString)(i)}. You may close this window.`)}catch(i){o.writeHead(400,{"Content-Type":_.ContentType.TEXT}),o.end(`Error: ${(0,_.normalizeErrorString)(i)}`)}finally{e.close()}else o.writeHead(404,{"Content-Type":_.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function da(t){let e=(0,To.platform)(),r;switch(e){case"openbsd":case"linux":r=`xdg-open '${t}'`;break;case"darwin":r=`open '${t}'`;break;case"win32":r=`cmd /c start "" "${t}"`;break;default:throw new Error("Unsupported platform: "+e)}return new Promise((o,n)=>{(0,Po.exec)(r,(s,i,c)=>{if(s){n(s);return}if(c){n(new Error("Could not open browser: "+c));return}o()})})}function ma(t){let e=t.getActiveLogin();e?(console.log(`Server: ${t.getBaseUrl()}`),console.log(`Profile: ${e.profile.display} (${e.profile.reference})`),console.log(`Project: ${e.project.display} (${e.project.reference})`)):console.log("Not logged in")}async function fa(t){await pa(t);let e=new URL(t.getAuthorizeUrl());e.searchParams.set("client_id",Oo),e.searchParams.set("redirect_uri",xo),e.searchParams.set("scope","openid"),e.searchParams.set("response_type","code"),e.searchParams.set("prompt","login"),await da(e.toString())}var Ne="\x1B[0m",ha="\x1B[1m",ga="\x1B[31m",ya="\x1B[32m",wa="\x1B[33m",Ea="\x1B[34m",ae={red:t=>`${ga}${t}${Ne}`,green:t=>`${ya}${t}${Ne}`,yellow:t=>`${wa}${t}${Ne}`,blue:t=>`${Ea}${t}${Ne}`,bold:t=>`${ha}${t}${Ne}`},rr=t=>t.replace(/\*\*(.*?)\*\*/g,(e,r)=>ae.bold(r));var X=require("@aws-sdk/client-cloudformation"),wt=require("@aws-sdk/client-cloudfront"),bs=require("@aws-sdk/client-ecs"),vs=require("@aws-sdk/client-s3"),we=require("@aws-sdk/client-ssm"),Et=require("@aws-sdk/client-sts"),Ps=require("@medplum/core"),Cs=N(require("node-fetch")),Ts=require("node:fs"),Os=N(Rr());var As=N(require("node:readline")),mt;function ft(){mt=As.default.createInterface({input:process.stdin,output:process.stdout})}function ht(){mt.close()}function a(t){mt.write(t+`
4
+ `),console.table(f.length?f:"No successful responses received"),console.info(),S.length&&(console.info(`${S.length} failed response(s):`),console.info(),console.table(S))}async function bo(t,e,r){if(!(e||r.criteria))throw new Error("This command requires either an [agentId] or a --criteria <criteria> flag");if(e&&r.criteria)throw new Error("Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive");let o;if(e)o=e;else{vo(r.criteria);let n=await t.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!n?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(n.entry.length!==1)throw new Error("Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent");o=n.entry[0].resource?.id}return{reference:`Agent/${o}`}}function sa(t){let e=[];for(let r of t.entry??[]){if(!r.resource)throw new Error("No Parameter resource found in entry");e.push(ia(r.resource))}return e}function ia(t){let e=t.parameter?.find(o=>o.name==="agent")?.resource;if(!e)throw new Error("Agent bulk operation response missing 'agent'");if(e.resourceType!=="Agent")throw new Error(`Agent bulk operation returned 'agent' with type '${e.resourceType}'`);let r=t.parameter?.find(o=>o.name==="result")?.resource;if(!r)throw new Error("Agent bulk operation response missing result'");if(!(r.resourceType==="Parameters"||r.resourceType==="OperationOutcome"))throw new Error(`Agent bulk operation returned 'result' with type '${r.resourceType}'`);return{agent:e,result:r}}function aa(t,e){let r={},o=e.required,n=e.optional;for(let s of o){let i=t.parameter?.find(l=>l.name===s);if(!i)throw new Error(`Failed to find parameter '${s}'`);let c;for(let l in i)if(l.startsWith("value")){if(c)throw new Error(`Found multiple values for parameter '${s}'`);c=l}if(!c)throw new Error(`Failed to find a value for parameter '${s}'`);r[s]=i[c]}if(n?.length)for(let s of n){let i=t.parameter?.find(l=>l.name===s);if(!i)continue;let c=ca(s,i);r[s]=c}return r}function ca(t,e){let r;for(let o in e)if(o.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${t}'`);r=o}if(!r)throw new Error(`Failed to find a value for parameter '${t}'`);return e[r]}function la(t,e){if(!Array.isArray(t))throw new Error("Invalid agent IDs array");if(t.length){if(e.criteria)throw new Error("Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive");for(let r of t)if(!(0,se.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:t}}if(e.criteria)return vo(e.criteria),{type:"criteria",criteria:e.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function vo(t){let e="Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`";if(typeof t!="string")throw new Error(e);let[r,o]=t.split("?");if(r!=="Agent"||!o)throw new Error(e);try{new URLSearchParams(o)}catch(n){throw new Error(e,{cause:n})}if(!o.includes("="))throw new Error(e,{cause:new Error("Query string lacks at least one `=`")})}var _=require("@medplum/core"),Po=require("node:child_process"),Co=require("node:http"),To=require("node:os");var Oo=_.MEDPLUM_CLI_CLIENT_ID,xo="http://localhost:9615",Zt=new g("login"),Qt=new g("whoami"),er=new g("token");Zt.action(async t=>{let e=t.profile??"default",r=et(e,t),o=await R(t,!1);await ua(o,r)});Qt.action(async t=>{let e=await R(t);ma(e)});er.action(async t=>{let e=await R(t);await e.getProfileAsync();let r=e.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function ua(t,e){switch(e?.authType??"authorization-code"){case"authorization-code":await fa(t);break;case"basic":t.setBasicAuth(e.clientId,e.clientSecret);break;case"client-credentials":t.setBasicAuth(e.clientId,e.clientSecret),await t.startClientLogin(e.clientId,e.clientSecret);break;case"jwt-bearer":await yo(t,e);break;case"jwt-assertion":await wo(t,e);break}}async function pa(t){let e=(0,Co.createServer)(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),s=n.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":_.ContentType.TEXT}),o.end("OK");return}if(n.pathname==="/"&&s)try{let i=await t.processCode(s,{clientId:Oo,redirectUri:xo});o.writeHead(200,{"Content-Type":_.ContentType.TEXT}),o.end(`Signed in as ${(0,_.getDisplayString)(i)}. You may close this window.`)}catch(i){o.writeHead(400,{"Content-Type":_.ContentType.TEXT}),o.end(`Error: ${(0,_.normalizeErrorString)(i)}`)}finally{e.close()}else o.writeHead(404,{"Content-Type":_.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function da(t){let e=(0,To.platform)(),r;switch(e){case"openbsd":case"linux":r=`xdg-open '${t}'`;break;case"darwin":r=`open '${t}'`;break;case"win32":r=`cmd /c start "" "${t}"`;break;default:throw new Error("Unsupported platform: "+e)}return new Promise((o,n)=>{(0,Po.exec)(r,(s,i,c)=>{if(s){n(s);return}if(c){n(new Error("Could not open browser: "+c));return}o()})})}function ma(t){let e=t.getActiveLogin();e?(console.log(`Server: ${t.getBaseUrl()}`),console.log(`Profile: ${e.profile.display} (${e.profile.reference})`),console.log(`Project: ${e.project.display} (${e.project.reference})`)):console.log("Not logged in")}async function fa(t){await pa(t);let e=new URL(t.getAuthorizeUrl());e.searchParams.set("client_id",Oo),e.searchParams.set("redirect_uri",xo),e.searchParams.set("scope","openid"),e.searchParams.set("response_type","code"),e.searchParams.set("prompt","login"),await da(e.toString())}var Ne="\x1B[0m",ha="\x1B[1m",ga="\x1B[31m",ya="\x1B[32m",wa="\x1B[33m",Ea="\x1B[34m",ae={red:t=>`${ga}${t}${Ne}`,green:t=>`${ya}${t}${Ne}`,yellow:t=>`${wa}${t}${Ne}`,blue:t=>`${Ea}${t}${Ne}`,bold:t=>`${ha}${t}${Ne}`},tr=t=>t.replace(/\*\*(.*?)\*\*/g,(e,r)=>ae.bold(r));var X=require("@aws-sdk/client-cloudformation"),wt=require("@aws-sdk/client-cloudfront"),bs=require("@aws-sdk/client-ecs"),vs=require("@aws-sdk/client-s3"),we=require("@aws-sdk/client-ssm"),Et=require("@aws-sdk/client-sts"),Ps=require("@medplum/core"),Cs=$(require("node-fetch")),Ts=require("node:fs"),Os=$(Sr());var As=$(require("node:readline")),mt;function ft(){mt=As.default.createInterface({input:process.stdin,output:process.stdout})}function ht(){mt.close()}function a(t){mt.write(t+`
5
5
  `)}function I(t){a(`
6
6
  `+t+`
7
- `)}function x(t,e=""){return new Promise(r=>{mt.question(t+(e?" ("+e+")":"")+" ",o=>{r(o||e.toString())})})}async function gt(t,e,r=""){let o=t+" ["+e.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await x(o)||r;if(e.includes(n))return n;a("Please choose one of the following options: "+e.join(", "))}}async function ye(t,e,r){return parseInt(await gt(t,e.map(o=>o.toString()),r.toString()),10)}async function Q(t){return(await gt(t,["y","n"])).toLowerCase()==="y"}async function Fe(t){if(!await Q(t))throw a("Exiting..."),new Error("User cancelled")}var yt=new X.CloudFormationClient({}),hu=new wt.CloudFrontClient({region:"us-east-1"}),_m=new bs.ECSClient({}),Be=new vs.S3Client({}),gu="medplum:environment";async function Ar(){let t=[],e=(0,X.paginateListStacks)({client:yt},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of e)if(r.StackSummaries)for(let o of r.StackSummaries)t.push(o);return t}async function Ee(t){let e=await Ar();for(let r of e){let o=r.StackName,n=await Ir(o);if(n?.tag===t)return n}}async function Ir(t){let e={};if(await Is(yt,t,e),await yt.config.region()!=="us-east-1")try{await Is(new X.CloudFormationClient({region:"us-east-1"}),t+"-us-east-1",e)}catch{}return e}async function Is(t,e,r){let o=new X.DescribeStacksCommand({StackName:e}),s=(await t.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===gu);if(!i)return;let c=await t.send(new X.DescribeStackResourcesCommand({StackName:e}));if(c.StackResources){t===yt&&(r.stack=s,r.tag=i.Value);for(let l of c.StackResources)yu(l,r)}}function yu(t,e){t.ResourceType==="AWS::ECS::Cluster"?e.ecsCluster=t:t.ResourceType==="AWS::ECS::Service"?e.ecsService=t:t.ResourceType==="AWS::S3::Bucket"&&t.LogicalResourceId?.startsWith("FrontEndAppBucket")?e.appBucket=t:t.ResourceType==="AWS::CloudFront::Distribution"&&t.LogicalResourceId?.startsWith("FrontEndAppDistribution")?e.appDistribution=t:t.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&t.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?e.appOriginAccessIdentity=t:t.ResourceType==="AWS::S3::Bucket"&&t.LogicalResourceId?.startsWith("StorageStorageBucket")?e.storageBucket=t:t.ResourceType==="AWS::CloudFront::Distribution"&&t.LogicalResourceId?.startsWith("StorageStorageDistribution")?e.storageDistribution=t:t.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&t.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(e.storageOriginAccessIdentity=t)}function St(t){console.log(`Medplum Tag: ${t.tag}`),console.log(`Stack Name: ${t.stack?.StackName}`),console.log(`Stack ID: ${t.stack?.StackId}`),console.log(`Status: ${t.stack?.StackStatus}`),console.log(`ECS Cluster: ${t.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${wu(t.ecsService)}`),console.log(`App Bucket: ${t.appBucket?.PhysicalResourceId}`),console.log(`App Distribution: ${t.appDistribution?.PhysicalResourceId}`),console.log(`App OAI: ${t.appOriginAccessIdentity?.PhysicalResourceId}`),console.log(`Storage Bucket: ${t.storageBucket?.PhysicalResourceId}`),console.log(`Storage Distribution: ${t.storageDistribution?.PhysicalResourceId}`),console.log(`Storage OAI: ${t.storageOriginAccessIdentity?.PhysicalResourceId}`)}function wu(t){return t?.PhysicalResourceId?.split("/")?.pop()||""}async function Rt(t){let e=await hu.send(new wt.CreateInvalidationCommand({DistributionId:t,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${e.Invalidation?.Id}`)}async function At(t){let o=(await(await(0,Cs.default)("https://api.github.com/repos/medplum/medplum/releases?per_page=100",{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})).json()).map(n=>n.tag_name.startsWith("v")?n.tag_name.slice(1):n.tag_name);return o.sort((n,s)=>Os.compare(s,n)),t?o.slice(0,o.indexOf(t)):o}async function It(t,e,r){let o=new we.SSMClient({region:t});for(let[n,s]of Object.entries(r)){let i=e+n,c=s.toString(),l=await Eu(o,i);l!==void 0&&l!==c&&(a(`Parameter "${i}" exists with different value.`),await Fe(`Do you want to overwrite "${i}"?`)),await Su(o,i,c)}}async function Eu(t,e){let r=new we.GetParameterCommand({Name:e,WithDecryption:!0});try{return(await t.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Su(t,e,r){let o=new we.PutParameterCommand({Name:e,Value:r,Type:"SecureString",Overwrite:!0});await t.send(o)}function ee(t,e){if(console.log(`Config not found: ${t} (${M(t,e)})`),e){let o=Object.entries(e);if(o.length>0){console.log("Additional options:");for(let[n,s]of o)console.log(` ${n}: ${s}`)}}console.log();let r=(0,Ts.readdirSync)(".",{withFileTypes:!0});if(r=r.filter(o=>o.isFile()&&o.name.startsWith("medplum.")&&o.name.endsWith(".json")).map(o=>o.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let o of r)console.log(` ${o.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${o})`)}}async function Se(t){console.log(`Stack not found: ${t}`),console.log();try{let e=new Et.STSClient,r=new Et.GetCallerIdentityCommand({}),o=await e.send(r),n=await e.config.region();console.log("AWS Region: ",n),console.log("AWS Account ID: ",o.Account),console.log("AWS Account ARN: ",o.Arn),console.log("AWS User ID: ",o.UserId)}catch(e){console.log("Warning: Unable to get AWS account ID",(0,Ps.normalizeErrorString)(e))}}async function xs(t){let e=await Ee(t);if(!e)throw await Se(t),new Error(`Stack not found: ${t}`);St(e)}var le=require("@aws-sdk/client-acm"),bt=require("@aws-sdk/client-cloudfront"),vt=require("@aws-sdk/client-sts"),Ns=require("@medplum/core"),Ke=require("node:crypto"),Ls=require("node:fs");var Ru=t=>`${t}DomainName`,Ds=t=>`${t}SslCertArn`;async function ks(){let t={apiPort:8103,region:"us-east-1"};ft(),I("MEDPLUM"),a("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),a(""),a("Most Medplum infrastructure is deployed using the AWS CDK."),a("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),a("This tool will help you create those resources."),a(""),a("Upon completion, this tool will:"),a(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),a(" 2. Optionally generate an AWS CloudFront signing key"),a(" 3. Optionally request SSL certificates from AWS Certificate Manager"),a(" 4. Optionally write server config settings to AWS Parameter Store"),a(""),a("The Medplum infra config file is an input to the Medplum CDK."),a("The Medplum CDK will create and manage the necessary AWS resources."),a(""),a("We will ask a series of questions to generate your infra config file."),a("Some questions have predefined options in [square brackets]."),a("Some questions have default values in (parentheses), which you can accept by pressing Enter."),a("Press Ctrl+C at any time to exit.");let e=await Au(t.region);e||(a("It appears that you do not have AWS credentials configured."),a("AWS credentials are not strictly required, but will enable some additional features."),a("If you intend to use AWS credentials, please configure them now."),await Fe("Do you want to continue without AWS credentials?")),I("ENVIRONMENT NAME"),a('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),a("The environment name is used in multiple places:"),a(" 1. As part of config file names (i.e., medplum.demo.config.json)"),a(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),a(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),t.name=await x("What is your environment name?","demo"),a('Using environment name "'+t.name+'"...'),I("CONFIG FILE"),a("Medplum Infrastructure will create a config file in the current directory.");let r=await x("What is the config file name?",`medplum.${t.name}.config.json`);(0,Ls.existsSync)(r)&&(a("Config file already exists."),await Fe("Do you want to overwrite the config file?")),a('Using config file "'+r+'"...'),v(r,t),I("AWS REGION"),a("Most Medplum resources will be created in a single AWS region."),t.region=await x("Enter your AWS region:","us-east-1"),v(r,t),I("AWS ACCOUNT NUMBER"),a("Medplum Infrastructure will use your AWS account number to create AWS resources."),e&&a("Using the AWS CLI, your current account ID is: "+e),t.accountNumber=await x("What is your AWS account number?",e),v(r,t),I("STACK NAME"),a("Medplum will create a CloudFormation stack to manage AWS resources."),a("AWS CloudFormation stack names ");let o="Medplum"+t.name.charAt(0).toUpperCase()+t.name.slice(1);for(t.stackName=await x("Enter your CloudFormation stack name?",o),v(r,t),I("BASE DOMAIN NAME"),a("Please enter the base domain name for your Medplum deployment."),a(""),a("Medplum deploys multiple subdomains for various services."),a(""),a('For example, "api." for the REST API and "app." for the web application.'),a("The base domain name is the common suffix for all subdomains."),a(""),a('For example, if your base domain name is "example.com",'),a('then the REST API will be "api.example.com".'),a(""),a('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),a(""),a("Note that you must own the base domain, and it must use Route53 DNS.");!t.domainName;)t.domainName=await x("Enter your base domain name:");v(r,t),I("SUPPORT EMAIL"),a("Medplum sends transactional emails to users."),a("For example, emails to new users or for password reset."),a("Medplum will use the support email address to send these emails."),a("Note that you must verify the support email address in SES.");let n=await x("Enter your support email address:");I("API DOMAIN NAME"),a("Medplum deploys a REST API for the backend services."),t.apiDomainName=await x("Enter your REST API domain name:","api."+t.domainName),t.baseUrl=`https://${t.apiDomainName}/`,v(r,t),I("APP DOMAIN NAME"),a("Medplum deploys a web application for the user interface."),t.appDomainName=await x("Enter your web application domain name:","app."+t.domainName),v(r,t),I("STORAGE DOMAIN NAME"),a("Medplum deploys a storage service for file uploads."),t.storageDomainName=await x("Enter your storage domain name:","storage."+t.domainName),v(r,t),I("STORAGE BUCKET"),a("Medplum uses an S3 bucket to store binary content such as file uploads."),a("Medplum will create a the S3 bucket as part of the CloudFormation stack."),t.storageBucketName=await x("Enter your storage bucket name:",t.storageDomainName),v(r,t),I("MAX AVAILABILITY ZONES"),a("Medplum API servers can be deployed in multiple availability zones."),a("This provides redundancy and high availability."),a("However, it also increases the cost of the deployment."),a("If you want to use all availability zones, choose a large number such as 99."),a("If you want to restrict the number, for example to manage EIP limits,"),a("then choose a small number such as 2 or 3."),t.maxAzs=await ye("Enter the maximum number of availability zones:",[2,3,99],2),I("DATABASE INSTANCES"),a("Medplum uses a relational database to store data."),a("Medplum can create a new RDS database as part of the CloudFormation stack,"),a("or can set up your own database and enter the database name, username, and password."),await Q("Do you want to create a new RDS database as part of the CloudFormation stack?")?(a("Medplum will create a new RDS database as part of the CloudFormation stack."),a(""),a("If you need high availability, you can choose multiple instances."),a("Use 1 for a single instance, or 2 for a primary and a standby."),t.rdsInstances=await ye("Enter the number of database instances:",[1,2],1)):(a("Medplum will not create a new RDS database."),a("Please create a new RDS database and enter the database name, username, and password."),a('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),t.rdsSecretsArn="TODO"),v(r,t),I("SERVER INSTANCES"),a("Medplum uses AWS Fargate to run the API servers."),a("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),a("Fargate will automatically scale the number of servers up and down."),a("If you need high availability, you can choose multiple instances."),t.desiredServerCount=await ye("Enter the number of server instances:",[1,2,3,4,6,8],1),v(r,t),I("SERVER MEMORY"),a("You can choose the amount of memory for each server instance."),a("The default is 512 MB, which is sufficient for getting started."),a("Note that only certain CPU units are compatible with memory units."),a('Consult AWS Fargate "Task Definition Parameters" for more information.'),t.serverMemory=await ye("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),v(r,t),I("SERVER CPU"),a("You can choose the amount of CPU for each server instance."),a("CPU is expressed as an integer using AWS CPU units"),a("The default is 256, which is sufficient for getting started."),a("Note that only certain CPU units are compatible with memory units."),a('Consult AWS Fargate "Task Definition Parameters" for more information.'),t.serverCpu=await ye("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),v(r,t),I("SERVER IMAGE"),a("Medplum uses Docker images for the API servers."),a("You can choose the image to use for the servers."),a("Docker images can be loaded from either Docker Hub or AWS ECR."),a("The default is the latest Medplum release.");let s=(await At())[0]??"latest";t.serverImage=await x("Enter the server image:",`medplum/medplum-server:${s}`),v(r,t),I("SIGNING KEY"),a("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await Pu(t.region,t.stackName+"SigningKey");i?(t.signingKeyId=i.keyId,t.storagePublicKey=i.publicKey,v(r,t)):(a("Unable to generate signing key."),a("Please manually create a signing key and enter the key ID and public key in the config file."),a('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),I("SSL CERTIFICATES"),a("Medplum will now check for existing SSL certificates for the subdomains.");let c=await Iu(t.region);a("Found "+c.length+" certificate(s).");for(let{region:u,certName:h}of[{region:t.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){a("");let f=await bu(t,c,u,h);t[Ds(h)]=f,v(r,t)}I("AWS PARAMETER STORE"),a("Medplum uses AWS Parameter Store to store sensitive configuration values."),a("These values will be encrypted at rest."),a(`The values will be stored in the "/medplum/${t.name}" path.`);let l={port:t.apiPort,baseUrl:t.baseUrl,appBaseUrl:`https://${t.appDomainName}/`,storageBaseUrl:`https://${t.storageDomainName}/binary/`,binaryStorage:`s3:${t.storageBucketName}`,supportEmail:n};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),a(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await Q("Do you want to store these values in AWS Parameter Store?"))await It(t.region,`/medplum/${t.name}/`,l);else{let u=M(t.name,{server:!0});v(u,l),a("Skipping AWS Parameter Store."),a(`Writing values to local config file: ${u}`),a("Please add these values to AWS Parameter Store manually.")}I("DONE!"),a("Medplum configuration complete."),a("You can now proceed to deploying the Medplum infrastructure with CDK."),a("Run:"),a(""),a(` npx cdk bootstrap -c config=${r}`),a(` npx cdk synth -c config=${r}`),t.region==="us-east-1"?a(` npx cdk deploy -c config=${r}`):a(` npx cdk deploy -c config=${r} --all`),a(""),a("See Medplum documentation for more information:"),a(""),a(" https://www.medplum.com/docs/self-hosting/install-on-aws"),a(""),ht()}async function Au(t){try{let e=new vt.STSClient({region:t}),r=new vt.GetCallerIdentityCommand({});return(await e.send(r)).Account}catch(e){console.log("Warning: Unable to get AWS account ID",e.message);return}}async function Iu(t){let e=await $s(t);if(t!=="us-east-1"){let r=await $s("us-east-1");e.push(...r)}return e}async function $s(t){try{let e=new le.ACMClient({region:t}),r=new le.ListCertificatesCommand({MaxItems:1e3});return(await e.send(r)).CertificateSummaryList}catch(e){return console.log("Warning: Unable to list certificates",e.message),[]}}async function bu(t,e,r,o){let n=t[Ru(o)],s=e.find(c=>c.CertificateArn?.includes(r)&&c.DomainName===n);if(s)return a(`Found existing certificate for "${n}" in "${r}.`),s.CertificateArn;if(a(`No existing certificate found for "${n}" in "${r}.`),!await Q("Do you want to request a new certificate?"))return a(`Please add your certificate ARN to the config file in the "${Ds(o)}" setting.`),"TODO";let i=await vu(r,n);return a("Certificate ARN: "+i),i}async function vu(t,e){try{let r=await gt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new le.ACMClient({region:t}),n=new le.RequestCertificateCommand({DomainName:e,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Pu(t,e){let r=(0,Ke.randomUUID)(),o=(0,Ke.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new bt.CloudFrontClient({region:t}).send(new bt.CreatePublicKeyCommand({PublicKeyConfig:{Name:e,CallerReference:(0,Ke.randomUUID)(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",(0,Ns.normalizeErrorString)(n));return}}async function Ms(){let t=await Ar();for(let e of t){let r=e.StackName,o=await Ir(r);o&&(St(o),console.log(""))}}var _s=require("@aws-sdk/client-s3"),U=require("@medplum/core"),Us=N(require("fast-glob")),br=N(require("node-fetch")),k=require("node:fs"),js=require("node:os"),ue=require("node:path"),Fs=require("node:stream/promises");async function Bs(t,e){let r=B(t,e);if(!r)throw ee(t,e),new Error(`Config not found: ${t}`);let o=await Ee(t);if(!o)throw await Se(t),new Error(`Stack not found: ${t}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${t}`);let s;if(e.tarPath)s=e.tarPath;else{let i=e?.toVersion??"latest";s=await Tu("@medplum/app",i)}Ks(s,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await xu(s,n.PhysicalResourceId,e),o.appDistribution?.PhysicalResourceId&&!e.dryrun&&await Rt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Cu(t,e){let r=`https://registry.npmjs.org/${t}/${e}`;return(await(0,br.default)(r)).json()}async function Tu(t,e){let o=(await Cu(t,e)).dist.tarball,n=(0,k.mkdtempSync)((0,ue.join)((0,js.tmpdir)(),"tarball-"));try{let s=await(0,br.default)(o),i=ho(n);return await(0,Fs.pipeline)(s.body,i),(0,ue.join)(n,"package","dist")}catch(s){throw(0,k.rmSync)(n,{recursive:!0,force:!0}),s}}function Ks(t,e){for(let r of(0,k.readdirSync)(t,{withFileTypes:!0})){let o=(0,ue.join)(t,r.name);r.isDirectory()?Ks(o,e):r.isFile()&&o.endsWith(".js")&&Ou(o,e)}}function Ou(t,e){let r=(0,k.readFileSync)(t,"utf-8");for(let[o,n]of Object.entries(e))r=r.replaceAll(`__${o}__`,n);(0,k.writeFileSync)(t,r)}async function xu(t,e,r){let o=[["assets/**/*.css",U.ContentType.CSS,!0],["assets/**/*.css.map",U.ContentType.JSON,!0],["assets/**/*.js",U.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",U.ContentType.JSON,!0],["assets/**/*.txt",U.ContentType.TEXT,!0],["assets/**/*.ico",U.ContentType.FAVICON,!0],["img/**/*.png",U.ContentType.PNG,!0],["img/**/*.svg",U.ContentType.SVG,!0],["robots.txt",U.ContentType.TEXT,!0],["index.html",U.ContentType.HTML,!1]];for(let n of o)await $u({rootDir:t,bucketName:e,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function $u(t){let e=Us.default.sync(t.fileNamePattern,{cwd:t.rootDir});for(let r of e)await Nu((0,ue.join)(t.rootDir,r),t)}async function Nu(t,e){let r=(0,k.createReadStream)(t),o=t.substring(e.rootDir.length+1).split(ue.sep).join("/"),n={Bucket:e.bucketName,Key:o,Body:r,ContentType:e.contentType,CacheControl:e.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${e.bucketName}...`),e.dryrun||await Be.send(new _s.PutObjectCommand(n))}var Pt=require("@aws-sdk/client-s3");async function qs(t,e){if(!B(t,e))throw ee(t,e),new Error(`Config not found: ${t}`);let o=await Ee(t);if(!o)throw await Se(t),new Error(`Stack not found: ${t}`);await Ws("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,e),await Ws("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,e),console.log("Done")}async function Ws(t,e,r,o,n){if(!e?.PhysicalResourceId)throw new Error(`${t} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${t} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${t} OAI not found`);let s=e.PhysicalResourceId,i=o.PhysicalResourceId,c=await Lu(s);if(ku(c,s,i))throw new Error(`${t} bucket already has policy statement`);Mu(c,s,i),console.log(`${t} bucket policy:`),console.log(JSON.stringify(c,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Du(s,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Rt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${t} bucket policy updated`))}async function Lu(t){let e=await Be.send(new Pt.GetBucketPolicyCommand({Bucket:t}));return JSON.parse(e.Policy??"{}")}async function Du(t,e){await Be.send(new Pt.PutBucketPolicyCommand({Bucket:t,Policy:JSON.stringify(e)}))}function ku(t,e,r){return!!t?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${e}`)&&o?.Resource?.includes(`arn:aws:s3:::${e}/*`))}function Mu(t,e,r){t.Version||(t.Version="2012-10-17"),t.Statement||(t.Statement=[]),t.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${e}`,`arn:aws:s3:::${e}/*`]})}async function Hs(t,e){try{ft();let r=B(t,e);if(!r)throw ee(t,e),new Error(`Config not found: ${t}`);let o=fo(t)??{};if(!e.yes&&Object.keys(o).length===0){let n=M(t,{server:!0});if(console.log(ae.yellow(`Config file ${n} not found!`)),!await Q("Do you want to proceed?")){console.log(ae.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}_u(r,o),ju(r,o),a("Medplum uses AWS Parameter Store to store sensitive configuration values."),a("These values will be encrypted at rest."),a(`The values will be stored in the "/medplum/${r.name}" path.`),a(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),e.dryrun?console.log(ae.yellow("Dry run - skipping updates!")):(e.yes||await Q("Do you want to store these values in AWS Parameter Store?"))&&await It(r.region,`/medplum/${r.name}/`,o)}finally{ht()}}function _u(t,e){Ct(t.apiPort,e.port,`Infra "apiPort" (${t.apiPort}) does not match server "port" (${e.port})`),Ct(t.baseUrl,e.baseUrl,`Infra "baseUrl" (${t.baseUrl}) does not match server "baseUrl" (${e.baseUrl})`),Ct(t.appDomainName&&`https://${t.appDomainName}/`,e.appBaseUrl,`Infra "appDomainName" (${t.appDomainName}) does not match server "appBaseUrl" (${e.appBaseUrl})`),Ct(t.storageDomainName&&`https://${t.storageDomainName}/binary/`,e.storageBaseUrl,`Infra "storageDomainName" (${t.storageDomainName}) does not match server "storageBaseUrl" (${e.storageBaseUrl})`)}function Ct(t,e,r){if(Uu(t,e))throw new Error(r)}function Uu(t,e){return t!==void 0&&e!==void 0&&t!==e}function ju(t,e){t.apiPort&&(e.port=t.apiPort),t.baseUrl&&(e.baseUrl=t.baseUrl),t.appDomainName&&(e.appBaseUrl=`https://${t.appDomainName}/`),t.storageDomainName&&(e.storageBaseUrl=`https://${t.storageDomainName}/`)}var Vs=require("node:child_process"),Re=N(Rr());async function Js(t,e){let r=await R(e),o=B(t,e);if(!o)throw console.log(`Configuration file ${M(t)} not found`),ee(t,e),new Error(`Config not found: ${t}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await Fu(r,o),c=await Gs(i);for(;c;){if(e.toVersion&&Re.gt(c,e.toVersion)){console.log(`Skipping update to v${c}`);break}console.log(`Performing update to v${c}`),o.serverImage=`${s}:${c}`,Bu(t,o),await r.startAsyncRequest("/admin/super/migrate"),c=await Gs(c)}}async function Fu(t,e){let r=e.serverImage.lastIndexOf(":"),o=e.serverImage.slice(r+1);if(o==="latest"){o=(await t.get("/healthcheck")).version;let s=o.indexOf("-");s>-1&&(o=o.slice(0,s))}return o}async function Gs(t,e){let r=await At(t),o=r[0];return r.filter(n=>n===o||n===e||Re.gte(n,Re.inc(t,"minor"))).pop()}function Bu(t,e){let r=M(t);v(r,e);let o=`npx cdk deploy -c config=${r}${e.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,Vs.spawnSync)(o,{stdio:"inherit"});if(n.status!==0)throw new Error(`Deploy of ${e.serverImage} failed (exit code ${n.status}): ${n.stderr}`);console.log(n.stdout)}function Xs(){let t=new g("aws").description("Commands to manage AWS resources");return t.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(ks),t.command("list").description("List Medplum AWS CloudFormation stacks").action(Ms),t.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(xs),t.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(rr(`Update the AWS Parameter Store config values.
7
+ `)}function x(t,e=""){return new Promise(r=>{mt.question(t+(e?" ("+e+")":"")+" ",o=>{r(o||e.toString())})})}async function gt(t,e,r=""){let o=t+" ["+e.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await x(o)||r;if(e.includes(n))return n;a("Please choose one of the following options: "+e.join(", "))}}async function ye(t,e,r){return parseInt(await gt(t,e.map(o=>o.toString()),r.toString()),10)}async function Q(t){return(await gt(t,["y","n"])).toLowerCase()==="y"}async function Fe(t){if(!await Q(t))throw a("Exiting..."),new Error("User cancelled")}var yt=new X.CloudFormationClient({}),hu=new wt.CloudFrontClient({region:"us-east-1"}),jm=new bs.ECSClient({}),Be=new vs.S3Client({}),gu="medplum:environment";async function Rr(){let t=[],e=(0,X.paginateListStacks)({client:yt},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of e)if(r.StackSummaries)for(let o of r.StackSummaries)t.push(o);return t}async function Ee(t){let e=await Rr();for(let r of e){let o=r.StackName,n=await Ar(o);if(n?.tag===t)return n}}async function Ar(t){let e={};if(await Is(yt,t,e),await yt.config.region()!=="us-east-1")try{await Is(new X.CloudFormationClient({region:"us-east-1"}),t+"-us-east-1",e)}catch{}return e}async function Is(t,e,r){let o=new X.DescribeStacksCommand({StackName:e}),s=(await t.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===gu);if(!i)return;let c=await t.send(new X.DescribeStackResourcesCommand({StackName:e}));if(c.StackResources){t===yt&&(r.stack=s,r.tag=i.Value);for(let l of c.StackResources)yu(l,r)}}function yu(t,e){t.ResourceType==="AWS::ECS::Cluster"?e.ecsCluster=t:t.ResourceType==="AWS::ECS::Service"?e.ecsService=t:t.ResourceType==="AWS::S3::Bucket"&&t.LogicalResourceId?.startsWith("FrontEndAppBucket")?e.appBucket=t:t.ResourceType==="AWS::CloudFront::Distribution"&&t.LogicalResourceId?.startsWith("FrontEndAppDistribution")?e.appDistribution=t:t.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&t.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?e.appOriginAccessIdentity=t:t.ResourceType==="AWS::S3::Bucket"&&t.LogicalResourceId?.startsWith("StorageStorageBucket")?e.storageBucket=t:t.ResourceType==="AWS::CloudFront::Distribution"&&t.LogicalResourceId?.startsWith("StorageStorageDistribution")?e.storageDistribution=t:t.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&t.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(e.storageOriginAccessIdentity=t)}function St(t){console.log(`Medplum Tag: ${t.tag}`),console.log(`Stack Name: ${t.stack?.StackName}`),console.log(`Stack ID: ${t.stack?.StackId}`),console.log(`Status: ${t.stack?.StackStatus}`),console.log(`ECS Cluster: ${t.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${wu(t.ecsService)}`),console.log(`App Bucket: ${t.appBucket?.PhysicalResourceId}`),console.log(`App Distribution: ${t.appDistribution?.PhysicalResourceId}`),console.log(`App OAI: ${t.appOriginAccessIdentity?.PhysicalResourceId}`),console.log(`Storage Bucket: ${t.storageBucket?.PhysicalResourceId}`),console.log(`Storage Distribution: ${t.storageDistribution?.PhysicalResourceId}`),console.log(`Storage OAI: ${t.storageOriginAccessIdentity?.PhysicalResourceId}`)}function wu(t){return t?.PhysicalResourceId?.split("/")?.pop()||""}async function Rt(t){let e=await hu.send(new wt.CreateInvalidationCommand({DistributionId:t,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${e.Invalidation?.Id}`)}async function At(t){let o=(await(await(0,Cs.default)("https://api.github.com/repos/medplum/medplum/releases?per_page=100",{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})).json()).map(n=>n.tag_name.startsWith("v")?n.tag_name.slice(1):n.tag_name);return o.sort((n,s)=>Os.compare(s,n)),t?o.slice(0,o.indexOf(t)):o}async function It(t,e,r){let o=new we.SSMClient({region:t});for(let[n,s]of Object.entries(r)){let i=e+n,c=s.toString(),l=await Eu(o,i);l!==void 0&&l!==c&&(a(`Parameter "${i}" exists with different value.`),await Fe(`Do you want to overwrite "${i}"?`)),await Su(o,i,c)}}async function Eu(t,e){let r=new we.GetParameterCommand({Name:e,WithDecryption:!0});try{return(await t.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Su(t,e,r){let o=new we.PutParameterCommand({Name:e,Value:r,Type:"SecureString",Overwrite:!0});await t.send(o)}function ee(t,e){if(console.log(`Config not found: ${t} (${M(t,e)})`),e){let o=Object.entries(e);if(o.length>0){console.log("Additional options:");for(let[n,s]of o)console.log(` ${n}: ${s}`)}}console.log();let r=(0,Ts.readdirSync)(".",{withFileTypes:!0});if(r=r.filter(o=>o.isFile()&&o.name.startsWith("medplum.")&&o.name.endsWith(".json")).map(o=>o.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let o of r)console.log(` ${o.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${o})`)}}async function Se(t){console.log(`Stack not found: ${t}`),console.log();try{let e=new Et.STSClient,r=new Et.GetCallerIdentityCommand({}),o=await e.send(r),n=await e.config.region();console.log("AWS Region: ",n),console.log("AWS Account ID: ",o.Account),console.log("AWS Account ARN: ",o.Arn),console.log("AWS User ID: ",o.UserId)}catch(e){console.log("Warning: Unable to get AWS account ID",(0,Ps.normalizeErrorString)(e))}}async function xs(t){let e=await Ee(t);if(!e)throw await Se(t),new Error(`Stack not found: ${t}`);St(e)}var le=require("@aws-sdk/client-acm"),bt=require("@aws-sdk/client-cloudfront"),vt=require("@aws-sdk/client-sts"),Ns=require("@medplum/core"),We=require("node:crypto"),Ls=require("node:fs");var Ru=t=>`${t}DomainName`,Ds=t=>`${t}SslCertArn`;async function ks(){let t={apiPort:8103,region:"us-east-1"};ft(),I("MEDPLUM"),a("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),a(""),a("Most Medplum infrastructure is deployed using the AWS CDK."),a("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),a("This tool will help you create those resources."),a(""),a("Upon completion, this tool will:"),a(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),a(" 2. Optionally generate an AWS CloudFront signing key"),a(" 3. Optionally request SSL certificates from AWS Certificate Manager"),a(" 4. Optionally write server config settings to AWS Parameter Store"),a(""),a("The Medplum infra config file is an input to the Medplum CDK."),a("The Medplum CDK will create and manage the necessary AWS resources."),a(""),a("We will ask a series of questions to generate your infra config file."),a("Some questions have predefined options in [square brackets]."),a("Some questions have default values in (parentheses), which you can accept by pressing Enter."),a("Press Ctrl+C at any time to exit.");let e=await Au(t.region);e||(a("It appears that you do not have AWS credentials configured."),a("AWS credentials are not strictly required, but will enable some additional features."),a("If you intend to use AWS credentials, please configure them now."),await Fe("Do you want to continue without AWS credentials?")),I("ENVIRONMENT NAME"),a('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),a("The environment name is used in multiple places:"),a(" 1. As part of config file names (i.e., medplum.demo.config.json)"),a(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),a(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),t.name=await x("What is your environment name?","demo"),a('Using environment name "'+t.name+'"...'),I("CONFIG FILE"),a("Medplum Infrastructure will create a config file in the current directory.");let r=await x("What is the config file name?",`medplum.${t.name}.config.json`);(0,Ls.existsSync)(r)&&(a("Config file already exists."),await Fe("Do you want to overwrite the config file?")),a('Using config file "'+r+'"...'),v(r,t),I("AWS REGION"),a("Most Medplum resources will be created in a single AWS region."),t.region=await x("Enter your AWS region:","us-east-1"),v(r,t),I("AWS ACCOUNT NUMBER"),a("Medplum Infrastructure will use your AWS account number to create AWS resources."),e&&a("Using the AWS CLI, your current account ID is: "+e),t.accountNumber=await x("What is your AWS account number?",e),v(r,t),I("STACK NAME"),a("Medplum will create a CloudFormation stack to manage AWS resources."),a("AWS CloudFormation stack names ");let o="Medplum"+t.name.charAt(0).toUpperCase()+t.name.slice(1);for(t.stackName=await x("Enter your CloudFormation stack name?",o),v(r,t),I("BASE DOMAIN NAME"),a("Please enter the base domain name for your Medplum deployment."),a(""),a("Medplum deploys multiple subdomains for various services."),a(""),a('For example, "api." for the REST API and "app." for the web application.'),a("The base domain name is the common suffix for all subdomains."),a(""),a('For example, if your base domain name is "example.com",'),a('then the REST API will be "api.example.com".'),a(""),a('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),a(""),a("Note that you must own the base domain, and it must use Route53 DNS.");!t.domainName;)t.domainName=await x("Enter your base domain name:");v(r,t),I("SUPPORT EMAIL"),a("Medplum sends transactional emails to users."),a("For example, emails to new users or for password reset."),a("Medplum will use the support email address to send these emails."),a("Note that you must verify the support email address in SES.");let n=await x("Enter your support email address:");I("API DOMAIN NAME"),a("Medplum deploys a REST API for the backend services."),t.apiDomainName=await x("Enter your REST API domain name:","api."+t.domainName),t.baseUrl=`https://${t.apiDomainName}/`,v(r,t),I("APP DOMAIN NAME"),a("Medplum deploys a web application for the user interface."),t.appDomainName=await x("Enter your web application domain name:","app."+t.domainName),v(r,t),I("STORAGE DOMAIN NAME"),a("Medplum deploys a storage service for file uploads."),t.storageDomainName=await x("Enter your storage domain name:","storage."+t.domainName),v(r,t),I("STORAGE BUCKET"),a("Medplum uses an S3 bucket to store binary content such as file uploads."),a("Medplum will create a the S3 bucket as part of the CloudFormation stack."),t.storageBucketName=await x("Enter your storage bucket name:",t.storageDomainName),v(r,t),I("MAX AVAILABILITY ZONES"),a("Medplum API servers can be deployed in multiple availability zones."),a("This provides redundancy and high availability."),a("However, it also increases the cost of the deployment."),a("If you want to use all availability zones, choose a large number such as 99."),a("If you want to restrict the number, for example to manage EIP limits,"),a("then choose a small number such as 2 or 3."),t.maxAzs=await ye("Enter the maximum number of availability zones:",[2,3,99],2),I("DATABASE INSTANCES"),a("Medplum uses a relational database to store data."),a("Medplum can create a new RDS database as part of the CloudFormation stack,"),a("or can set up your own database and enter the database name, username, and password."),await Q("Do you want to create a new RDS database as part of the CloudFormation stack?")?(a("Medplum will create a new RDS database as part of the CloudFormation stack."),a(""),a("If you need high availability, you can choose multiple instances."),a("Use 1 for a single instance, or 2 for a primary and a standby."),t.rdsInstances=await ye("Enter the number of database instances:",[1,2],1)):(a("Medplum will not create a new RDS database."),a("Please create a new RDS database and enter the database name, username, and password."),a('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),t.rdsSecretsArn="TODO"),v(r,t),I("SERVER INSTANCES"),a("Medplum uses AWS Fargate to run the API servers."),a("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),a("Fargate will automatically scale the number of servers up and down."),a("If you need high availability, you can choose multiple instances."),t.desiredServerCount=await ye("Enter the number of server instances:",[1,2,3,4,6,8],1),v(r,t),I("SERVER MEMORY"),a("You can choose the amount of memory for each server instance."),a("The default is 512 MB, which is sufficient for getting started."),a("Note that only certain CPU units are compatible with memory units."),a('Consult AWS Fargate "Task Definition Parameters" for more information.'),t.serverMemory=await ye("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),v(r,t),I("SERVER CPU"),a("You can choose the amount of CPU for each server instance."),a("CPU is expressed as an integer using AWS CPU units"),a("The default is 256, which is sufficient for getting started."),a("Note that only certain CPU units are compatible with memory units."),a('Consult AWS Fargate "Task Definition Parameters" for more information.'),t.serverCpu=await ye("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),v(r,t),I("SERVER IMAGE"),a("Medplum uses Docker images for the API servers."),a("You can choose the image to use for the servers."),a("Docker images can be loaded from either Docker Hub or AWS ECR."),a("The default is the latest Medplum release.");let s=(await At())[0]??"latest";t.serverImage=await x("Enter the server image:",`medplum/medplum-server:${s}`),v(r,t),I("SIGNING KEY"),a("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await Pu(t.region,t.stackName+"SigningKey");i?(t.signingKeyId=i.keyId,t.storagePublicKey=i.publicKey,v(r,t)):(a("Unable to generate signing key."),a("Please manually create a signing key and enter the key ID and public key in the config file."),a('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),I("SSL CERTIFICATES"),a("Medplum will now check for existing SSL certificates for the subdomains.");let c=await Iu(t.region);a("Found "+c.length+" certificate(s).");for(let{region:u,certName:h}of[{region:t.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){a("");let f=await bu(t,c,u,h);t[Ds(h)]=f,v(r,t)}I("AWS PARAMETER STORE"),a("Medplum uses AWS Parameter Store to store sensitive configuration values."),a("These values will be encrypted at rest."),a(`The values will be stored in the "/medplum/${t.name}" path.`);let l={port:t.apiPort,baseUrl:t.baseUrl,appBaseUrl:`https://${t.appDomainName}/`,storageBaseUrl:`https://${t.storageDomainName}/binary/`,binaryStorage:`s3:${t.storageBucketName}`,supportEmail:n};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),a(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await Q("Do you want to store these values in AWS Parameter Store?"))await It(t.region,`/medplum/${t.name}/`,l);else{let u=M(t.name,{server:!0});v(u,l),a("Skipping AWS Parameter Store."),a(`Writing values to local config file: ${u}`),a("Please add these values to AWS Parameter Store manually.")}I("DONE!"),a("Medplum configuration complete."),a("You can now proceed to deploying the Medplum infrastructure with CDK."),a("Run:"),a(""),a(` npx cdk bootstrap -c config=${r}`),a(` npx cdk synth -c config=${r}`),t.region==="us-east-1"?a(` npx cdk deploy -c config=${r}`):a(` npx cdk deploy -c config=${r} --all`),a(""),a("See Medplum documentation for more information:"),a(""),a(" https://www.medplum.com/docs/self-hosting/install-on-aws"),a(""),ht()}async function Au(t){try{let e=new vt.STSClient({region:t}),r=new vt.GetCallerIdentityCommand({});return(await e.send(r)).Account}catch(e){console.log("Warning: Unable to get AWS account ID",e.message);return}}async function Iu(t){let e=await $s(t);if(t!=="us-east-1"){let r=await $s("us-east-1");e.push(...r)}return e}async function $s(t){try{let e=new le.ACMClient({region:t}),r=new le.ListCertificatesCommand({MaxItems:1e3});return(await e.send(r)).CertificateSummaryList}catch(e){return console.log("Warning: Unable to list certificates",e.message),[]}}async function bu(t,e,r,o){let n=t[Ru(o)],s=e.find(c=>c.CertificateArn?.includes(r)&&c.DomainName===n);if(s)return a(`Found existing certificate for "${n}" in "${r}.`),s.CertificateArn;if(a(`No existing certificate found for "${n}" in "${r}.`),!await Q("Do you want to request a new certificate?"))return a(`Please add your certificate ARN to the config file in the "${Ds(o)}" setting.`),"TODO";let i=await vu(r,n);return a("Certificate ARN: "+i),i}async function vu(t,e){try{let r=await gt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new le.ACMClient({region:t}),n=new le.RequestCertificateCommand({DomainName:e,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Pu(t,e){let r=(0,We.randomUUID)(),o=(0,We.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new bt.CloudFrontClient({region:t}).send(new bt.CreatePublicKeyCommand({PublicKeyConfig:{Name:e,CallerReference:(0,We.randomUUID)(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",(0,Ns.normalizeErrorString)(n));return}}async function Ms(){let t=await Rr();for(let e of t){let r=e.StackName,o=await Ar(r);o&&(St(o),console.log(""))}}var _s=require("@aws-sdk/client-s3"),U=require("@medplum/core"),Us=$(require("fast-glob")),Ir=$(require("node-fetch")),k=require("node:fs"),js=require("node:os"),ue=require("node:path"),Fs=require("node:stream/promises");async function Bs(t,e){let r=B(t,e);if(!r)throw ee(t,e),new Error(`Config not found: ${t}`);let o=await Ee(t);if(!o)throw await Se(t),new Error(`Stack not found: ${t}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${t}`);let s;if(e.tarPath)s=e.tarPath;else{let i=e?.toVersion??"latest";s=await Tu("@medplum/app",i)}Ws(s,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await xu(s,n.PhysicalResourceId,e),o.appDistribution?.PhysicalResourceId&&!e.dryrun&&await Rt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Cu(t,e){let r=`https://registry.npmjs.org/${t}/${e}`;return(await(0,Ir.default)(r)).json()}async function Tu(t,e){let o=(await Cu(t,e)).dist.tarball,n=(0,k.mkdtempSync)((0,ue.join)((0,js.tmpdir)(),"tarball-"));try{let s=await(0,Ir.default)(o),i=ho(n);return await(0,Fs.pipeline)(s.body,i),(0,ue.join)(n,"package","dist")}catch(s){throw(0,k.rmSync)(n,{recursive:!0,force:!0}),s}}function Ws(t,e){for(let r of(0,k.readdirSync)(t,{withFileTypes:!0})){let o=(0,ue.join)(t,r.name);r.isDirectory()?Ws(o,e):r.isFile()&&o.endsWith(".js")&&Ou(o,e)}}function Ou(t,e){let r=(0,k.readFileSync)(t,"utf-8");for(let[o,n]of Object.entries(e))r=r.replaceAll(`__${o}__`,n);(0,k.writeFileSync)(t,r)}async function xu(t,e,r){let o=[["assets/**/*.css",U.ContentType.CSS,!0],["assets/**/*.css.map",U.ContentType.JSON,!0],["assets/**/*.js",U.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",U.ContentType.JSON,!0],["assets/**/*.txt",U.ContentType.TEXT,!0],["assets/**/*.ico",U.ContentType.FAVICON,!0],["img/**/*.png",U.ContentType.PNG,!0],["img/**/*.svg",U.ContentType.SVG,!0],["robots.txt",U.ContentType.TEXT,!0],["index.html",U.ContentType.HTML,!1]];for(let n of o)await $u({rootDir:t,bucketName:e,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function $u(t){let e=Us.default.sync(t.fileNamePattern,{cwd:t.rootDir});for(let r of e)await Nu((0,ue.join)(t.rootDir,r),t)}async function Nu(t,e){let r=(0,k.createReadStream)(t),o=t.substring(e.rootDir.length+1).split(ue.sep).join("/"),n={Bucket:e.bucketName,Key:o,Body:r,ContentType:e.contentType,CacheControl:e.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${e.bucketName}...`),e.dryrun||await Be.send(new _s.PutObjectCommand(n))}var Pt=require("@aws-sdk/client-s3");async function qs(t,e){if(!B(t,e))throw ee(t,e),new Error(`Config not found: ${t}`);let o=await Ee(t);if(!o)throw await Se(t),new Error(`Stack not found: ${t}`);await Ks("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,e),await Ks("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,e),console.log("Done")}async function Ks(t,e,r,o,n){if(!e?.PhysicalResourceId)throw new Error(`${t} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${t} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${t} OAI not found`);let s=e.PhysicalResourceId,i=o.PhysicalResourceId,c=await Lu(s);if(ku(c,s,i))throw new Error(`${t} bucket already has policy statement`);Mu(c,s,i),console.log(`${t} bucket policy:`),console.log(JSON.stringify(c,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Du(s,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Rt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${t} bucket policy updated`))}async function Lu(t){let e=await Be.send(new Pt.GetBucketPolicyCommand({Bucket:t}));return JSON.parse(e.Policy??"{}")}async function Du(t,e){await Be.send(new Pt.PutBucketPolicyCommand({Bucket:t,Policy:JSON.stringify(e)}))}function ku(t,e,r){return!!t?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${e}`)&&o?.Resource?.includes(`arn:aws:s3:::${e}/*`))}function Mu(t,e,r){t.Version||(t.Version="2012-10-17"),t.Statement||(t.Statement=[]),t.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${e}`,`arn:aws:s3:::${e}/*`]})}async function Hs(t,e){try{ft();let r=B(t,e);if(!r)throw ee(t,e),new Error(`Config not found: ${t}`);let o=fo(t)??{};if(!e.yes&&Object.keys(o).length===0){let n=M(t,{server:!0});if(console.log(ae.yellow(`Config file ${n} not found!`)),!await Q("Do you want to proceed?")){console.log(ae.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}_u(r,o),ju(r,o),a("Medplum uses AWS Parameter Store to store sensitive configuration values."),a("These values will be encrypted at rest."),a(`The values will be stored in the "/medplum/${r.name}" path.`),a(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),e.dryrun?console.log(ae.yellow("Dry run - skipping updates!")):(e.yes||await Q("Do you want to store these values in AWS Parameter Store?"))&&await It(r.region,`/medplum/${r.name}/`,o)}finally{ht()}}function _u(t,e){Ct(t.apiPort,e.port,`Infra "apiPort" (${t.apiPort}) does not match server "port" (${e.port})`),Ct(t.baseUrl,e.baseUrl,`Infra "baseUrl" (${t.baseUrl}) does not match server "baseUrl" (${e.baseUrl})`),Ct(t.appDomainName&&`https://${t.appDomainName}/`,e.appBaseUrl,`Infra "appDomainName" (${t.appDomainName}) does not match server "appBaseUrl" (${e.appBaseUrl})`),Ct(t.storageDomainName&&`https://${t.storageDomainName}/binary/`,e.storageBaseUrl,`Infra "storageDomainName" (${t.storageDomainName}) does not match server "storageBaseUrl" (${e.storageBaseUrl})`)}function Ct(t,e,r){if(Uu(t,e))throw new Error(r)}function Uu(t,e){return t!==void 0&&e!==void 0&&t!==e}function ju(t,e){t.apiPort&&(e.port=t.apiPort),t.baseUrl&&(e.baseUrl=t.baseUrl),t.appDomainName&&(e.appBaseUrl=`https://${t.appDomainName}/`),t.storageDomainName&&(e.storageBaseUrl=`https://${t.storageDomainName}/`)}var Vs=require("node:child_process"),Re=$(Sr());async function Js(t,e){let r=await R(e),o=B(t,e);if(!o)throw console.log(`Configuration file ${M(t)} not found`),ee(t,e),new Error(`Config not found: ${t}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await Fu(r,o),c=await Gs(i);for(;c;){if(e.toVersion&&Re.gt(c,e.toVersion)){console.log(`Skipping update to v${c}`);break}console.log(`Performing update to v${c}`),o.serverImage=`${s}:${c}`,Bu(t,o),await r.startAsyncRequest("/admin/super/migrate"),c=await Gs(c)}}async function Fu(t,e){let r=e.serverImage.lastIndexOf(":"),o=e.serverImage.slice(r+1);if(o==="latest"){o=(await t.get("/healthcheck")).version;let s=o.indexOf("-");s>-1&&(o=o.slice(0,s))}return o}async function Gs(t,e){let r=await At(t),o=r[0];return r.filter(n=>n===o||n===e||Re.gte(n,Re.inc(t,"minor"))).pop()}function Bu(t,e){let r=M(t);v(r,e);let o=`npx cdk deploy -c config=${r}${e.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,Vs.spawnSync)(o,{stdio:"inherit"});if(n.status!==0)throw new Error(`Deploy of ${e.serverImage} failed (exit code ${n.status}): ${n.stderr}`);console.log(n.stdout)}function Xs(){let t=new g("aws").description("Commands to manage AWS resources");return t.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(ks),t.command("list").description("List Medplum AWS CloudFormation stacks").action(Ms),t.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(xs),t.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(tr(`Update the AWS Parameter Store config values.
8
8
 
9
9
  Configuration values come from a file named **medplum.<tag>.config.server.json** where **<tag>** is the Medplum stack tag.
10
10
 
11
- `+ae.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",rr("File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.")).option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--yes","Automatically confirm the update").action(Hs),y(t,new g("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(Js)),t.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--tar-path [tarPath]","Specifies the path to the extracted tarball of the @medplum/app package.").action(Bs),t.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(qs),t}var zs=new g("save"),Ys=new g("deploy"),Zs=new g("create"),We=new g("bot");y(We,zs);y(We,Ys);y(We,Zs);var vr=new g("save-bot"),Pr=new g("deploy-bot"),Cr=new g("create-bot");zs.description("Saving the bot").argument("<botName>").action(async(t,e)=>{let r=await R(e);await Tt(r,t)});Ys.description("Deploy the app to AWS").argument("<botName>").action(async(t,e)=>{let r=await R(e);await Tt(r,t,!0)});Zs.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(t,e,r,o,n)=>{let s=await R(n);await zt(s,t,e,r,o,n.runtimeVersion,!!n.writeConfig)});async function Tt(t,e,r=!1){let o=mo(e),n=[],s=[],i=0,c=0;for(let l of o)try{let u=await t.readResource("Bot",l.id);await Jt(t,l,u),i++,r&&(await Xt(t,l,u),c++)}catch(u){n.push(u),s.push(`${l.name} [${l.id}]`)}if(console.log(`Number of bots saved: ${i}`),console.log(`Number of bots deployed: ${c}`),console.log(`Number of errors: ${n.length}`),n.length)throw new Error(`${n.length} bot(s) had failures. Bots with failures:
11
+ `+ae.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",tr("File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.")).option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--yes","Automatically confirm the update").action(Hs),y(t,new g("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(Js)),t.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--tar-path [tarPath]","Specifies the path to the extracted tarball of the @medplum/app package.").action(Bs),t.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(qs),t}var zs=new g("save"),Ys=new g("deploy"),Zs=new g("create"),Ke=new g("bot");y(Ke,zs);y(Ke,Ys);y(Ke,Zs);var br=new g("save-bot"),vr=new g("deploy-bot"),Pr=new g("create-bot");zs.description("Saving the bot").argument("<botName>").action(async(t,e)=>{let r=await R(e);await Tt(r,t)});Ys.description("Deploy the app to AWS").argument("<botName>").action(async(t,e)=>{let r=await R(e);await Tt(r,t,!0)});Zs.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(t,e,r,o,n)=>{let s=await R(n);await Xt(s,t,e,r,o,n.runtimeVersion,!!n.writeConfig)});async function Tt(t,e,r=!1){let o=mo(e),n=[],s=[],i=0,c=0;for(let l of o)try{let u=await t.readResource("Bot",l.id);await Vt(t,l,u),i++,r&&(await Jt(t,l,u),c++)}catch(u){n.push(u),s.push(`${l.name} [${l.id}]`)}if(console.log(`Number of bots saved: ${i}`),console.log(`Number of bots deployed: ${c}`),console.log(`Number of errors: ${n.length}`),n.length)throw new Error(`${n.length} bot(s) had failures. Bots with failures:
12
12
 
13
13
  ${s.join(`
14
- `)}`,{cause:n})}vr.description("Saves the bot").argument("<botName>").action(async(t,e)=>{let r=await R(e);await Tt(r,t)});Pr.description("Deploy the bot to AWS").argument("<botName>").action(async(t,e)=>{let r=await R(e);await Tt(r,t,!0)});Cr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(t,e,r,o,n)=>{let s=await R(n);await zt(s,t,e,r,o)});var Ot=require("node:fs"),Tr=require("node:path"),ei=require("node:readline");var ti=new g("export"),ri=new g("import"),xt=new g("bulk");y(xt,ti);y(xt,ri);ti.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async t=>{let{exportLevel:e,types:r,since:o,targetDirectory:n}=t,s=await R(t);(await s.bulkExport(e,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:c,url:l})=>{let u=new URL(l),h=await s.download(l),f=`${c}_${u.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",S=(0,Tr.resolve)(n??"",f);(0,Ot.writeFile)(`${S}`,await h.text(),()=>{console.log(`${S} is created`)})})});ri.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(t,e)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=e,s=(0,Tr.resolve)(n??process.cwd(),t),i=await R(e);await Ku(s,Number.parseInt(r,10),i,o)});async function Ku(t,e,r,o){let n=[],s=(0,Ot.createReadStream)(t),i=(0,ei.createInterface)({input:s});for await(let c of i){let l=Wu(c,o);n.push({resource:l,request:{method:"POST",url:l.resourceType}}),n.length%e===0&&(await Qs(n,r),n=[])}n.length>0&&await Qs(n,r)}async function Qs(t,e){(await e.executeBatch({resourceType:"Bundle",type:"transaction",entry:t})).entry?.forEach(o=>{J(o.response)})}function Wu(t,e){let r=JSON.parse(t);return e?qu(r):r}function qu(t){return t.resourceType==="ExplanationOfBenefit"?Hu(t):t}function Hu(t){return t.provider||(t.provider=Yt()),t.item?.forEach(e=>{e?.productOrService||(e.productOrService=Yt())}),t}var Lt=require("@medplum/core");var ni=require("node:net"),si=require("@medplum/core"),Nt=require("iconv-lite"),li=N(require("node:net"),1),oi=class extends EventTarget{addEventListener(t,e,r){super.addEventListener(t,e,r)}removeEventListener(t,e,r){super.removeEventListener(t,e,r)}};var Gu=class extends Event{constructor(t,e){super("message"),this.connection=t,this.message=e}},$t=class extends Event{constructor(t){super("error"),this.error=t}},ii=class extends Event{constructor(){super("close")}},ai=class extends oi{constructor(t,e="utf-8"){super(),this.socket=t,this.encoding=e,this.chunks=[],this.messageQueue=[],t.on("data",r=>{try{if(this.appendData(r),r.at(-2)===28&&r.at(-1)===13){let o=Buffer.concat(this.chunks),n=o.subarray(1,o.length-2),s=(0,Nt.decode)(n,this.encoding),i=si.Hl7Message.parse(s);this.dispatchEvent(new Gu(this,i)),this.resetBuffer()}}catch(o){this.dispatchEvent(new $t(o))}}),t.on("error",r=>{this.resetBuffer(),this.dispatchEvent(new $t(r))}),t.on("end",()=>{this.close()}),this.addEventListener("message",r=>{let o=this.messageQueue.shift();if(!o){this.dispatchEvent(new $t(new Error(`Received a message when no pending messages were in the queue. Message: ${r.message}`)));return}o.resolve?.(r.message)})}sendImpl(t,e){this.messageQueue.push(e);let r=t.toString(),o=(0,Nt.encode)(r,this.encoding),n=Buffer.alloc(o.length+3);n.writeInt8(11,0),o.copy(n,1),n.writeInt8(28,o.length+1),n.writeInt8(13,o.length+2),this.socket.write(n)}send(t){this.sendImpl(t,{message:t})}async sendAndWait(t){return new Promise((e,r)=>{let o={message:t,resolve:e,reject:r};this.sendImpl(t,o)})}close(){this.socket.end(),this.socket.destroy(),this.dispatchEvent(new ii)}appendData(t){this.chunks.push(t)}resetBuffer(){this.chunks=[]}},ci=class extends oi{constructor(t){super(),this.options=t,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding,this.keepAlive=this.options.keepAlive??!1}connect(){return this.connection?Promise.resolve(this.connection):new Promise((t,e)=>{let r=(0,ni.connect)({host:this.host,port:this.port,keepAlive:this.keepAlive},()=>{let o;this.connection=o=new ai(r,this.encoding),r.off("error",e),o.addEventListener("close",()=>this.dispatchEvent(new ii)),o.addEventListener("error",n=>this.dispatchEvent(new $t(n.error))),t(this.connection)});r.on("error",e)})}async send(t){return(await this.connect()).send(t)}async sendAndWait(t){return(await this.connect()).sendAndWait(t)}close(){this.connection&&(this.connection.close(),delete this.connection)}},ui=class{constructor(t){this.handler=t}start(t,e){let r=li.default.createServer(o=>{let n=new ai(o,e);this.handler(n)});r.listen(t),this.server=r}async stop(){return new Promise((t,e)=>{if(!this.server){e(new Error("Stop was called but there is no server running"));return}this.server.close(r=>{if(r){e(r);return}t()}),this.server=void 0})}};var pi=require("node:fs");var Vu=new g("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(t,e,r,o)=>{if(o.generateExample?r=Xu():o.file&&(r=(0,pi.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new ci({host:t,port:Number.parseInt(e,10),encoding:o.encoding});try{let s=await n.sendAndWait(Lt.Hl7Message.parse(r));console.log(s.toString().replaceAll("\r",`
14
+ `)}`,{cause:n})}br.description("Saves the bot").argument("<botName>").action(async(t,e)=>{let r=await R(e);await Tt(r,t)});vr.description("Deploy the bot to AWS").argument("<botName>").action(async(t,e)=>{let r=await R(e);await Tt(r,t,!0)});Pr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(t,e,r,o,n)=>{let s=await R(n);await Xt(s,t,e,r,o)});var Ot=require("node:fs"),Cr=require("node:path"),ei=require("node:readline");var ti=new g("export"),ri=new g("import"),xt=new g("bulk");y(xt,ti);y(xt,ri);ti.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async t=>{let{exportLevel:e,types:r,since:o,targetDirectory:n}=t,s=await R(t);(await s.bulkExport(e,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:c,url:l})=>{let u=new URL(l),h=await s.download(l),f=`${c}_${u.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",S=(0,Cr.resolve)(n??"",f);(0,Ot.writeFile)(`${S}`,await h.text(),()=>{console.log(`${S} is created`)})})});ri.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(t,e)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=e,s=(0,Cr.resolve)(n??process.cwd(),t),i=await R(e);await Wu(s,Number.parseInt(r,10),i,o)});async function Wu(t,e,r,o){let n=[],s=(0,Ot.createReadStream)(t),i=(0,ei.createInterface)({input:s});for await(let c of i){let l=Ku(c,o);n.push({resource:l,request:{method:"POST",url:l.resourceType}}),n.length%e===0&&(await Qs(n,r),n=[])}n.length>0&&await Qs(n,r)}async function Qs(t,e){(await e.executeBatch({resourceType:"Bundle",type:"transaction",entry:t})).entry?.forEach(o=>{J(o.response)})}function Ku(t,e){let r=JSON.parse(t);return e?qu(r):r}function qu(t){return t.resourceType==="ExplanationOfBenefit"?Hu(t):t}function Hu(t){return t.provider||(t.provider=zt()),t.item?.forEach(e=>{e?.productOrService||(e.productOrService=zt())}),t}var Nt=require("@medplum/core");var ni=require("node:net"),si=require("@medplum/core"),Tr=$(require("iconv-lite"),1),li=$(require("node:net"),1),oi=class extends EventTarget{addEventListener(t,e,r){super.addEventListener(t,e,r)}removeEventListener(t,e,r){super.removeEventListener(t,e,r)}};var Gu=class extends Event{constructor(t,e){super("message"),this.connection=t,this.message=e}},$t=class extends Event{constructor(t){super("error"),this.error=t}},ii=class extends Event{constructor(){super("close")}},ai=class extends oi{constructor(t,e="utf-8"){super(),this.chunks=[],this.messageQueue=[],this.socket=t,this.encoding=e,t.on("data",r=>{try{if(this.appendData(r),r.at(-2)===28&&r.at(-1)===13){let o=Buffer.concat(this.chunks),n=o.subarray(1,o.length-2),s=Tr.default.decode(n,this.encoding),i=si.Hl7Message.parse(s);this.dispatchEvent(new Gu(this,i)),this.resetBuffer()}}catch(o){this.dispatchEvent(new $t(o))}}),t.on("error",r=>{this.resetBuffer(),this.dispatchEvent(new $t(r))}),t.on("end",()=>{this.close()}),this.addEventListener("message",r=>{let o=this.messageQueue.shift();if(!o){this.dispatchEvent(new $t(new Error(`Received a message when no pending messages were in the queue. Message: ${r.message}`)));return}o.resolve?.(r.message)})}sendImpl(t,e){this.messageQueue.push(e);let r=t.toString(),o=Tr.default.encode(r,this.encoding),n=Buffer.alloc(o.length+3);n.writeInt8(11,0),o.copy(n,1),n.writeInt8(28,o.length+1),n.writeInt8(13,o.length+2),this.socket.write(n)}send(t){this.sendImpl(t,{message:t})}async sendAndWait(t){return new Promise((e,r)=>{let o={message:t,resolve:e,reject:r};this.sendImpl(t,o)})}close(){this.socket.end(),this.socket.destroy(),this.dispatchEvent(new ii)}appendData(t){this.chunks.push(t)}resetBuffer(){this.chunks=[]}},ci=class extends oi{constructor(t){super(),this.options=t,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding,this.keepAlive=this.options.keepAlive??!1}connect(){return this.connection?Promise.resolve(this.connection):new Promise((t,e)=>{let r=(0,ni.connect)({host:this.host,port:this.port,keepAlive:this.keepAlive},()=>{let o;this.connection=o=new ai(r,this.encoding),r.off("error",e),o.addEventListener("close",()=>this.dispatchEvent(new ii)),o.addEventListener("error",n=>this.dispatchEvent(new $t(n.error))),t(this.connection)});r.on("error",e)})}async send(t){return(await this.connect()).send(t)}async sendAndWait(t){return(await this.connect()).sendAndWait(t)}close(){this.connection&&(this.connection.close(),delete this.connection)}},ui=class{constructor(t){this.handler=t}start(t,e){let r=li.default.createServer(o=>{let n=new ai(o,e);this.handler(n)});r.listen(t),this.server=r}async stop(){return new Promise((t,e)=>{if(!this.server){e(new Error("Stop was called but there is no server running"));return}this.server.close(r=>{if(r){e(r);return}t()}),this.server=void 0})}};var pi=require("node:fs");var Vu=new g("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(t,e,r,o)=>{if(o.generateExample?r=Xu():o.file&&(r=(0,pi.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new ci({host:t,port:Number.parseInt(e,10),encoding:o.encoding});try{let s=await n.sendAndWait(Nt.Hl7Message.parse(r));console.log(s.toString().replaceAll("\r",`
15
15
  `))}finally{n.close()}}),Ju=new g("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(t,e)=>{new ui(o=>{o.addEventListener("message",({message:n})=>{console.log(n.toString().replaceAll("\r",`
16
- `)),o.send(n.buildAck())})}).start(Number.parseInt(t,10),e.encoding),console.log("Listening on port "+t)}),Dt=new g("hl7");y(Dt,Vu);y(Dt,Ju);function Xu(){let t=(0,Lt.formatHl7DateTime)(new Date),e=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${t}||ADT^A01|${e}|P|2.5|
16
+ `)),o.send(n.buildAck())})}).start(Number.parseInt(t,10),e.encoding),console.log("Listening on port "+t)}),Lt=new g("hl7");y(Lt,Vu);y(Lt,Ju);function Xu(){let t=(0,Nt.formatHl7DateTime)(new Date),e=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${t}||ADT^A01|${e}|P|2.5|
17
17
  EVN|A01|${t}||
18
18
  PID|1|12345|12345^^^HOSP^MR|123456|DOE^JOHN^MIDDLE^SUFFIX|19800101|M|||123 STREET^APT 4B^CITY^ST^12345-6789||555-555-5555||S|
19
19
  PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var di=require("node:fs"),mi=require("node:os"),fi=require("node:path");var hi=new g("set"),gi=new g("remove"),yi=new g("list"),wi=new g("describe"),Ae=new g("profile");y(Ae,hi);y(Ae,gi);y(Ae,yi);y(Ae,wi);hi.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(t,e)=>{et(t,e)});gi.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async t=>{new j(t).setObject("options",void 0),console.log(`${t} profile removed`)});yi.description("List all profiles saved").action(async()=>{let t=(0,fi.resolve)((0,mi.homedir)(),".medplum"),e=(0,di.readdirSync)(t),r=[];e.forEach(o=>{let n=o.split(".")[0],i=new j(n).getObject("options");i&&r.push({profileName:n,profile:i})}),console.log(r)});wi.argument("<profileName>","Name of the profile").description("Describes a profile").action(async t=>{let e=go(t);console.log(e)});var Ei=require("commander");var Si=new g("list"),Ri=new g("current"),Ai=new g("switch"),Ii=new g("invite"),Ie=new g("project");y(Ie,Si);y(Ie,Ri);y(Ie,Ai);y(Ie,Ii);Si.description("List of current projects").action(async t=>{let e=await R(t);zu(e)});function zu(t){let r=t.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
20
20
 
21
21
  `);console.log(r)}Ri.description("Project you are currently on").action(async t=>{let r=(await R(t)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});Ai.description("Switching to another project from the current one").argument("<projectId>").action(async(t,e)=>{let r=await R(e);await Yu(r,t)});Ii.description("Invite a member to your current project (run npx medplum project current to confirm)").arguments("<firstName> <lastName> <email>").option("--send-email","If you want to send the email when inviting the user").option("--admin","If the user you are inviting is an admin").addOption(new Ei.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(t,e,r,o)=>{let n=await R(o),s=n.getActiveLogin();if(!s)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!s?.project?.reference)throw new Error("No current project to invite user to");let i=s.project.reference.split("/")[1],c={resourceType:o.role,firstName:t,lastName:e,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await Zu(i,c,n)});async function Yu(t,e){let o=t.getLogins().find(n=>n.project.reference?.includes(e));if(!o)throw new Error(`Project ${e} not found. Make sure you are added as a user to this project`);await t.setActiveLogin(o),console.log(`Switched to project ${e}
22
- `)}async function Zu(t,e,r){await r.invite(t,e),e.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var bi=require("@medplum/core");var Or=new g("delete"),xr=new g("get"),$r=new g("patch"),Nr=new g("post"),Lr=new g("put");Or.argument("<url>","Resource/$id").action(async(t,e)=>{let r=await R(e);J(await r.delete(qe(r,t)))});xr.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(t,e)=>{let r=await R(e),o=await r.get(qe(r,t));e.asTransaction?J((0,bi.convertToTransactionBundle)(o)):J(o)});$r.arguments("<url> <body>").action(async(t,e,r)=>{let o=await R(r);J(await o.patch(qe(o,t),Dr(e)))});Nr.arguments("<url> <body>").action(async(t,e,r)=>{let o=await R(r);J(await o.post(qe(o,t),Dr(e)))});Lr.arguments("<url> <body>").action(async(t,e,r)=>{let o=await R(r);J(await o.put(qe(o,t),Dr(e)))});function Dr(t){if(t)try{return JSON.parse(t)}catch{return t}}function qe(t,e){return["admin/","auth/","fhir/R4"].some(o=>e.startsWith(o))?e:t.fhirUrl(e).toString()}async function Pi(t){let e=new g("medplum").description("Command to access Medplum CLI").option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base URL, must be absolute").option("--token-url <tokenUrl>","FHIR server token URL, absolute or relative to base URL").option("--authorize-url <authorizeUrl>","FHIR server authorize URL, absolute or relative to base URL").option("--fhir-url, --fhir-url-path <fhirUrlPath>","FHIR server URL, absolute or relative to base URL").option("--scope <scope>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new He.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"])).on("option:verbose",()=>{process.env.VERBOSE="1"});e.exitOverride(),e.version(be.MEDPLUM_VERSION),e.configureHelp({showGlobalOptions:!0}),y(e,Qt),y(e,er),y(e,tr),y(e,xr),y(e,Nr),y(e,$r),y(e,Lr),y(e,Or),y(e,Ie),y(e,xt),y(e,We),y(e,ie),y(e,vr),y(e,Pr),y(e,Cr),y(e,Ae),y(e,Xs()),y(e,Dt);try{await e.parseAsync(t)}catch(r){Ci(r)}}function Ci(t){let e=1,r=!0;if(t instanceof He.CommanderError&&(process.env.VERBOSE||(r=!1),e=t.exitCode),e!==0&&r){kr(t,!!process.env.VERBOSE);let o=t.cause;if(process.env.VERBOSE)if(Array.isArray(o))for(let n of o)kr(n,!0);else o instanceof Error&&kr(o,!0)}process.exit(e)}function kr(t,e=!1){if(e){console.error(t);return}t instanceof He.CommanderError?process.stderr.write(`${(0,be.normalizeErrorString)(t)}
22
+ `)}async function Zu(t,e,r){await r.invite(t,e),e.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var bi=require("@medplum/core");var Or=new g("delete"),xr=new g("get"),$r=new g("patch"),Nr=new g("post"),Lr=new g("put");Or.argument("<url>","Resource/$id").action(async(t,e)=>{let r=await R(e);J(await r.delete(qe(r,t)))});xr.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(t,e)=>{let r=await R(e),o=await r.get(qe(r,t));e.asTransaction?J((0,bi.convertToTransactionBundle)(o)):J(o)});$r.arguments("<url> <body>").action(async(t,e,r)=>{let o=await R(r);J(await o.patch(qe(o,t),Dr(e)))});Nr.arguments("<url> <body>").action(async(t,e,r)=>{let o=await R(r);J(await o.post(qe(o,t),Dr(e)))});Lr.arguments("<url> <body>").action(async(t,e,r)=>{let o=await R(r);J(await o.put(qe(o,t),Dr(e)))});function Dr(t){if(t)try{return JSON.parse(t)}catch{return t}}function qe(t,e){return["admin/","auth/","fhir/R4"].some(o=>e.startsWith(o))?e:t.fhirUrl(e).toString()}async function Pi(t){let e=new g("medplum").description("Command to access Medplum CLI").option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base URL, must be absolute").option("--token-url <tokenUrl>","FHIR server token URL, absolute or relative to base URL").option("--authorize-url <authorizeUrl>","FHIR server authorize URL, absolute or relative to base URL").option("--fhir-url, --fhir-url-path <fhirUrlPath>","FHIR server URL, absolute or relative to base URL").option("--scope <scope>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new He.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"])).on("option:verbose",()=>{process.env.VERBOSE="1"});e.exitOverride(),e.version(be.MEDPLUM_VERSION),e.configureHelp({showGlobalOptions:!0}),y(e,Zt),y(e,Qt),y(e,er),y(e,xr),y(e,Nr),y(e,$r),y(e,Lr),y(e,Or),y(e,Ie),y(e,xt),y(e,Ke),y(e,ie),y(e,br),y(e,vr),y(e,Pr),y(e,Ae),y(e,Xs()),y(e,Lt);try{await e.parseAsync(t)}catch(r){Ci(r)}}function Ci(t){let e=1,r=!0;if(t instanceof He.CommanderError&&(process.env.VERBOSE||(r=!1),e=t.exitCode),e!==0&&r){kr(t,!!process.env.VERBOSE);let o=t.cause;if(process.env.VERBOSE)if(Array.isArray(o))for(let n of o)kr(n,!0);else o instanceof Error&&kr(o,!0)}process.exit(e)}function kr(t,e=!1){if(e){console.error(t);return}t instanceof He.CommanderError?process.stderr.write(`${(0,be.normalizeErrorString)(t)}
23
23
  `):process.stderr.write(`Error: ${(0,be.normalizeErrorString)(t)}
24
24
  `)}async function Ti(){vi.default.config(),await Pi(process.argv)}require.main===module&&Ti().catch(t=>{console.error("Unhandled error:",(0,be.normalizeErrorString)(t)),process.exit(1)});0&&(module.exports={handleError,main,run});
25
25
  //# sourceMappingURL=index.cjs.map