@medplum/cli 4.3.6 → 4.3.7

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