@medplum/cli 5.1.36 → 5.1.37

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,30 +1,30 @@
1
1
  #!/usr/bin/env node
2
- var Ii=Object.create;var At=Object.defineProperty;var vi=Object.getOwnPropertyDescriptor;var Ci=Object.getOwnPropertyNames;var Ti=Object.getPrototypeOf,Oi=Object.prototype.hasOwnProperty;var Nr=e=>{throw TypeError(e)};var xi=(e,t,r)=>t in e?At(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var $i=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ci(t))!Oi.call(e,o)&&o!==r&&At(e,o,{get:()=>t[o],enumerable:!(n=vi(t,o))||n.enumerable});return e};var kr=(e,t,r)=>(r=e!=null?Ii(Ti(e)):{},$i(t||!e||!e.__esModule?At(r,"default",{value:e,enumerable:!0}):r,e));var N=(e,t,r)=>xi(e,typeof t!="symbol"?t+"":t,r),Dr=(e,t,r)=>t.has(e)||Nr("Cannot "+r);var R=(e,t,r)=>(Dr(e,t,"read from private field"),r?r.call(e):t.get(e)),L=(e,t,r)=>t.has(e)?Nr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),U=(e,t,r,n)=>(Dr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var ce=w((eg,jn)=>{"use strict";var Ba="2.0.0",Wa=Number.MAX_SAFE_INTEGER||9007199254740991,qa=16,Ka=250,Ga=["major","premajor","minor","preminor","patch","prepatch","prerelease"];jn.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:qa,MAX_SAFE_BUILD_LENGTH:Ka,MAX_SAFE_INTEGER:Wa,RELEASE_TYPES:Ga,SEMVER_SPEC_VERSION:Ba,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var be=w((tg,Bn)=>{"use strict";var Va=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};Bn.exports=Va});var le=w((V,Wn)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Ht,MAX_SAFE_BUILD_LENGTH:Ha,MAX_LENGTH:Ja}=ce(),Xa=be();V=Wn.exports={};var za=V.re=[],Ya=V.safeRe=[],p=V.src=[],Qa=V.safeSrc=[],d=V.t={},Za=0,Jt="[a-zA-Z0-9-]",ec=[["\\s",1],["\\d",Ja],[Jt,Ha]],tc=e=>{for(let[t,r]of ec)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=tc(t),o=Za++;Xa(e,o,t),d[e]=o,p[o]=t,Qa[o]=n,za[o]=new RegExp(t,r?"g":void 0),Ya[o]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Jt}*`);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",`${Jt}+`);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,${Ht}})(?:\\.(\\d{1,${Ht}}))?(?:\\.(\\d{1,${Ht}}))?`);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);V.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);V.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);V.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 Xe=w((rg,qn)=>{"use strict";var rc=Object.freeze({loose:!0}),nc=Object.freeze({}),oc=e=>e?typeof e!="object"?rc:e:nc;qn.exports=oc});var Xt=w((ng,Vn)=>{"use strict";var Kn=/^[0-9]+$/,Gn=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=Kn.test(e),n=Kn.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},sc=(e,t)=>Gn(t,e);Vn.exports={compareIdentifiers:Gn,rcompareIdentifiers:sc}});var x=w((og,Jn)=>{"use strict";var ze=be(),{MAX_LENGTH:Hn,MAX_SAFE_INTEGER:Ye}=ce(),{safeRe:Qe,t:Ze}=le(),ic=Xe(),{compareIdentifiers:zt}=Xt(),ac=(e,t)=>{let r=t.split(".");if(r.length>e.length)return!1;for(let n=0;n<r.length;n++)if(zt(e[n],r[n])!==0)return!1;return!0},Yt=class e{constructor(t,r){if(r=ic(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>Hn)throw new TypeError(`version is longer than ${Hn} characters`);ze("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?Qe[Ze.LOOSE]:Qe[Ze.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Ye||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Ye||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Ye||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){let s=+o;if(s>=0&&s<Ye)return s}return o}):this.prerelease=[],this.build=n[5]?n[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(ze("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)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}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 n=this.prerelease[r],o=t.prerelease[r];if(ze("prerelease compare",r,n,o),n===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(n===void 0)return-1;if(n===o)continue;return zt(n,o)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],o=t.build[r];if(ze("build compare",r,n,o),n===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(n===void 0)return-1;if(n===o)continue;return zt(n,o)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let o=`-${r}`.match(this.options.loose?Qe[Ze.PRERELEASELOOSE]:Qe[Ze.PRERELEASE]);if(!o||o[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,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);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 o=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[o];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(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(r){let s=[r,o];if(n===!1&&(s=[r]),ac(this.prerelease,r)){let i=this.prerelease[r.split(".").length];isNaN(i)&&(this.prerelease=s)}else 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}};Jn.exports=Yt});var Q=w((sg,zn)=>{"use strict";var Xn=x(),cc=(e,t,r=!1)=>{if(e instanceof Xn)return e;try{return new Xn(e,t)}catch(n){if(!r)return null;throw n}};zn.exports=cc});var Qn=w((ig,Yn)=>{"use strict";var lc=Q(),uc=(e,t)=>{let r=lc(e,t);return r?r.version:null};Yn.exports=uc});var eo=w((ag,Zn)=>{"use strict";var pc=Q(),dc=(e,t)=>{let r=pc(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Zn.exports=dc});var no=w((cg,ro)=>{"use strict";var to=x(),mc=(e,t,r,n,o)=>{typeof r=="string"&&(o=n,n=r,r=void 0);try{return new to(e instanceof to?e.version:e,r).inc(t,n,o).version}catch{return null}};ro.exports=mc});var io=w((lg,so)=>{"use strict";var oo=Q(),fc=(e,t)=>{let r=oo(e,null,!0),n=oo(t,null,!0),o=r.compare(n);if(o===0)return null;let s=o>0,i=s?r:n,a=s?n:r,l=!!i.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}let f=l?"pre":"";return r.major!==n.major?f+"major":r.minor!==n.minor?f+"minor":r.patch!==n.patch?f+"patch":"prerelease"};so.exports=fc});var co=w((ug,ao)=>{"use strict";var gc=x(),hc=(e,t)=>new gc(e,t).major;ao.exports=hc});var uo=w((pg,lo)=>{"use strict";var yc=x(),wc=(e,t)=>new yc(e,t).minor;lo.exports=wc});var mo=w((dg,po)=>{"use strict";var Ec=x(),Sc=(e,t)=>new Ec(e,t).patch;po.exports=Sc});var go=w((mg,fo)=>{"use strict";var Rc=Q(),Ac=(e,t)=>{let r=Rc(e,t);return r&&r.prerelease.length?r.prerelease:null};fo.exports=Ac});var F=w((fg,yo)=>{"use strict";var ho=x(),bc=(e,t,r)=>new ho(e,r).compare(new ho(t,r));yo.exports=bc});var Eo=w((gg,wo)=>{"use strict";var Pc=F(),Ic=(e,t,r)=>Pc(t,e,r);wo.exports=Ic});var Ro=w((hg,So)=>{"use strict";var vc=F(),Cc=(e,t)=>vc(e,t,!0);So.exports=Cc});var et=w((yg,bo)=>{"use strict";var Ao=x(),Tc=(e,t,r)=>{let n=new Ao(e,r),o=new Ao(t,r);return n.compare(o)||n.compareBuild(o)};bo.exports=Tc});var Io=w((wg,Po)=>{"use strict";var Oc=et(),xc=(e,t)=>e.sort((r,n)=>Oc(r,n,t));Po.exports=xc});var Co=w((Eg,vo)=>{"use strict";var $c=et(),Nc=(e,t)=>e.sort((r,n)=>$c(n,r,t));vo.exports=Nc});var Pe=w((Sg,To)=>{"use strict";var kc=F(),Dc=(e,t,r)=>kc(e,t,r)>0;To.exports=Dc});var tt=w((Rg,Oo)=>{"use strict";var Mc=F(),Lc=(e,t,r)=>Mc(e,t,r)<0;Oo.exports=Lc});var Qt=w((Ag,xo)=>{"use strict";var Uc=F(),_c=(e,t,r)=>Uc(e,t,r)===0;xo.exports=_c});var Zt=w((bg,$o)=>{"use strict";var Fc=F(),jc=(e,t,r)=>Fc(e,t,r)!==0;$o.exports=jc});var rt=w((Pg,No)=>{"use strict";var Bc=F(),Wc=(e,t,r)=>Bc(e,t,r)>=0;No.exports=Wc});var nt=w((Ig,ko)=>{"use strict";var qc=F(),Kc=(e,t,r)=>qc(e,t,r)<=0;ko.exports=Kc});var er=w((vg,Do)=>{"use strict";var Gc=Qt(),Vc=Zt(),Hc=Pe(),Jc=rt(),Xc=tt(),zc=nt(),Yc=(e,t,r,n)=>{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 Gc(e,r,n);case"!=":return Vc(e,r,n);case">":return Hc(e,r,n);case">=":return Jc(e,r,n);case"<":return Xc(e,r,n);case"<=":return zc(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Do.exports=Yc});var Lo=w((Cg,Mo)=>{"use strict";var Qc=x(),Zc=Q(),{safeRe:ot,t:st}=le(),el=(e,t)=>{if(e instanceof Qc)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?ot[st.COERCEFULL]:ot[st.COERCE]);else{let l=t.includePrerelease?ot[st.COERCERTLFULL]:ot[st.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 n=r[2],o=r[3]||"0",s=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Zc(`${n}.${o}.${s}${i}${a}`,t)};Mo.exports=el});var _o=w((Tg,Uo)=>{"use strict";var tl=Q(),rl=ce(),nl=x(),ol=(e,t,r)=>{if(!rl.RELEASE_TYPES.includes(t))return null;let n=sl(e,r);return n&&il(n,t)},sl=(e,t)=>{let r=e instanceof nl?e.version:e;return tl(r,t)},il=(e,t)=>{if(al(t))return e.version;switch(e.prerelease=[],t){case"major":e.minor=0,e.patch=0;break;case"minor":e.patch=0;break}return e.format()},al=e=>e.startsWith("pre");Uo.exports=ol});var jo=w((Og,Fo)=>{"use strict";var tr=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 o=this.map.keys().next().value;this.delete(o)}this.map.set(t,r)}return this}};Fo.exports=tr});var j=w((xg,Ko)=>{"use strict";var cl=/\s+/g,rr=class e{constructor(t,r){if(r=ul(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof nr)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(cl," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(o=>!Wo(o[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let o of this.set)if(o.length===1&&El(o[0])){this.set=[o];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 n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(wl,"");let n=((this.options.includePrerelease&&hl)|(this.options.loose&&yl))+":"+t,o=Bo.get(n);if(o)return o;let s=this.options.loose,i=s?k[$.HYPHENRANGELOOSE]:k[$.HYPHENRANGE];t=t.replace(i,xl(this.options.includePrerelease)),P("hyphen replace",t),t=t.replace(k[$.COMPARATORTRIM],ml),P("comparator trim",t),t=t.replace(k[$.TILDETRIM],fl),P("tilde trim",t),t=t.replace(k[$.CARETTRIM],gl),P("caret trim",t);let a=t.split(" ").map(m=>Sl(m,this.options)).join(" ").split(/\s+/).map(m=>Ol(m,this.options));s&&(a=a.filter(m=>(P("loose invalid filter",m,this.options),!!m.match(k[$.COMPARATORLOOSE])))),P("range list",a);let l=new Map,u=a.map(m=>new nr(m,this.options));for(let m of u){if(Wo(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let f=[...l.values()];return Bo.set(n,f),f}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>qo(n,r)&&t.set.some(o=>qo(o,r)&&n.every(s=>o.every(i=>s.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new pl(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if($l(this.set[r],t,this.options))return!0;return!1}};Ko.exports=rr;var ll=jo(),Bo=new ll,ul=Xe(),nr=Ie(),P=be(),pl=x(),{safeRe:k,src:dl,t:$,comparatorTrimReplace:ml,tildeTrimReplace:fl,caretTrimReplace:gl}=le(),{FLAG_INCLUDE_PRERELEASE:hl,FLAG_LOOSE:yl}=ce(),wl=new RegExp(dl[$.BUILD],"g"),Wo=e=>e.value==="<0.0.0-0",El=e=>e.value==="",qo=(e,t)=>{let r=!0,n=e.slice(),o=n.pop();for(;r&&n.length;)r=n.every(s=>o.intersects(s,t)),o=n.pop();return r},Sl=(e,t)=>(e=e.replace(k[$.BUILD],""),P("comp",e,t),e=Pl(e,t),P("caret",e),e=Al(e,t),P("tildes",e),e=vl(e,t),P("xrange",e),e=Tl(e,t),P("stars",e),e),T=e=>!e||e.toLowerCase()==="x"||e==="*",Rl=(e,t,r)=>T(e)&&!T(t)||T(t)&&r&&!T(r),Al=(e,t)=>e.trim().split(/\s+/).map(r=>bl(r,t)).join(" "),bl=(e,t)=>{let r=t.loose?k[$.TILDELOOSE]:k[$.TILDE],n=t.includePrerelease?"-0":"";return e.replace(r,(o,s,i,a,l)=>{P("tilde",e,o,s,i,a,l);let u;return T(s)?u="":T(i)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:T(a)?u=`>=${s}.${i}.0${n} <${s}.${+i+1}.0-0`:l?(P("replaceTilde pr",l),u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`):u=`>=${s}.${i}.${a} <${s}.${+i+1}.0-0`,P("tilde return",u),u})},Pl=(e,t)=>e.trim().split(/\s+/).map(r=>Il(r,t)).join(" "),Il=(e,t)=>{P("caret",e,t);let r=t.loose?k[$.CARETLOOSE]:k[$.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(o,s,i,a,l)=>{P("caret",e,o,s,i,a,l);let u;return T(s)?u="":T(i)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:T(a)?s==="0"?u=`>=${s}.${i}.0${n} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${n} <${+s+1}.0.0-0`:l?(P("replaceCaret pr",l),s==="0"?i==="0"?u=`>=${s}.${i}.${a}-${l} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a}-${l} <${+s+1}.0.0-0`):(P("no pr"),s==="0"?i==="0"?u=`>=${s}.${i}.${a} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a} <${+s+1}.0.0-0`),P("caret return",u),u})},vl=(e,t)=>(P("replaceXRanges",e,t),e.split(/\s+/).map(r=>Cl(r,t)).join(" ")),Cl=(e,t)=>{e=e.trim();let r=t.loose?k[$.XRANGELOOSE]:k[$.XRANGE];return e.replace(r,(n,o,s,i,a,l)=>{if(P("xRange",e,n,o,s,i,a,l),Rl(s,i,a))return e;let u=T(s),f=u||T(i),m=f||T(a),S=m;return o==="="&&S&&(o=""),l=t.includePrerelease?"-0":"",u?o===">"||o==="<"?n="<0.0.0-0":n="*":o&&S?(f&&(i=0),a=0,o===">"?(o=">=",f?(s=+s+1,i=0,a=0):(i=+i+1,a=0)):o==="<="&&(o="<",f?s=+s+1:i=+i+1),o==="<"&&(l="-0"),n=`${o+s}.${i}.${a}${l}`):f?n=`>=${s}.0.0${l} <${+s+1}.0.0-0`:m&&(n=`>=${s}.${i}.0${l} <${s}.${+i+1}.0-0`),P("xRange return",n),n})},Tl=(e,t)=>(P("replaceStars",e,t),e.trim().replace(k[$.STAR],"")),Ol=(e,t)=>(P("replaceGTE0",e,t),e.trim().replace(k[t.includePrerelease?$.GTE0PRE:$.GTE0],"")),xl=e=>(t,r,n,o,s,i,a,l,u,f,m,S)=>(T(n)?r="":T(o)?r=`>=${n}.0.0${e?"-0":""}`:T(s)?r=`>=${n}.${o}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,T(u)?l="":T(f)?l=`<${+u+1}.0.0-0`:T(m)?l=`<${u}.${+f+1}.0-0`:S?l=`<=${u}.${f}.${m}-${S}`:e?l=`<${u}.${f}.${+m+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),$l=(e,t,r)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let n=0;n<e.length;n++)if(P(e[n].semver),e[n].semver!==nr.ANY&&e[n].semver.prerelease.length>0){let o=e[n].semver;if(o.major===t.major&&o.minor===t.minor&&o.patch===t.patch)return!0}return!1}return!0}});var Ie=w(($g,zo)=>{"use strict";var ve=Symbol("SemVer ANY"),ir=class e{static get ANY(){return ve}constructor(t,r){if(r=Go(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),sr("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===ve?this.value="":this.value=this.operator+this.semver.version,sr("comp",this)}parse(t){let r=this.options.loose?Vo[Ho.COMPARATORLOOSE]:Vo[Ho.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Jo(n[2],this.options.loose):this.semver=ve}toString(){return this.value}test(t){if(sr("Comparator.test",t,this.options.loose),this.semver===ve||t===ve)return!0;if(typeof t=="string")try{t=new Jo(t,this.options)}catch{return!1}return or(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 Xo(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Xo(this.value,r).test(t.semver):(r=Go(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("=")||or(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||or(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};zo.exports=ir;var Go=Xe(),{safeRe:Vo,t:Ho}=le(),or=er(),sr=be(),Jo=x(),Xo=j()});var Ce=w((Ng,Yo)=>{"use strict";var Nl=j(),kl=(e,t,r)=>{try{t=new Nl(t,r)}catch{return!1}return t.test(e)};Yo.exports=kl});var Zo=w((kg,Qo)=>{"use strict";var Dl=j(),Ml=(e,t)=>new Dl(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));Qo.exports=Ml});var ts=w((Dg,es)=>{"use strict";var Ll=x(),Ul=j(),_l=(e,t,r)=>{let n=null,o=null,s=null;try{s=new Ul(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!n||o.compare(i)===-1)&&(n=i,o=new Ll(n,r))}),n};es.exports=_l});var ns=w((Mg,rs)=>{"use strict";var Fl=x(),jl=j(),Bl=(e,t,r)=>{let n=null,o=null,s=null;try{s=new jl(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!n||o.compare(i)===1)&&(n=i,o=new Fl(n,r))}),n};rs.exports=Bl});var is=w((Lg,ss)=>{"use strict";var ar=x(),Wl=j(),os=Pe(),ql=(e,t)=>{e=new Wl(e,t);let r=new ar("0.0.0");if(e.test(r)||(r=new ar("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n<e.set.length;++n){let o=e.set[n],s=null;o.forEach(i=>{let a=new ar(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||os(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||os(r,s))&&(r=s)}return r&&e.test(r)?r:null};ss.exports=ql});var cs=w((Ug,as)=>{"use strict";var Kl=j(),Gl=(e,t)=>{try{return new Kl(e,t).range||"*"}catch{return null}};as.exports=Gl});var it=w((_g,ds)=>{"use strict";var Vl=x(),ps=Ie(),{ANY:Hl}=ps,Jl=j(),Xl=Ce(),ls=Pe(),us=tt(),zl=nt(),Yl=rt(),Ql=(e,t,r,n)=>{e=new Vl(e,n),t=new Jl(t,n);let o,s,i,a,l;switch(r){case">":o=ls,s=zl,i=us,a=">",l=">=";break;case"<":o=us,s=Yl,i=ls,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Xl(e,t,n))return!1;for(let u=0;u<t.set.length;++u){let f=t.set[u],m=null,S=null;if(f.forEach(g=>{g.semver===Hl&&(g=new ps(">=0.0.0")),m=m||g,S=S||g,o(g.semver,m.semver,n)?m=g:i(g.semver,S.semver,n)&&(S=g)}),m.operator===a||m.operator===l||(!S.operator||S.operator===a)&&s(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};ds.exports=Ql});var fs=w((Fg,ms)=>{"use strict";var Zl=it(),eu=(e,t,r)=>Zl(e,t,">",r);ms.exports=eu});var hs=w((jg,gs)=>{"use strict";var tu=it(),ru=(e,t,r)=>tu(e,t,"<",r);gs.exports=ru});var Es=w((Bg,ws)=>{"use strict";var ys=j(),nu=(e,t,r)=>(e=new ys(e,r),t=new ys(t,r),e.intersects(t,r));ws.exports=nu});var Rs=w((Wg,Ss)=>{"use strict";var ou=Ce(),su=F();Ss.exports=(e,t,r)=>{let n=[],o=null,s=null,i=e.sort((f,m)=>su(f,m,r));for(let f of i)ou(f,t,r)?(s=f,o||(o=f)):(s&&n.push([o,s]),s=null,o=null);o&&n.push([o,null]);let a=[];for(let[f,m]of n)f===m?a.push(f):!m&&f===i[0]?a.push("*"):m?f===i[0]?a.push(`<=${m}`):a.push(`${f} - ${m}`):a.push(`>=${f}`);let l=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var Cs=w((qg,vs)=>{"use strict";var As=j(),ur=Ie(),{ANY:cr}=ur,lr=Ce(),pr=F(),iu=(e,t,r={})=>{if(e===t)return!0;e=new As(e,r),t=new As(t,r);let n=!1;e:for(let o of e.set){for(let s of t.set){let i=cu(o,s,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},au=[new ur(">=0.0.0-0")],bs=[new ur(">=0.0.0")],cu=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===cr){if(t.length===1&&t[0].semver===cr)return!0;r.includePrerelease?e=au:e=bs}if(t.length===1&&t[0].semver===cr){if(r.includePrerelease)return!0;t=bs}let n=new Set,o,s;for(let g of e)g.operator===">"||g.operator===">="?o=Ps(o,g,r):g.operator==="<"||g.operator==="<="?s=Is(s,g,r):n.add(g.semver);if(n.size>1)return null;let i;if(o&&s){if(i=pr(o.semver,s.semver,r),i>0)return null;if(i===0&&(o.operator!==">="||s.operator!=="<="))return null}for(let g of n){if(o&&!lr(g,String(o),r)||s&&!lr(g,String(s),r))return null;for(let z of t)if(!lr(g,String(z),r))return!1;return!0}let a,l,u,f,m=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,S=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1;m&&m.prerelease.length===1&&s.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let g of t){if(f=f||g.operator===">"||g.operator===">=",u=u||g.operator==="<"||g.operator==="<=",o){if(S&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===S.major&&g.semver.minor===S.minor&&g.semver.patch===S.patch&&(S=!1),g.operator===">"||g.operator===">="){if(a=Ps(o,g,r),a===g&&a!==o)return!1}else if(o.operator===">="&&!g.test(o.semver))return!1}if(s){if(m&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===m.major&&g.semver.minor===m.minor&&g.semver.patch===m.patch&&(m=!1),g.operator==="<"||g.operator==="<="){if(l=Is(s,g,r),l===g&&l!==s)return!1}else if(s.operator==="<="&&!g.test(s.semver))return!1}if(!g.operator&&(s||o)&&i!==0)return!1}return!(o&&u&&!s&&i!==0||s&&f&&!o&&i!==0||S||m)},Ps=(e,t,r)=>{if(!e)return t;let n=pr(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},Is=(e,t,r)=>{if(!e)return t;let n=pr(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};vs.exports=iu});var mr=w((Kg,xs)=>{"use strict";var dr=le(),Ts=ce(),lu=x(),Os=Xt(),uu=Q(),pu=Qn(),du=eo(),mu=no(),fu=io(),gu=co(),hu=uo(),yu=mo(),wu=go(),Eu=F(),Su=Eo(),Ru=Ro(),Au=et(),bu=Io(),Pu=Co(),Iu=Pe(),vu=tt(),Cu=Qt(),Tu=Zt(),Ou=rt(),xu=nt(),$u=er(),Nu=Lo(),ku=_o(),Du=Ie(),Mu=j(),Lu=Ce(),Uu=Zo(),_u=ts(),Fu=ns(),ju=is(),Bu=cs(),Wu=it(),qu=fs(),Ku=hs(),Gu=Es(),Vu=Rs(),Hu=Cs();xs.exports={parse:uu,valid:pu,clean:du,inc:mu,diff:fu,major:gu,minor:hu,patch:yu,prerelease:wu,compare:Eu,rcompare:Su,compareLoose:Ru,compareBuild:Au,sort:bu,rsort:Pu,gt:Iu,lt:vu,eq:Cu,neq:Tu,gte:Ou,lte:xu,cmp:$u,coerce:Nu,truncate:ku,Comparator:Du,Range:Mu,satisfies:Lu,toComparators:Uu,maxSatisfying:_u,minSatisfying:Fu,minVersion:ju,validRange:Bu,outside:Wu,gtr:qu,ltr:Ku,intersects:Gu,simplifyRange:Vu,subset:Hu,SemVer:lu,re:dr.re,src:dr.src,tokens:dr.t,SEMVER_SPEC_VERSION:Ts.SEMVER_SPEC_VERSION,RELEASE_TYPES:Ts.RELEASE_TYPES,compareIdentifiers:Os.compareIdentifiers,rcompareIdentifiers:Os.rcompareIdentifiers}});import{MEDPLUM_VERSION as lm,normalizeErrorString as $r}from"@medplum/core";import{CommanderError as bi,Option as um}from"commander";import pm from"dotenv";import{ContentType as Tn,EMPTY as fa,isOk as ga,isUUID as ha,normalizeErrorString as ya}from"@medplum/core";import{Option as Ve}from"commander";import{MedplumClient as Ui}from"@medplum/core";import{ClientStorage as Ni}from"@medplum/core";import{existsSync as Mr,mkdirSync as ki,readFileSync as Di,writeFileSync as Mi}from"node:fs";import{homedir as Li}from"node:os";import{resolve as Lr}from"node:path";var W=class extends Ni{constructor(r){super();N(this,"dirName");N(this,"fileName");this.dirName=Lr(Li(),".medplum"),this.fileName=Lr(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,n){let o=this.readFile()??{};n?o[r]=n:delete o[r],this.writeFile(o)}getObject(r){let n=this.getString(r);return n?JSON.parse(n):void 0}setObject(r,n){this.setString(r,n?JSON.stringify(n):void 0)}readFile(){if(Mr(this.fileName))return JSON.parse(Di(this.fileName,"utf8"))}writeFile(r){Mr(this.dirName)||ki(this.dirName),Mi(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function A(e,t=!0){let r=e.profile??"default",n=new W(r),o=n.getObject("options");if(r!=="default"&&!o)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:s,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:f,clientSecret:m}=_i(e,n),S=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await Fi(e.baseUrl,S);let g=new Ui({fetch:S,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:n,onUnauthenticated:ji,verbose:e.verbose});return t&&(a?g.setAccessToken(a):f&&m&&(g.setBasicAuth(f,m),o?.authType!=="basic"&&await g.startClientLogin(f,m))),g}function _i(e,t){let r=t.getObject("options"),n=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",o=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,a=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:n,fhirUrlPath:o,accessToken:s,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}async function Fi(e,t){try{let r=new URL("healthcheck",e).toString(),n=await t(r);if(!n.ok)throw new Error(`Healthcheck returned status ${n.status}`);if((await n.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${n}`)}}function ji(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{ContentType as Ut,encodeBase64 as fn,isOk as ea,normalizeErrorString as ta,OAuthSigningAlgorithm as gn}from"@medplum/core";import{Command as ra}from"commander";var De=new TextEncoder,bt=new TextDecoder,Bi=new TextDecoder("utf-8",{fatal:!0}),Im=2**32;function Ur(...e){let t=e.reduce((o,{length:s})=>o+s,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Me(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}var Le=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Wi(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function _r(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Fr(e,t,r){let n=e.algorithm;if(n.name!==t.name)throw Le(t.name);if(t.hash&&n.hash?.name!==t.hash)throw Le(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw Le(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&n.length!==t.length)throw Le(t.length,"algorithm.length");Wi(e,r)}function qi(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}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 Pt=(e,t,...r)=>qi(`Key for the ${e} algorithm must be `,t,...r);var te=class extends Error{constructor(r,n){super(r,n);N(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};N(te,"code","ERR_JOSE_GENERIC");var q=class extends te{constructor(){super(...arguments);N(this,"code","ERR_JOSE_NOT_SUPPORTED")}};N(q,"code","ERR_JOSE_NOT_SUPPORTED");var K=class extends te{constructor(){super(...arguments);N(this,"code","ERR_JWS_INVALID")}};N(K,"code","ERR_JWS_INVALID");var ye=class extends te{constructor(){super(...arguments);N(this,"code","ERR_JWT_INVALID")}};N(ye,"code","ERR_JWT_INVALID");var jr,Br,It=class extends(Br=te,jr=Symbol.asyncIterator,Br){constructor(r="multiple matching keys found in the JSON Web Key Set",n){super(r,n);N(this,jr,async function*(){});N(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};N(It,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var vt=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Ki=e=>e?.[Symbol.toStringTag]==="KeyObject",Wr=e=>vt(e)||Ki(e);function qr(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,r=[];for(let n=0;n<e.length;n+=t)r.push(String.fromCharCode.apply(null,e.subarray(n,n+t)));return btoa(r.join(""))}function Kr(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var Ct="The input to be decoded is not correctly encoded.";function Gr(e){if(Uint8Array.fromBase64)try{return Uint8Array.fromBase64(typeof e=="string"?e:bt.decode(e),{alphabet:"base64url"})}catch(r){throw new TypeError(Ct,{cause:r})}let t=e;if(t instanceof Uint8Array&&(t=bt.decode(t)),t.includes("+")||t.includes("/"))throw new TypeError(Ct);t=t.replace(/-/g,"+").replace(/_/g,"/");try{return Kr(t)}catch{throw new TypeError(Ct)}}function Ue(e){let t=e;return typeof t=="string"&&(t=De.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):qr(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Tt(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=t;for(;Object.getPrototypeOf(r)!==null;)r=Object.getPrototypeOf(r);return t===r}function Vr(...e){let t=new Set;for(let r of e)if(r)for(let n of Object.keys(r)){if(t.has(n))return!1;t.add(n)}return!0}var Hr=e=>Tt(e)&&typeof e.kty=="string",Jr=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),Xr=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,zr=e=>e.kty==="oct"&&typeof e.k=="string";function Ot(e,t){if(e)throw new TypeError(`${t} can only be called once`)}async function Yr(e,t){if(t.kty==="RSA"&&"oth"in t&&t.oth!==void 0)throw new q('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');if(!e.kty.includes(t.kty))throw new q('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,n=!!(t.d||t.priv),o={...t};return o.kty!=="AKP"&&delete o.alg,delete o.use,crypto.subtle.importKey("jwk",o,r,t.ext??!n,t.key_ops??e.usages[n?1:0])}var xt=e=>e[Symbol.toStringTag],Vi=(e,t,r)=>{let{alg:n}=e;if(t.use!==void 0){let o=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==o)throw new TypeError(`Invalid key for this operation, its "use" must be "${o}" when present`)}if(t.alg!==void 0&&t.alg!==n)throw new TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(t.key_ops)){let o=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(o&&!t.key_ops.includes(o))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}};function Hi(e,t,r){let{alg:n,secret:o}=e,s=r==="decrypt"||r==="sign";if(o&&t instanceof Uint8Array)return[Zr,t];if(Hr(t)){if(o?!zr(t):!(s?Jr(t):Xr(t)))throw new TypeError(o?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${s?"private":"public"} JWK`);return Vi(e,t,r),[rn,t]}if(!Wr(t))throw new TypeError(o?Pt(n,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):Pt(n,t,"CryptoKey","KeyObject","JSON Web Key"));if(o){if(t.type!=="secret")throw new TypeError(`${xt(t)} instances for symmetric algorithms must be of type "secret"`)}else{if(t.type==="secret")throw new TypeError(`${xt(t)} instances for asymmetric algorithms must not be of type "secret"`);let i=s?"private":"public";if((t.type==="public"||t.type==="private")&&t.type!==i){let a=r==="sign"?"signing":r==="verify"?"verifying":`${r.slice(0,-1)}tion`;throw new TypeError(`${xt(t)} instances for asymmetric algorithm ${a} must be of type "${i}"`)}}return vt(t)?[en,t]:[tn,t]}var Zr=0,en=1,tn=2,rn=3,$t,Ji={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function _e(e,t,r){$t||=new WeakMap;let n=$t.get(e);return r&&(n?n[t]=r:$t.set(e,{__proto__:null,[t]:r})),r??n?.[t]}var Qr=async(e,t,r)=>_e(e,r.alg)??_e(e,r.alg,await Yr(r,{...t,alg:r.alg})),Xi=(e,t)=>{let r=_e(e,t.alg);if(r)return r;let n=e.type==="public",o=t.usages[n?0:1],{asymmetricKeyType:s}=e,i=Ji[e.asymmetricKeyDetails?.namedCurve],a=t.resolve?.({crv:i,asymmetricKeyType:s})??t.subtle;return _e(e,t.alg,e.toCryptoKey(a,n,o))};async function nn(e,t,r){let n=Hi(e,t,r);switch(n[0]){case Zr:case en:return n[1];case rn:{let o=n[1];if(o.k)return Gr(o.k);if(!Object.isFrozen(o)){let{key_ops:s}=o;Array.isArray(s)&&Object.freeze(s),Object.freeze(o)}return Qr(o,o,e)}case tn:{let o=n[1];return o.type==="secret"?o.export():"toCryptoKey"in o&&typeof o.toCryptoKey=="function"?Xi(o,e):Qr(o,o.export({format:"jwk"}),e)}}}function on(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var sn={__proto__:null,b64:!0};function an(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function cn(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return[];if(!Array.isArray(n.crit)||n.crit.length===0||n.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?t:{__proto__:null,...r,...t};for(let i of n.crit){if(!(i in s))throw new q(`Extension Header Parameter "${i}" is not recognized`);if(!Object.hasOwn(o,i)||o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s[i]&&(!Object.hasOwn(n,i)||n[i]===void 0))throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return n.crit}async function zi(e,t,r){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,e.subtle,!1,[r]):(Fr(t,e.subtle,r),e.minRsaBits&&_r(e.alg,t),t)}async function ln(e,t,r){let n=await zi(e,t,"sign"),o=await crypto.subtle.sign(e.signing,n,r);return new Uint8Array(o)}var we=[["verify"],["sign"]];function Nt(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:we}}function ne(e,t){let n={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:n,signing:t?{...n,saltLength:t}:n,usages:we,minRsaBits:2048}}function kt(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:we}}function un(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:we}}function Dt(e){let r={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:r,signing:r,usages:we}}var Yi=on({HS256:Nt(256),HS384:Nt(384),HS512:Nt(512),RS256:ne(256),RS384:ne(384),RS512:ne(512),PS256:ne(256,32),PS384:ne(384,48),PS512:ne(512,64),ES256:kt("P-256",256),ES384:kt("P-384",384),ES512:kt("P-521",512),EdDSA:un(),Ed25519:un(),"ML-DSA-44":Dt(44),"ML-DSA-65":Dt(65),"ML-DSA-87":Dt(87)});function pn(e){let t=typeof e=="string"?Yi[e]:void 0;if(!t)throw new q(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}var Fe=e=>Math.floor(e.getTime()/1e3),Qi={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Zi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function dn(e){let t=Zi.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=Math.round(r*Qi[t[3][0].toLowerCase()]);return t[1]==="-"||t[4]==="ago"?-n:n}function Lt(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function Mt(e,t){return typeof e=="number"?Lt(t,e):e instanceof Date?Lt(t,Fe(e)):Fe(new Date)+dn(e)}var O,je=class{constructor(t){L(this,O);if(!Tt(t))throw new TypeError("JWT Claims Set MUST be an object");U(this,O,structuredClone(t))}data(){return De.encode(JSON.stringify(R(this,O)))}get iss(){return R(this,O).iss}set iss(t){R(this,O).iss=t}get sub(){return R(this,O).sub}set sub(t){R(this,O).sub=t}get aud(){return R(this,O).aud}set aud(t){R(this,O).aud=t}set jti(t){R(this,O).jti=t}set nbf(t){R(this,O).nbf=Mt(t,"setNotBefore")}set exp(t){R(this,O).exp=Mt(t,"setExpirationTime")}set iat(t){t===void 0?R(this,O).iat=Fe(new Date):typeof t=="string"?R(this,O).iat=Lt("setIssuedAt",Fe(new Date)+dn(t)):R(this,O).iat=Mt(t,"setIssuedAt")}};O=new WeakMap;function Be(e){return e?.b64===!1&&Array.isArray(e.crit)&&e.crit.includes("b64")}async function mn(e,t){let{protectedHeader:r,unprotectedHeader:n}=e;if(!r&&!n)throw new K("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Vr(r,n))throw new K("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...r,...n};an(K,r);let s=cn(K,sn,e.crit,r,o),i=!0;if(s.includes("b64")&&(i=r.b64,typeof i!="boolean"))throw new K('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=o;if(typeof a!="string"||!a)throw new K('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=pn(a),u,f;if(i){let J=e.encoded??=[];J[0]??=Ue(e.payload),J[1]??=Me(J[0]),u=J[0],f=J[1]}else f=e.payload,u="";let m,S;r?(m=Ue(JSON.stringify(r)),S=Me(m)):(m="",S=new Uint8Array);let g=Ur(S,Me("."),f),z=await nn(l,t,"sign"),v=await ln(l,z,g),M={signature:Ue(v),payload:u};return r&&(M.protected=m),n&&(M.header=n),M}var Ee,oe,se,We=class{constructor(t){L(this,Ee);L(this,oe);L(this,se);if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");U(this,Ee,t)}setProtectedHeader(t){return Ot(R(this,oe),"setProtectedHeader"),U(this,oe,t),this}setUnprotectedHeader(t){return Ot(R(this,se),"setUnprotectedHeader"),U(this,se,t),this}async sign(t,r){return mn({payload:R(this,Ee),protectedHeader:R(this,oe),unprotectedHeader:R(this,se),crit:r?.crit},t)}};Ee=new WeakMap,oe=new WeakMap,se=new WeakMap;var ie,Se,qe=class{constructor(t){L(this,ie);L(this,Se);U(this,ie,new We(t))}setProtectedHeader(t){return R(this,ie).setProtectedHeader(t),U(this,Se,t),this}async sign(t,r){if(Be(R(this,Se)))throw new TypeError("use the flattened module for creating JWS with b64: false");let n=await R(this,ie).sign(t,r);return`${n.protected}.${n.payload}.${n.signature}`}};ie=new WeakMap,Se=new WeakMap;var ae,_,Re=class{constructor(t={}){L(this,ae);L(this,_);U(this,_,new je(t))}setIssuer(t){return R(this,_).iss=t,this}setSubject(t){return R(this,_).sub=t,this}setAudience(t){return R(this,_).aud=t,this}setJti(t){return R(this,_).jti=t,this}setNotBefore(t){return R(this,_).nbf=t,this}setExpirationTime(t){return R(this,_).exp=t,this}setIssuedAt(t){return R(this,_).iat=t,this}setProtectedHeader(t){return U(this,ae,t),this}async sign(t,r){let n=new qe(R(this,_).data());if(n.setProtectedHeader(R(this,ae)),Be(R(this,ae)))throw new ye("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};ae=new WeakMap,_=new WeakMap;import{createHmac as na,createPrivateKey as oa,randomBytes as sa}from"node:crypto";import{existsSync as ia,readFileSync as hn,writeFileSync as yn}from"node:fs";import{basename as wn,extname as aa,resolve as _t}from"node:path";import{isPromise as ca}from"node:util/types";import{extract as la}from"tar";function X(e){console.log(JSON.stringify(e,null,2))}async function Ft(e,t,r){let n=t.source,o=Ke(n);if(!o)return;console.log("Saving source code...");let s=await e.createAttachment({data:o,filename:wn(n),contentType:da(n)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:s});console.log("Success! New bot version: "+i.meta?.versionId)}async function jt(e,t,r){let n=t.dist??t.source,o=Ke(n);if(!o)return;console.log("Deploying bot...");let s=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:o,filename:wn(n)});if(console.log("Deploy result: "+s.issue?.[0]?.details?.text),!ea(s))throw new Error(`Bot deploy failed: ${ta(s)}`)}async function Bt(e,t,r,n,o,s,i){let a={name:t,description:"",runtimeVersion:s},l=await e.post("admin/projects/"+r+"/bot",a),u=await e.readResource("Bot",l.id),f={name:t,id:l.id,source:n,dist:o};await Ft(e,f,u),await jt(e,f,u),console.log(`Success! Bot created: ${u.id}`),i&&ua(f)}function En(e){let t=new RegExp("^"+pa(e).replaceAll(String.raw`\*`,".*")+"$"),r=G()?.bots?.filter(n=>t.test(n.name));return r||[]}function B(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 C(e,t){yn(_t(e),JSON.stringify(t,void 0,2),"utf-8")}function G(e,t){let r=B(e,t),n=Ke(r);if(n)return JSON.parse(n)}function Sn(e){let t=Ke(B(e,{server:!0}));if(t)return JSON.parse(t)}function Ke(e){let t=_t(e);return ia(t)?hn(t,"utf8"):""}function ua(e){let t=G()??{};t.bots||(t.bots=[]),t.bots.push(e),yn("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function pa(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Rn(e){let n=0,o=0;return la({cwd:e,filter:(s,i)=>{if(n++,n>100)throw new Error("Tar extractor reached max number of files");if(o+=i.size,o>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Wt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function da(e){let t=aa(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?Ut.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?Ut.TYPESCRIPT:Ut.TEXT}function Ge(e,t){let r=new W(e),n={name:e,...t};return r.setObject("options",n),n}function An(e){return new W(e).getObject("options")}async function bn(e,t){let r={typ:"JWT",alg:gn.HS256},n=Math.floor(Date.now()/1e3),o={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:n,iat:n,exp:n+604800},s=fn(JSON.stringify(r)),i=fn(JSON.stringify(o)),a=`${s}.${i}`,l=na("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Pn(e,t){let r=oa(hn(_t(t.privateKeyPath))),n=await new Re({}).setProtectedHeader({typ:"JWT",alg:gn.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(sa(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(n)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var h=class extends ra{action(t){let r=ma(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 ma(e,t){return async r=>{let n=e.registeredArguments.length,o=r.slice(0,n);o[n]=e.optsWithGlobals();try{let s=t(...o);ca(s)&&await s}finally{e.resetOptionDefaults()}}}var On=new h("status").aliases(["info","list","ls"]),xn=new h("ping"),$n=new h("push"),Nn=new h("reload-config"),kn=new h("upgrade"),Dn=new h("stats"),Y=new h("agent");y(Y,On);y(Y,xn);y(Y,$n);y(Y,Nn);y(Y,kn);y(Y,Dn);On.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 Ve("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await He({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let n=Ln(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:n.version,connectionStatus:n.status,statusLastUpdated:n.lastUpdated??"N/A"}}})});xn.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 n=await A(r),o=await Mn(n,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 n.pushToAgent(o,e,`PING ${s}`,Tn.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});$n.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",Tn.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,n)=>{let o=await A(n),s=await Mn(o,r,n),i;try{i=await o.pushToAgent(s,{reference:`Device/${e}`},t,n.contentType,n.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});Nn.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 Ve("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await He({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});kn.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 Ve("--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 He({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:n=>({id:n.agent.id,name:n.agent.name,version:t.agentVersion??"latest"})})});Dn.description("Get runtime statistics for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) to get stats for. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to get stats for. Mutually exclusive with [agentIds...] arg").addOption(new Ve("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await He({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:n}=Ln(r.result,{required:["stats"]}),o;try{o=JSON.parse(n)}catch(s){console.error(`Failed to parse stats for agent ${r.agent.id}: ${ya(s)}`)}return{id:r.agent.id,name:r.agent.name,stats:o}},renderSuccessfulRows:r=>{for(let n=0;n<r.length;n++)n>0&&console.info(),wa(r[n])}})});var In=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function vn(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function Cn(e){return e?Object.entries(e).filter(([,t])=>t?.rtt).map(([t,r])=>({name:t,count:r.rtt.count,pending:r.rtt.pendingCount,"min (ms)":r.rtt.min,"avg (ms)":r.rtt.average,"max (ms)":r.rtt.max,"p50 (ms)":r.rtt.p50,"p95 (ms)":r.rtt.p95,"p99 (ms)":r.rtt.p99})):[]}function wa(e){let t=e.name?`${e.name} (${e.id})`:e.id;if(console.info(`Agent: ${t}`),!e.stats){console.info(" (stats unavailable)");return}let r={};for(let i of In)r[i]=vn(e.stats[i]);let n=new Set([...In,"channelStats","clientStats"]);for(let[i,a]of Object.entries(e.stats))n.has(i)||(r[i]=vn(a));console.table(r);let o=Cn(e.stats.channelStats);o.length&&(console.info("Channel Stats:"),console.table(o));let s=Cn(e.stats.clientStats);s.length&&(console.info("Client Stats:"),console.table(s))}async function He({operation:e,agentIds:t,options:r,params:n={},parseSuccessfulResponse:o,renderSuccessfulRows:s}){let i=Aa(t,r),a=await A(r),l=i.type==="criteria"?i.criteria:`Agent?_id=${i.ids.join(",")}`,u=new URLSearchParams(l.split("?")[1]);for(let[v,M]of Object.entries(n))u.append(v,M.toString());let f;try{let v=a.fhirUrl("Agent",e);v.search=u.toString(),f=await a.get(v,{cache:"reload"})}catch(v){throw new Error(`Operation '${e}' failed`,{cause:v})}if(r.output==="json"){console.info(JSON.stringify(f,null,2));return}let m=[],S=[];switch(f.resourceType){case"Bundle":{let v=Ea(f);for(let M of v)M.result.resourceType==="Parameters"||ga(M.result)?m.push(M):S.push(M);break}case"Parameters":case"OperationOutcome":{let v=await a.searchOne("Agent",u,{cache:"reload"});if(!v)throw new Error("Agent not found");f.resourceType==="Parameters"?m.push({agent:v,result:f}):S.push({agent:v,result:f});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(f)}`)}let g=[];for(let v of m){let M=o(v);g.push(M)}let z=[];for(let v of S){let J=v.result.issue?.[0],Pi={id:v.agent.id,name:v.agent.name,severity:J.severity,code:J.code,details:J.details?.text??"No details to show"};z.push(Pi)}console.info(`
2
+ var wi=Object.create;var dt=Object.defineProperty;var Ei=Object.getOwnPropertyDescriptor;var Si=Object.getOwnPropertyNames;var Ri=Object.getPrototypeOf,bi=Object.prototype.hasOwnProperty;var br=e=>{throw TypeError(e)};var Ai=(e,t,r)=>t in e?dt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Pi=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Si(t))!bi.call(e,o)&&o!==r&&dt(e,o,{get:()=>t[o],enumerable:!(n=Ei(t,o))||n.enumerable});return e};var Ar=(e,t,r)=>(r=e!=null?wi(Ri(e)):{},Pi(t||!e||!e.__esModule?dt(r,"default",{value:e,enumerable:!0}):r,e));var x=(e,t,r)=>Ai(e,typeof t!="symbol"?t+"":t,r),Pr=(e,t,r)=>t.has(e)||br("Cannot "+r);var mt=(e,t,r)=>(Pr(e,t,"read from private field"),r?r.call(e):t.get(e)),Ir=(e,t,r)=>t.has(e)?br("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),vr=(e,t,r,n)=>(Pr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var te=w((Hf,kn)=>{"use strict";var ja="2.0.0",Ba=Number.MAX_SAFE_INTEGER||9007199254740991,qa=16,Wa=250,Ka=["major","premajor","minor","preminor","patch","prepatch","prerelease"];kn.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:qa,MAX_SAFE_BUILD_LENGTH:Wa,MAX_SAFE_INTEGER:Ba,RELEASE_TYPES:Ka,SEMVER_SPEC_VERSION:ja,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var ge=w((Jf,Dn)=>{"use strict";var Ga=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};Dn.exports=Ga});var re=w((j,Mn)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Ut,MAX_SAFE_BUILD_LENGTH:Va,MAX_LENGTH:Ha}=te(),Ja=ge();j=Mn.exports={};var Xa=j.re=[],za=j.safeRe=[],p=j.src=[],Ya=j.safeSrc=[],d=j.t={},Qa=0,_t="[a-zA-Z0-9-]",Za=[["\\s",1],["\\d",Ha],[_t,Va]],ec=e=>{for(let[t,r]of Za)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=ec(t),o=Qa++;Ja(e,o,t),d[e]=o,p[o]=t,Ya[o]=n,Xa[o]=new RegExp(t,r?"g":void 0),za[o]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${_t}*`);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",`${_t}+`);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,${Ut}})(?:\\.(\\d{1,${Ut}}))?(?:\\.(\\d{1,${Ut}}))?`);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);j.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);j.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);j.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 _e=w((Xf,Ln)=>{"use strict";var tc=Object.freeze({loose:!0}),rc=Object.freeze({}),nc=e=>e?typeof e!="object"?tc:e:rc;Ln.exports=nc});var Ft=w((zf,Fn)=>{"use strict";var Un=/^[0-9]+$/,_n=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=Un.test(e),n=Un.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},oc=(e,t)=>_n(t,e);Fn.exports={compareIdentifiers:_n,rcompareIdentifiers:oc}});var T=w((Yf,Bn)=>{"use strict";var Fe=ge(),{MAX_LENGTH:jn,MAX_SAFE_INTEGER:je}=te(),{safeRe:Be,t:qe}=re(),sc=_e(),{compareIdentifiers:jt}=Ft(),ic=(e,t)=>{let r=t.split(".");if(r.length>e.length)return!1;for(let n=0;n<r.length;n++)if(jt(e[n],r[n])!==0)return!1;return!0},Bt=class e{constructor(t,r){if(r=sc(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>jn)throw new TypeError(`version is longer than ${jn} characters`);Fe("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?Be[qe.LOOSE]:Be[qe.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>je||this.major<0)throw new TypeError("Invalid major version");if(this.minor>je||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>je||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){let s=+o;if(s>=0&&s<je)return s}return o}):this.prerelease=[],this.build=n[5]?n[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(Fe("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)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}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 n=this.prerelease[r],o=t.prerelease[r];if(Fe("prerelease compare",r,n,o),n===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(n===void 0)return-1;if(n===o)continue;return jt(n,o)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],o=t.build[r];if(Fe("build compare",r,n,o),n===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(n===void 0)return-1;if(n===o)continue;return jt(n,o)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let o=`-${r}`.match(this.options.loose?Be[qe.PRERELEASELOOSE]:Be[qe.PRERELEASE]);if(!o||o[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,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);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 o=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[o];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(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(r){let s=[r,o];if(n===!1&&(s=[r]),ic(this.prerelease,r)){let i=this.prerelease[r.split(".").length];isNaN(i)&&(this.prerelease=s)}else 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}};Bn.exports=Bt});var V=w((Qf,Wn)=>{"use strict";var qn=T(),ac=(e,t,r=!1)=>{if(e instanceof qn)return e;try{return new qn(e,t)}catch(n){if(!r)return null;throw n}};Wn.exports=ac});var Gn=w((Zf,Kn)=>{"use strict";var cc=V(),lc=(e,t)=>{let r=cc(e,t);return r?r.version:null};Kn.exports=lc});var Hn=w((eg,Vn)=>{"use strict";var uc=V(),pc=(e,t)=>{let r=uc(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Vn.exports=pc});var zn=w((tg,Xn)=>{"use strict";var Jn=T(),dc=(e,t,r,n,o)=>{typeof r=="string"&&(o=n,n=r,r=void 0);try{return new Jn(e instanceof Jn?e.version:e,r).inc(t,n,o).version}catch{return null}};Xn.exports=dc});var Zn=w((rg,Qn)=>{"use strict";var Yn=V(),mc=(e,t)=>{let r=Yn(e,null,!0),n=Yn(t,null,!0),o=r.compare(n);if(o===0)return null;let s=o>0,i=s?r:n,a=s?n:r,l=!!i.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}let m=l?"pre":"";return r.major!==n.major?m+"major":r.minor!==n.minor?m+"minor":r.patch!==n.patch?m+"patch":"prerelease"};Qn.exports=mc});var to=w((ng,eo)=>{"use strict";var fc=T(),gc=(e,t)=>new fc(e,t).major;eo.exports=gc});var no=w((og,ro)=>{"use strict";var hc=T(),yc=(e,t)=>new hc(e,t).minor;ro.exports=yc});var so=w((sg,oo)=>{"use strict";var wc=T(),Ec=(e,t)=>new wc(e,t).patch;oo.exports=Ec});var ao=w((ig,io)=>{"use strict";var Sc=V(),Rc=(e,t)=>{let r=Sc(e,t);return r&&r.prerelease.length?r.prerelease:null};io.exports=Rc});var k=w((ag,lo)=>{"use strict";var co=T(),bc=(e,t,r)=>new co(e,r).compare(new co(t,r));lo.exports=bc});var po=w((cg,uo)=>{"use strict";var Ac=k(),Pc=(e,t,r)=>Ac(t,e,r);uo.exports=Pc});var fo=w((lg,mo)=>{"use strict";var Ic=k(),vc=(e,t)=>Ic(e,t,!0);mo.exports=vc});var We=w((ug,ho)=>{"use strict";var go=T(),Cc=(e,t,r)=>{let n=new go(e,r),o=new go(t,r);return n.compare(o)||n.compareBuild(o)};ho.exports=Cc});var wo=w((pg,yo)=>{"use strict";var Tc=We(),Oc=(e,t)=>e.sort((r,n)=>Tc(r,n,t));yo.exports=Oc});var So=w((dg,Eo)=>{"use strict";var xc=We(),$c=(e,t)=>e.sort((r,n)=>xc(n,r,t));Eo.exports=$c});var he=w((mg,Ro)=>{"use strict";var Nc=k(),kc=(e,t,r)=>Nc(e,t,r)>0;Ro.exports=kc});var Ke=w((fg,bo)=>{"use strict";var Dc=k(),Mc=(e,t,r)=>Dc(e,t,r)<0;bo.exports=Mc});var qt=w((gg,Ao)=>{"use strict";var Lc=k(),Uc=(e,t,r)=>Lc(e,t,r)===0;Ao.exports=Uc});var Wt=w((hg,Po)=>{"use strict";var _c=k(),Fc=(e,t,r)=>_c(e,t,r)!==0;Po.exports=Fc});var Ge=w((yg,Io)=>{"use strict";var jc=k(),Bc=(e,t,r)=>jc(e,t,r)>=0;Io.exports=Bc});var Ve=w((wg,vo)=>{"use strict";var qc=k(),Wc=(e,t,r)=>qc(e,t,r)<=0;vo.exports=Wc});var Kt=w((Eg,Co)=>{"use strict";var Kc=qt(),Gc=Wt(),Vc=he(),Hc=Ge(),Jc=Ke(),Xc=Ve(),zc=(e,t,r,n)=>{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 Kc(e,r,n);case"!=":return Gc(e,r,n);case">":return Vc(e,r,n);case">=":return Hc(e,r,n);case"<":return Jc(e,r,n);case"<=":return Xc(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Co.exports=zc});var Oo=w((Sg,To)=>{"use strict";var Yc=T(),Qc=V(),{safeRe:He,t:Je}=re(),Zc=(e,t)=>{if(e instanceof Yc)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?He[Je.COERCEFULL]:He[Je.COERCE]);else{let l=t.includePrerelease?He[Je.COERCERTLFULL]:He[Je.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 n=r[2],o=r[3]||"0",s=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Qc(`${n}.${o}.${s}${i}${a}`,t)};To.exports=Zc});var $o=w((Rg,xo)=>{"use strict";var el=V(),tl=te(),rl=T(),nl=(e,t,r)=>{if(!tl.RELEASE_TYPES.includes(t))return null;let n=ol(e,r);return n&&sl(n,t)},ol=(e,t)=>{let r=e instanceof rl?e.version:e;return el(r,t)},sl=(e,t)=>{if(il(t))return e.version;switch(e.prerelease=[],t){case"major":e.minor=0,e.patch=0;break;case"minor":e.patch=0;break}return e.format()},il=e=>e.startsWith("pre");xo.exports=nl});var ko=w((bg,No)=>{"use strict";var Gt=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 o=this.map.keys().next().value;this.delete(o)}this.map.set(t,r)}return this}};No.exports=Gt});var D=w((Ag,Uo)=>{"use strict";var al=/\s+/g,Vt=class e{constructor(t,r){if(r=ll(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof Ht)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(al," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(o=>!Mo(o[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let o of this.set)if(o.length===1&&wl(o[0])){this.set=[o];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 n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(yl,"");let n=((this.options.includePrerelease&&gl)|(this.options.loose&&hl))+":"+t,o=Do.get(n);if(o)return o;let s=this.options.loose,i=s?$[O.HYPHENRANGELOOSE]:$[O.HYPHENRANGE];t=t.replace(i,Ol(this.options.includePrerelease)),A("hyphen replace",t),t=t.replace($[O.COMPARATORTRIM],dl),A("comparator trim",t),t=t.replace($[O.TILDETRIM],ml),A("tilde trim",t),t=t.replace($[O.CARETTRIM],fl),A("caret trim",t);let a=t.split(" ").map(f=>El(f,this.options)).join(" ").split(/\s+/).map(f=>Tl(f,this.options));s&&(a=a.filter(f=>(A("loose invalid filter",f,this.options),!!f.match($[O.COMPARATORLOOSE])))),A("range list",a);let l=new Map,u=a.map(f=>new Ht(f,this.options));for(let f of u){if(Mo(f))return[f];l.set(f.value,f)}l.size>1&&l.has("")&&l.delete("");let m=[...l.values()];return Do.set(n,m),m}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Lo(n,r)&&t.set.some(o=>Lo(o,r)&&n.every(s=>o.every(i=>s.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new ul(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(xl(this.set[r],t,this.options))return!0;return!1}};Uo.exports=Vt;var cl=ko(),Do=new cl,ll=_e(),Ht=ye(),A=ge(),ul=T(),{safeRe:$,src:pl,t:O,comparatorTrimReplace:dl,tildeTrimReplace:ml,caretTrimReplace:fl}=re(),{FLAG_INCLUDE_PRERELEASE:gl,FLAG_LOOSE:hl}=te(),yl=new RegExp(pl[O.BUILD],"g"),Mo=e=>e.value==="<0.0.0-0",wl=e=>e.value==="",Lo=(e,t)=>{let r=!0,n=e.slice(),o=n.pop();for(;r&&n.length;)r=n.every(s=>o.intersects(s,t)),o=n.pop();return r},El=(e,t)=>(e=e.replace($[O.BUILD],""),A("comp",e,t),e=Al(e,t),A("caret",e),e=Rl(e,t),A("tildes",e),e=Il(e,t),A("xrange",e),e=Cl(e,t),A("stars",e),e),v=e=>!e||e.toLowerCase()==="x"||e==="*",Sl=(e,t,r)=>v(e)&&!v(t)||v(t)&&r&&!v(r),Rl=(e,t)=>e.trim().split(/\s+/).map(r=>bl(r,t)).join(" "),bl=(e,t)=>{let r=t.loose?$[O.TILDELOOSE]:$[O.TILDE],n=t.includePrerelease?"-0":"";return e.replace(r,(o,s,i,a,l)=>{A("tilde",e,o,s,i,a,l);let u;return v(s)?u="":v(i)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:v(a)?u=`>=${s}.${i}.0${n} <${s}.${+i+1}.0-0`:l?(A("replaceTilde pr",l),u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`):u=`>=${s}.${i}.${a} <${s}.${+i+1}.0-0`,A("tilde return",u),u})},Al=(e,t)=>e.trim().split(/\s+/).map(r=>Pl(r,t)).join(" "),Pl=(e,t)=>{A("caret",e,t);let r=t.loose?$[O.CARETLOOSE]:$[O.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(o,s,i,a,l)=>{A("caret",e,o,s,i,a,l);let u;return v(s)?u="":v(i)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:v(a)?s==="0"?u=`>=${s}.${i}.0${n} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${n} <${+s+1}.0.0-0`:l?(A("replaceCaret pr",l),s==="0"?i==="0"?u=`>=${s}.${i}.${a}-${l} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a}-${l} <${+s+1}.0.0-0`):(A("no pr"),s==="0"?i==="0"?u=`>=${s}.${i}.${a} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a} <${+s+1}.0.0-0`),A("caret return",u),u})},Il=(e,t)=>(A("replaceXRanges",e,t),e.split(/\s+/).map(r=>vl(r,t)).join(" ")),vl=(e,t)=>{e=e.trim();let r=t.loose?$[O.XRANGELOOSE]:$[O.XRANGE];return e.replace(r,(n,o,s,i,a,l)=>{if(A("xRange",e,n,o,s,i,a,l),Sl(s,i,a))return e;let u=v(s),m=u||v(i),f=m||v(a),S=f;return o==="="&&S&&(o=""),l=t.includePrerelease?"-0":"",u?o===">"||o==="<"?n="<0.0.0-0":n="*":o&&S?(m&&(i=0),a=0,o===">"?(o=">=",m?(s=+s+1,i=0,a=0):(i=+i+1,a=0)):o==="<="&&(o="<",m?s=+s+1:i=+i+1),o==="<"&&(l="-0"),n=`${o+s}.${i}.${a}${l}`):m?n=`>=${s}.0.0${l} <${+s+1}.0.0-0`:f&&(n=`>=${s}.${i}.0${l} <${s}.${+i+1}.0-0`),A("xRange return",n),n})},Cl=(e,t)=>(A("replaceStars",e,t),e.trim().replace($[O.STAR],"")),Tl=(e,t)=>(A("replaceGTE0",e,t),e.trim().replace($[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),Ol=e=>(t,r,n,o,s,i,a,l,u,m,f,S)=>(v(n)?r="":v(o)?r=`>=${n}.0.0${e?"-0":""}`:v(s)?r=`>=${n}.${o}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,v(u)?l="":v(m)?l=`<${+u+1}.0.0-0`:v(f)?l=`<${u}.${+m+1}.0-0`:S?l=`<=${u}.${m}.${f}-${S}`:e?l=`<${u}.${m}.${+f+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),xl=(e,t,r)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let n=0;n<e.length;n++)if(A(e[n].semver),e[n].semver!==Ht.ANY&&e[n].semver.prerelease.length>0){let o=e[n].semver;if(o.major===t.major&&o.minor===t.minor&&o.patch===t.patch)return!0}return!1}return!0}});var ye=w((Pg,Wo)=>{"use strict";var we=Symbol("SemVer ANY"),zt=class e{static get ANY(){return we}constructor(t,r){if(r=_o(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Xt("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===we?this.value="":this.value=this.operator+this.semver.version,Xt("comp",this)}parse(t){let r=this.options.loose?Fo[jo.COMPARATORLOOSE]:Fo[jo.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Bo(n[2],this.options.loose):this.semver=we}toString(){return this.value}test(t){if(Xt("Comparator.test",t,this.options.loose),this.semver===we||t===we)return!0;if(typeof t=="string")try{t=new Bo(t,this.options)}catch{return!1}return Jt(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 qo(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new qo(this.value,r).test(t.semver):(r=_o(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("=")||Jt(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||Jt(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Wo.exports=zt;var _o=_e(),{safeRe:Fo,t:jo}=re(),Jt=Kt(),Xt=ge(),Bo=T(),qo=D()});var Ee=w((Ig,Ko)=>{"use strict";var $l=D(),Nl=(e,t,r)=>{try{t=new $l(t,r)}catch{return!1}return t.test(e)};Ko.exports=Nl});var Vo=w((vg,Go)=>{"use strict";var kl=D(),Dl=(e,t)=>new kl(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));Go.exports=Dl});var Jo=w((Cg,Ho)=>{"use strict";var Ml=T(),Ll=D(),Ul=(e,t,r)=>{let n=null,o=null,s=null;try{s=new Ll(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!n||o.compare(i)===-1)&&(n=i,o=new Ml(n,r))}),n};Ho.exports=Ul});var zo=w((Tg,Xo)=>{"use strict";var _l=T(),Fl=D(),jl=(e,t,r)=>{let n=null,o=null,s=null;try{s=new Fl(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!n||o.compare(i)===1)&&(n=i,o=new _l(n,r))}),n};Xo.exports=jl});var Zo=w((Og,Qo)=>{"use strict";var Yt=T(),Bl=D(),Yo=he(),ql=(e,t)=>{e=new Bl(e,t);let r=new Yt("0.0.0");if(e.test(r)||(r=new Yt("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n<e.set.length;++n){let o=e.set[n],s=null;o.forEach(i=>{let a=new Yt(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||Yo(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||Yo(r,s))&&(r=s)}return r&&e.test(r)?r:null};Qo.exports=ql});var ts=w((xg,es)=>{"use strict";var Wl=D(),Kl=(e,t)=>{try{return new Wl(e,t).range||"*"}catch{return null}};es.exports=Kl});var Xe=w(($g,ss)=>{"use strict";var Gl=T(),os=ye(),{ANY:Vl}=os,Hl=D(),Jl=Ee(),rs=he(),ns=Ke(),Xl=Ve(),zl=Ge(),Yl=(e,t,r,n)=>{e=new Gl(e,n),t=new Hl(t,n);let o,s,i,a,l;switch(r){case">":o=rs,s=Xl,i=ns,a=">",l=">=";break;case"<":o=ns,s=zl,i=rs,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Jl(e,t,n))return!1;for(let u=0;u<t.set.length;++u){let m=t.set[u],f=null,S=null;if(m.forEach(g=>{g.semver===Vl&&(g=new os(">=0.0.0")),f=f||g,S=S||g,o(g.semver,f.semver,n)?f=g:i(g.semver,S.semver,n)&&(S=g)}),f.operator===a||f.operator===l||(!S.operator||S.operator===a)&&s(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};ss.exports=Yl});var as=w((Ng,is)=>{"use strict";var Ql=Xe(),Zl=(e,t,r)=>Ql(e,t,">",r);is.exports=Zl});var ls=w((kg,cs)=>{"use strict";var eu=Xe(),tu=(e,t,r)=>eu(e,t,"<",r);cs.exports=tu});var ds=w((Dg,ps)=>{"use strict";var us=D(),ru=(e,t,r)=>(e=new us(e,r),t=new us(t,r),e.intersects(t,r));ps.exports=ru});var fs=w((Mg,ms)=>{"use strict";var nu=Ee(),ou=k();ms.exports=(e,t,r)=>{let n=[],o=null,s=null,i=e.sort((m,f)=>ou(m,f,r));for(let m of i)nu(m,t,r)?(s=m,o||(o=m)):(s&&n.push([o,s]),s=null,o=null);o&&n.push([o,null]);let a=[];for(let[m,f]of n)m===f?a.push(m):!f&&m===i[0]?a.push("*"):f?m===i[0]?a.push(`<=${f}`):a.push(`${m} - ${f}`):a.push(`>=${m}`);let l=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var Ss=w((Lg,Es)=>{"use strict";var gs=D(),er=ye(),{ANY:Qt}=er,Zt=Ee(),tr=k(),su=(e,t,r={})=>{if(e===t)return!0;e=new gs(e,r),t=new gs(t,r);let n=!1;e:for(let o of e.set){for(let s of t.set){let i=au(o,s,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},iu=[new er(">=0.0.0-0")],hs=[new er(">=0.0.0")],au=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Qt){if(t.length===1&&t[0].semver===Qt)return!0;r.includePrerelease?e=iu:e=hs}if(t.length===1&&t[0].semver===Qt){if(r.includePrerelease)return!0;t=hs}let n=new Set,o,s;for(let g of e)g.operator===">"||g.operator===">="?o=ys(o,g,r):g.operator==="<"||g.operator==="<="?s=ws(s,g,r):n.add(g.semver);if(n.size>1)return null;let i;if(o&&s){if(i=tr(o.semver,s.semver,r),i>0)return null;if(i===0&&(o.operator!==">="||s.operator!=="<="))return null}for(let g of n){if(o&&!Zt(g,String(o),r)||s&&!Zt(g,String(s),r))return null;for(let Y of t)if(!Zt(g,String(Y),r))return!1;return!0}let a,l,u,m,f=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,S=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1;f&&f.prerelease.length===1&&s.operator==="<"&&f.prerelease[0]===0&&(f=!1);for(let g of t){if(m=m||g.operator===">"||g.operator===">=",u=u||g.operator==="<"||g.operator==="<=",o){if(S&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===S.major&&g.semver.minor===S.minor&&g.semver.patch===S.patch&&(S=!1),g.operator===">"||g.operator===">="){if(a=ys(o,g,r),a===g&&a!==o)return!1}else if(o.operator===">="&&!g.test(o.semver))return!1}if(s){if(f&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===f.major&&g.semver.minor===f.minor&&g.semver.patch===f.patch&&(f=!1),g.operator==="<"||g.operator==="<="){if(l=ws(s,g,r),l===g&&l!==s)return!1}else if(s.operator==="<="&&!g.test(s.semver))return!1}if(!g.operator&&(s||o)&&i!==0)return!1}return!(o&&u&&!s&&i!==0||s&&m&&!o&&i!==0||S||f)},ys=(e,t,r)=>{if(!e)return t;let n=tr(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},ws=(e,t,r)=>{if(!e)return t;let n=tr(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};Es.exports=su});var nr=w((Ug,As)=>{"use strict";var rr=re(),Rs=te(),cu=T(),bs=Ft(),lu=V(),uu=Gn(),pu=Hn(),du=zn(),mu=Zn(),fu=to(),gu=no(),hu=so(),yu=ao(),wu=k(),Eu=po(),Su=fo(),Ru=We(),bu=wo(),Au=So(),Pu=he(),Iu=Ke(),vu=qt(),Cu=Wt(),Tu=Ge(),Ou=Ve(),xu=Kt(),$u=Oo(),Nu=$o(),ku=ye(),Du=D(),Mu=Ee(),Lu=Vo(),Uu=Jo(),_u=zo(),Fu=Zo(),ju=ts(),Bu=Xe(),qu=as(),Wu=ls(),Ku=ds(),Gu=fs(),Vu=Ss();As.exports={parse:lu,valid:uu,clean:pu,inc:du,diff:mu,major:fu,minor:gu,patch:hu,prerelease:yu,compare:wu,rcompare:Eu,compareLoose:Su,compareBuild:Ru,sort:bu,rsort:Au,gt:Pu,lt:Iu,eq:vu,neq:Cu,gte:Tu,lte:Ou,cmp:xu,coerce:$u,truncate:Nu,Comparator:ku,Range:Du,satisfies:Mu,toComparators:Lu,maxSatisfying:Uu,minSatisfying:_u,minVersion:Fu,validRange:ju,outside:Bu,gtr:qu,ltr:Wu,intersects:Ku,simplifyRange:Gu,subset:Vu,SemVer:cu,re:rr.re,src:rr.src,tokens:rr.t,SEMVER_SPEC_VERSION:Rs.SEMVER_SPEC_VERSION,RELEASE_TYPES:Rs.RELEASE_TYPES,compareIdentifiers:bs.compareIdentifiers,rcompareIdentifiers:bs.rcompareIdentifiers}});import{MEDPLUM_VERSION as cm,normalizeErrorString as Rr}from"@medplum/core";import{CommanderError as hi,Option as lm}from"commander";import um from"dotenv";import{ContentType as Rn,EMPTY as ma,isOk as fa,isUUID as ga,normalizeErrorString as ha}from"@medplum/core";import{Option as Me}from"commander";import{MedplumClient as xi}from"@medplum/core";import{ClientStorage as Ii}from"@medplum/core";import{existsSync as Cr,mkdirSync as vi,readFileSync as Ci,writeFileSync as Ti}from"node:fs";import{homedir as Oi}from"node:os";import{resolve as Tr}from"node:path";var U=class extends Ii{constructor(r){super();x(this,"dirName");x(this,"fileName");this.dirName=Tr(Oi(),".medplum"),this.fileName=Tr(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,n){let o=this.readFile()??{};n?o[r]=n:delete o[r],this.writeFile(o)}getObject(r){let n=this.getString(r);return n?JSON.parse(n):void 0}setObject(r,n){this.setString(r,n?JSON.stringify(n):void 0)}readFile(){if(Cr(this.fileName))return JSON.parse(Ci(this.fileName,"utf8"))}writeFile(r){Cr(this.dirName)||vi(this.dirName),Ti(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function R(e,t=!0){let r=e.profile??"default",n=new U(r),o=n.getObject("options");if(r!=="default"&&!o)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:s,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:m,clientSecret:f}=$i(e,n),S=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await Ni(e.baseUrl,S);let g=new xi({fetch:S,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:n,onUnauthenticated:ki,verbose:e.verbose});return t&&(a?g.setAccessToken(a):m&&f&&(g.setBasicAuth(m,f),o?.authType!=="basic"&&await g.startClientLogin(m,f))),g}function $i(e,t){let r=t.getObject("options"),n=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",o=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,a=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:n,fhirUrlPath:o,accessToken:s,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}async function Ni(e,t){try{let r=new URL("healthcheck",e).toString(),n=await t(r);if(!n.ok)throw new Error(`Healthcheck returned status ${n.status}`);if((await n.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${n}`)}}function ki(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{ContentType as Ct,encodeBase64 as an,isOk as Zi,normalizeErrorString as ea,OAuthSigningAlgorithm as cn}from"@medplum/core";import{Command as ta}from"commander";var ve=new TextEncoder,ft=new TextDecoder,Di=new TextDecoder("utf-8",{fatal:!0}),Pm=2**32;function Or(...e){let t=e.reduce((o,{length:s})=>o+s,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Ce(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}var Te=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Mi(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function xr(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function $r(e,t,r){let n=e.algorithm;if(n.name!==t.name)throw Te(t.name);if(t.hash&&n.hash?.name!==t.hash)throw Te(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw Te(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&n.length!==t.length)throw Te(t.length,"algorithm.length");Mi(e,r)}function Li(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}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 ue=(e,t,...r)=>Li(`Key for the ${e} algorithm must be `,t,...r);var X=class extends Error{constructor(r,n){super(r,n);x(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};x(X,"code","ERR_JOSE_GENERIC");var _=class extends X{constructor(){super(...arguments);x(this,"code","ERR_JOSE_NOT_SUPPORTED")}};x(_,"code","ERR_JOSE_NOT_SUPPORTED");var M=class extends X{constructor(){super(...arguments);x(this,"code","ERR_JWS_INVALID")}};x(M,"code","ERR_JWS_INVALID");var pe=class extends X{constructor(){super(...arguments);x(this,"code","ERR_JWT_INVALID")}};x(pe,"code","ERR_JWT_INVALID");var Nr,kr,gt=class extends(kr=X,Nr=Symbol.asyncIterator,kr){constructor(r="multiple matching keys found in the JSON Web Key Set",n){super(r,n);x(this,Nr,async function*(){});x(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};x(gt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var ht=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Ui=e=>e?.[Symbol.toStringTag]==="KeyObject",Dr=e=>ht(e)||Ui(e);function Mr(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,r=[];for(let n=0;n<e.length;n+=t)r.push(String.fromCharCode.apply(null,e.subarray(n,n+t)));return btoa(r.join(""))}function Lr(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var yt="The input to be decoded is not correctly encoded.";function Ur(e){if(Uint8Array.fromBase64)try{return Uint8Array.fromBase64(typeof e=="string"?e:ft.decode(e),{alphabet:"base64url"})}catch(r){throw new TypeError(yt,{cause:r})}let t=e;if(t instanceof Uint8Array&&(t=ft.decode(t)),t.includes("+")||t.includes("/"))throw new TypeError(yt);t=t.replace(/-/g,"+").replace(/_/g,"/");try{return Lr(t)}catch{throw new TypeError(yt)}}function Oe(e){let t=e;return typeof t=="string"&&(t=ve.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):Mr(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Q(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function _r(e,t){if(e!==void 0)throw new TypeError(`${t} can only be called once`)}async function Fr(e,t){if(t.kty==="RSA"&&"oth"in t&&t.oth!==void 0)throw new _('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');if(!e.kty.includes(t.kty))throw new _('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,n=!!(t.d||t.priv),o={...t};return o.kty!=="AKP"&&delete o.alg,delete o.use,crypto.subtle.importKey("jwk",o,r,t.ext??!n,t.key_ops??e.usages[n?1:0])}function _i(e){return{__proto__:null,...e}}function jr(e){let t=_i(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,n=Array.isArray(r)?[...r]:void 0;if(!n||n.some(o=>typeof o!="string")||new Set(n).size!==n.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=n}return t}var wt=e=>e[Symbol.toStringTag],Fi=(e,t,r)=>{let{alg:n}=e;if(t.use!==void 0){let o=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==o)throw new TypeError(`Invalid key for this operation, its "use" must be "${o}" when present`)}if(t.alg!==void 0&&t.alg!==n)throw new TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(t.key_ops)){let o=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(o&&!t.key_ops.includes(o))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}};function ji(e,t,r){let{alg:n,secret:o}=e,s=r==="decrypt"||r==="sign";if(o&&t instanceof Uint8Array)return[qr,t];if(Q(t)){let i=jr(t);if(typeof i.kty!="string")throw new TypeError(o?ue(n,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):ue(n,t,"CryptoKey","KeyObject","JSON Web Key"));if(!(o?i.kty==="oct"&&typeof i.k=="string":i.kty!=="oct"&&(s?i.kty==="AKP"&&typeof i.priv=="string"||typeof i.d=="string":i.d===void 0&&i.priv===void 0)))throw new TypeError(o?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${s?"private":"public"} JWK`);return Fi(e,i,r),[Gr,t,i]}if(!Dr(t))throw new TypeError(o?ue(n,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):ue(n,t,"CryptoKey","KeyObject","JSON Web Key"));if(o){if(t.type!=="secret")throw new TypeError(`${wt(t)} instances for symmetric algorithms must be of type "secret"`)}else{if(t.type==="secret")throw new TypeError(`${wt(t)} instances for asymmetric algorithms must not be of type "secret"`);let i=s?"private":"public";if((t.type==="public"||t.type==="private")&&t.type!==i){let a=r==="sign"?"signing":r==="verify"?"verifying":`${r.slice(0,-1)}tion`;throw new TypeError(`${wt(t)} instances for asymmetric algorithm ${a} must be of type "${i}"`)}}return ht(t)?[Wr,t]:[Kr,t]}var qr=0,Wr=1,Kr=2,Gr=3,Et,Bi={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function xe(e,t,r){Et||=new WeakMap;let n=Et.get(e);return r&&(n?n[t]=r:Et.set(e,{[t]:r})),r??n?.[t]}var Br=async(e,t,r)=>xe(e,r.alg)??xe(e,r.alg,await Fr(r,{...t,alg:r.alg})),qi=(e,t)=>{let r=xe(e,t.alg);if(r)return r;let n=e.type==="public",o=t.usages[n?0:1],{asymmetricKeyType:s}=e,i=Bi[e.asymmetricKeyDetails?.namedCurve],a=t.resolve?.({crv:i,asymmetricKeyType:s})??t.subtle;return xe(e,t.alg,e.toCryptoKey(a,n,o))};async function Vr(e,t,r){let n=ji(e,t,r);switch(n[0]){case qr:case Wr:return n[1];case Gr:{let o=n[1],s=n[2];if(s.kty==="oct")return Ur(s.k);if(!Object.isFrozen(o)){let{key_ops:i}=o;Array.isArray(i)&&Object.freeze(i),Object.freeze(o)}return Br(o,s,e)}case Kr:{let o=n[1];return o.type==="secret"?o.export():"toCryptoKey"in o&&typeof o.toCryptoKey=="function"?qi(o,e):Br(o,o.export({format:"jwk"}),e)}}}function Hr(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var Jr={__proto__:null,b64:!0};function Xr(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function zr(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return[];if(!Array.isArray(n.crit)||n.crit.length===0||n.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?t:{__proto__:null,...r,...t};for(let i of n.crit){if(!(i in s))throw new _(`Extension Header Parameter "${i}" is not recognized`);if(!Object.hasOwn(o,i)||o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s[i]&&(!Object.hasOwn(n,i)||n[i]===void 0))throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return n.crit}function Yr(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!="boolean")throw new M('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function Qr(e,t){let r,n;try{r=JSON.stringify(t),n=JSON.parse(r)}catch(o){throw new e("JOSE Header is not valid JSON",{cause:o})}if(!Q(n))throw new e("JOSE Header is not a JSON object");return[n,r]}async function Wi(e,t,r){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,e.subtle,!1,[r]):($r(t,e.subtle,r),e.minRsaBits&&xr(e.alg,t),t)}async function Zr(e,t,r){let n=await Wi(e,t,"sign"),o=await crypto.subtle.sign(e.signing,n,r);return new Uint8Array(o)}var de=[["verify"],["sign"]];function St(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:de}}function Z(e,t){let n={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:n,signing:t?{...n,saltLength:t}:n,usages:de,minRsaBits:2048}}function Rt(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:de}}function en(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:de}}function bt(e){let r={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:r,signing:r,usages:de}}var Ki=Hr({HS256:St(256),HS384:St(384),HS512:St(512),RS256:Z(256),RS384:Z(384),RS512:Z(512),PS256:Z(256,32),PS384:Z(384,48),PS512:Z(512,64),ES256:Rt("P-256",256),ES384:Rt("P-384",384),ES512:Rt("P-521",512),EdDSA:en(),Ed25519:en(),"ML-DSA-44":bt(44),"ML-DSA-65":bt(65),"ML-DSA-87":bt(87)});function tn(e){let t=typeof e=="string"?Ki[e]:void 0;if(!t)throw new _(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}var $e=e=>Math.floor(e.getTime()/1e3),Gi={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Vi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function At(){throw new TypeError("Invalid time period format")}function rn(e){typeof e!="string"&&At();let t=Vi.exec(e);(!t||t[4]&&t[1])&&At();let r=parseFloat(t[2]),n=Math.round(r*Gi[t[3][0].toLowerCase()]);return Number.isFinite(n)||At(),t[1]==="-"||t[4]==="ago"?-n:n}function vt(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function Pt(e,t){if(typeof t!="string")throw new TypeError(`"${e}" claim must be a string`)}function Hi(e){if(typeof e!="string"&&(!Array.isArray(e)||Array.from(e).some(t=>typeof t!="string")))throw new TypeError('"aud" claim must be a string or an array of strings')}function It(e,t){return typeof e=="number"?vt(t,e):e instanceof Date?vt(t,$e(e)):$e(new Date)+rn(e)}var nn;function K(e){return nn.get(e)}function on(e){let t=K(e);for(let r of["iat","nbf","exp"]){let n=t[r];if(typeof n=="number"&&!Number.isFinite(n))throw new TypeError(`"${r}" claim must be a finite number`)}return ve.encode(JSON.stringify(t))}var Ne=class{constructor(t={}){if(!Q(t))throw new TypeError("JWT Claims Set MUST be an object");(nn||=new WeakMap).set(this,structuredClone(t))}setIssuer(t){return Pt("iss",t),K(this).iss=t,this}setSubject(t){return Pt("sub",t),K(this).sub=t,this}setAudience(t){return Hi(t),K(this).aud=t,this}setJti(t){return Pt("jti",t),K(this).jti=t,this}setNotBefore(t){return K(this).nbf=It(t,"setNotBefore"),this}setExpirationTime(t){return K(this).exp=It(t,"setExpirationTime"),this}setIssuedAt(t){let r=K(this);return t===void 0?r.iat=$e(new Date):typeof t=="string"?r.iat=vt("setIssuedAt",$e(new Date)+rn(t)):r.iat=It(t,"setIssuedAt"),this}};function Ji(e){if(e===void 0)return[void 0,""];let t=Qr(M,e);return[t[0],Oe(t[1])]}function Xi(e,t,r){return Xr(M,e),Yr(e,zr(M,Jr,r,e,t))}function zi(e){let t=e.alg;if(typeof t!="string"||!t)throw new M('JWS "alg" (Algorithm) Header Parameter missing or invalid');return tn(t)}async function Yi(e,t,r,n){let o=Or(Ce(e),Ce("."),t),s=await Vr(r,n,"sign");return Oe(await Zr(r,s,o))}async function sn(e,t,r,n,o){let[s,i]=Ji(t);if(!s)throw new M("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");Xi(s,s,r)||o();let l=zi(s),u=Oe(e),m=await Yi(i,Ce(u),l,n);return`${i}.${u}.${m}`}var Qi=Ne,ee,me=class extends Qi{constructor(){super(...arguments);Ir(this,ee)}setProtectedHeader(r){return _r(mt(this,ee),"setProtectedHeader"),vr(this,ee,r),this}async sign(r,n){return sn(on(this),mt(this,ee),n?.crit,r,()=>{throw new pe("JWTs MUST NOT use unencoded payload")})}};ee=new WeakMap;import{createHmac as ra,createPrivateKey as na,randomBytes as oa}from"node:crypto";import{existsSync as sa,readFileSync as ln,writeFileSync as un}from"node:fs";import{basename as pn,extname as ia,resolve as Tt}from"node:path";import{isPromise as aa}from"node:util/types";import{extract as ca}from"tar";function W(e){console.log(JSON.stringify(e,null,2))}async function Ot(e,t,r){let n=t.source,o=ke(n);if(!o)return;console.log("Saving source code...");let s=await e.createAttachment({data:o,filename:pn(n),contentType:pa(n)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:s});console.log("Success! New bot version: "+i.meta?.versionId)}async function xt(e,t,r){let n=t.dist??t.source,o=ke(n);if(!o)return;console.log("Deploying bot...");let s=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:o,filename:pn(n)});if(console.log("Deploy result: "+s.issue?.[0]?.details?.text),!Zi(s))throw new Error(`Bot deploy failed: ${ea(s)}`)}async function $t(e,t,r,n,o,s,i){let a={name:t,description:"",runtimeVersion:s},l=await e.post("admin/projects/"+r+"/bot",a),u=await e.readResource("Bot",l.id),m={name:t,id:l.id,source:n,dist:o};await Ot(e,m,u),await xt(e,m,u),console.log(`Success! Bot created: ${u.id}`),i&&la(m)}function dn(e){let t=new RegExp("^"+ua(e).replaceAll(String.raw`\*`,".*")+"$"),r=F()?.bots?.filter(n=>t.test(n.name));return r||[]}function L(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 I(e,t){un(Tt(e),JSON.stringify(t,void 0,2),"utf-8")}function F(e,t){let r=L(e,t),n=ke(r);if(n)return JSON.parse(n)}function mn(e){let t=ke(L(e,{server:!0}));if(t)return JSON.parse(t)}function ke(e){let t=Tt(e);return sa(t)?ln(t,"utf8"):""}function la(e){let t=F()??{};t.bots||(t.bots=[]),t.bots.push(e),un("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function ua(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function fn(e){let n=0,o=0;return ca({cwd:e,filter:(s,i)=>{if(n++,n>100)throw new Error("Tar extractor reached max number of files");if(o+=i.size,o>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Nt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function pa(e){let t=ia(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?Ct.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?Ct.TYPESCRIPT:Ct.TEXT}function De(e,t){let r=new U(e),n={name:e,...t};return r.setObject("options",n),n}function gn(e){return new U(e).getObject("options")}async function hn(e,t){let r={typ:"JWT",alg:cn.HS256},n=Math.floor(Date.now()/1e3),o={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:n,iat:n,exp:n+604800},s=an(JSON.stringify(r)),i=an(JSON.stringify(o)),a=`${s}.${i}`,l=ra("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function yn(e,t){let r=na(ln(Tt(t.privateKeyPath))),n=await new me({}).setProtectedHeader({typ:"JWT",alg:cn.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(oa(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(n)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var h=class extends ta{action(t){let r=da(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 da(e,t){return async r=>{let n=e.registeredArguments.length,o=r.slice(0,n);o[n]=e.optsWithGlobals();try{let s=t(...o);aa(s)&&await s}finally{e.resetOptionDefaults()}}}var bn=new h("status").aliases(["info","list","ls"]),An=new h("ping"),Pn=new h("push"),In=new h("reload-config"),vn=new h("upgrade"),Cn=new h("stats"),G=new h("agent");y(G,bn);y(G,An);y(G,Pn);y(G,In);y(G,vn);y(G,Cn);bn.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 Me("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Le({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let n=On(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:n.version,connectionStatus:n.status,statusLastUpdated:n.lastUpdated??"N/A"}}})});An.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 n=await R(r),o=await Tn(n,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 n.pushToAgent(o,e,`PING ${s}`,Rn.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});Pn.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",Rn.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,n)=>{let o=await R(n),s=await Tn(o,r,n),i;try{i=await o.pushToAgent(s,{reference:`Device/${e}`},t,n.contentType,n.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});In.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 Me("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Le({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});vn.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 Me("--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 Le({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:n=>({id:n.agent.id,name:n.agent.name,version:t.agentVersion??"latest"})})});Cn.description("Get runtime statistics for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) to get stats for. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to get stats for. Mutually exclusive with [agentIds...] arg").addOption(new Me("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Le({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:n}=On(r.result,{required:["stats"]}),o;try{o=JSON.parse(n)}catch(s){console.error(`Failed to parse stats for agent ${r.agent.id}: ${ha(s)}`)}return{id:r.agent.id,name:r.agent.name,stats:o}},renderSuccessfulRows:r=>{for(let n=0;n<r.length;n++)n>0&&console.info(),ya(r[n])}})});var wn=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function En(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function Sn(e){return e?Object.entries(e).filter(([,t])=>t?.rtt).map(([t,r])=>({name:t,count:r.rtt.count,pending:r.rtt.pendingCount,"min (ms)":r.rtt.min,"avg (ms)":r.rtt.average,"max (ms)":r.rtt.max,"p50 (ms)":r.rtt.p50,"p95 (ms)":r.rtt.p95,"p99 (ms)":r.rtt.p99})):[]}function ya(e){let t=e.name?`${e.name} (${e.id})`:e.id;if(console.info(`Agent: ${t}`),!e.stats){console.info(" (stats unavailable)");return}let r={};for(let i of wn)r[i]=En(e.stats[i]);let n=new Set([...wn,"channelStats","clientStats"]);for(let[i,a]of Object.entries(e.stats))n.has(i)||(r[i]=En(a));console.table(r);let o=Sn(e.stats.channelStats);o.length&&(console.info("Channel Stats:"),console.table(o));let s=Sn(e.stats.clientStats);s.length&&(console.info("Client Stats:"),console.table(s))}async function Le({operation:e,agentIds:t,options:r,params:n={},parseSuccessfulResponse:o,renderSuccessfulRows:s}){let i=Ra(t,r),a=await R(r),l=i.type==="criteria"?i.criteria:`Agent?_id=${i.ids.join(",")}`,u=new URLSearchParams(l.split("?")[1]);for(let[C,q]of Object.entries(n))u.append(C,q.toString());let m;try{let C=a.fhirUrl("Agent",e);C.search=u.toString(),m=await a.get(C,{cache:"reload"})}catch(C){throw new Error(`Operation '${e}' failed`,{cause:C})}if(r.output==="json"){console.info(JSON.stringify(m,null,2));return}let f=[],S=[];switch(m.resourceType){case"Bundle":{let C=wa(m);for(let q of C)q.result.resourceType==="Parameters"||fa(q.result)?f.push(q):S.push(q);break}case"Parameters":case"OperationOutcome":{let C=await a.searchOne("Agent",u,{cache:"reload"});if(!C)throw new Error("Agent not found");m.resourceType==="Parameters"?f.push({agent:C,result:m}):S.push({agent:C,result:m});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(m)}`)}let g=[];for(let C of f){let q=o(C);g.push(q)}let Y=[];for(let C of S){let pt=C.result.issue?.[0],yi={id:C.agent.id,name:C.agent.name,severity:pt.severity,code:pt.code,details:pt.details?.text??"No details to show"};Y.push(yi)}console.info(`
3
3
  ${g.length} successful response(s):
4
- `),s?g.length?s(g):console.info("No successful responses received"):console.table(g.length?g:"No successful responses received"),console.info(),z.length&&(console.info(`${z.length} failed response(s):`),console.info(),console.table(z))}async function Mn(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 n;if(t)n=t;else{Un(r.criteria);let o=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!o?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(o.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");n=o.entry[0].resource?.id}return{reference:`Agent/${n}`}}function Ea(e){let t=[];for(let r of e.entry??fa){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(Sa(r.resource))}return t}function Sa(e){let t=e.parameter?.find(n=>n.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(n=>n.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 Ln(e,t){let r={},n=t.required,o=t.optional;for(let s of n){let i=e.parameter?.find(l=>l.name===s);if(!i)throw new Error(`Failed to find parameter '${s}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${s}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${s}'`);r[s]=i[a]}if(o?.length)for(let s of o){let i=e.parameter?.find(l=>l.name===s);if(!i)continue;let a=Ra(s,i);r[s]=a}return r}function Ra(e,t){let r;for(let n in t)if(n.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=n}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function Aa(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(!ha(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return Un(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function Un(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,n]=e.split("?");if(r!=="Agent"||!n)throw new Error(t);try{new URLSearchParams(n)}catch(o){throw new Error(t,{cause:o})}if(!n.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}import{ContentType as Je,getDisplayString as ba,MEDPLUM_CLI_CLIENT_ID as Pa,normalizeErrorString as Ia}from"@medplum/core";import{exec as va}from"node:child_process";import{createServer as Ca}from"node:http";import{platform as Ta}from"node:os";import{promisify as Oa}from"node:util";var xa=Oa(va),_n=Pa,Fn="http://localhost:9615",qt=new h("login"),Kt=new h("whoami"),Gt=new h("token");qt.action(async e=>{let t=e.profile??"default",r=Ge(t,e),n=await A(e,!1);await $a(n,r)});Kt.action(async e=>{let t=await A(e);Da(t)});Gt.action(async e=>{let t=await A(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function $a(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Ma(e,t);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 bn(e,t);break;case"jwt-assertion":await Pn(e,t);break}}async function Na(e){let t=Ca(async(r,n)=>{let o=new URL(r.url,"http://localhost:9615"),s=o.searchParams.get("code");if(r.method==="OPTIONS"){n.writeHead(200,{Allow:"GET, POST","Content-Type":Je.TEXT}),n.end("OK");return}if(o.pathname==="/"&&s)try{let i=await e.processCode(s,{clientId:_n,redirectUri:Fn});n.writeHead(200,{"Content-Type":Je.TEXT}),n.end(`Signed in as ${ba(i)}. You may close this window.`)}catch(i){n.writeHead(400,{"Content-Type":Je.TEXT}),n.end(`Error: ${Ia(i)}`)}finally{t.close(),process.exit(0)}else n.writeHead(404,{"Content-Type":Je.TEXT}),n.end("Not found")}).listen(9615)}async function ka(e){let t=Ta(),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)}await xa(r)}function Da(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 Ma(e,t){await Na(e);let r=new URL(e.getAuthorizeUrl());r.searchParams.set("client_id",_n),r.searchParams.set("redirect_uri",Fn),r.searchParams.set("scope",t.scope??"openid offline_access"),r.searchParams.set("response_type","code"),r.searchParams.set("prompt","login"),await ka(r.toString())}var Ae="\x1B[0m",La="\x1B[1m",Ua="\x1B[31m",_a="\x1B[32m",Fa="\x1B[33m",ja="\x1B[34m",re={red:e=>`${Ua}${e}${Ae}`,green:e=>`${_a}${e}${Ae}`,yellow:e=>`${Fa}${e}${Ae}`,blue:e=>`${ja}${e}${Ae}`,bold:e=>`${La}${e}${Ae}`},Vt=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>re.bold(r));var ks=kr(mr(),1);import{CloudFormationClient as Ns,DescribeStackResourcesCommand as Xu,DescribeStacksCommand as zu,paginateListStacks as Yu}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as Qu,CreateInvalidationCommand as Zu}from"@aws-sdk/client-cloudfront";import{ECSClient as ep}from"@aws-sdk/client-ecs";import{S3Client as tp}from"@aws-sdk/client-s3";import{GetParameterCommand as rp,PutParameterCommand as np,SSMClient as op}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as sp,STSClient as ip}from"@aws-sdk/client-sts";import{EMPTY as ap,normalizeErrorString as cp}from"@medplum/core";import{readdirSync as lp}from"node:fs";import Ju from"node:readline";var at;function ct(){at=Ju.createInterface({input:process.stdin,output:process.stdout})}function lt(){at.close()}function c(e){at.write(e+`
5
- `)}function I(e){c(`
4
+ `),s?g.length?s(g):console.info("No successful responses received"):console.table(g.length?g:"No successful responses received"),console.info(),Y.length&&(console.info(`${Y.length} failed response(s):`),console.info(),console.table(Y))}async function Tn(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 n;if(t)n=t;else{xn(r.criteria);let o=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!o?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(o.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");n=o.entry[0].resource?.id}return{reference:`Agent/${n}`}}function wa(e){let t=[];for(let r of e.entry??ma){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(Ea(r.resource))}return t}function Ea(e){let t=e.parameter?.find(n=>n.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(n=>n.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 On(e,t){let r={},n=t.required,o=t.optional;for(let s of n){let i=e.parameter?.find(l=>l.name===s);if(!i)throw new Error(`Failed to find parameter '${s}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${s}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${s}'`);r[s]=i[a]}if(o?.length)for(let s of o){let i=e.parameter?.find(l=>l.name===s);if(!i)continue;let a=Sa(s,i);r[s]=a}return r}function Sa(e,t){let r;for(let n in t)if(n.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=n}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function Ra(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(!ga(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return xn(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function xn(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,n]=e.split("?");if(r!=="Agent"||!n)throw new Error(t);try{new URLSearchParams(n)}catch(o){throw new Error(t,{cause:o})}if(!n.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}import{ContentType as Ue,getDisplayString as ba,MEDPLUM_CLI_CLIENT_ID as Aa,normalizeErrorString as Pa}from"@medplum/core";import{exec as Ia}from"node:child_process";import{createServer as va}from"node:http";import{platform as Ca}from"node:os";import{promisify as Ta}from"node:util";var Oa=Ta(Ia),$n=Aa,Nn="http://localhost:9615",kt=new h("login"),Dt=new h("whoami"),Mt=new h("token");kt.action(async e=>{let t=e.profile??"default",r=De(t,e),n=await R(e,!1);await xa(n,r)});Dt.action(async e=>{let t=await R(e);ka(t)});Mt.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 xa(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Da(e,t);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 hn(e,t);break;case"jwt-assertion":await yn(e,t);break}}async function $a(e){let t=va(async(r,n)=>{let o=new URL(r.url,"http://localhost:9615"),s=o.searchParams.get("code");if(r.method==="OPTIONS"){n.writeHead(200,{Allow:"GET, POST","Content-Type":Ue.TEXT}),n.end("OK");return}if(o.pathname==="/"&&s)try{let i=await e.processCode(s,{clientId:$n,redirectUri:Nn});n.writeHead(200,{"Content-Type":Ue.TEXT}),n.end(`Signed in as ${ba(i)}. You may close this window.`)}catch(i){n.writeHead(400,{"Content-Type":Ue.TEXT}),n.end(`Error: ${Pa(i)}`)}finally{t.close(),process.exit(0)}else n.writeHead(404,{"Content-Type":Ue.TEXT}),n.end("Not found")}).listen(9615)}async function Na(e){let t=Ca(),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)}await Oa(r)}function ka(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 Da(e,t){await $a(e);let r=new URL(e.getAuthorizeUrl());r.searchParams.set("client_id",$n),r.searchParams.set("redirect_uri",Nn),r.searchParams.set("scope",t.scope??"openid offline_access"),r.searchParams.set("response_type","code"),r.searchParams.set("prompt","login"),await Na(r.toString())}var fe="\x1B[0m",Ma="\x1B[1m",La="\x1B[31m",Ua="\x1B[32m",_a="\x1B[33m",Fa="\x1B[34m",z={red:e=>`${La}${e}${fe}`,green:e=>`${Ua}${e}${fe}`,yellow:e=>`${_a}${e}${fe}`,blue:e=>`${Fa}${e}${fe}`,bold:e=>`${Ma}${e}${fe}`},Lt=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>z.bold(r));var vs=Ar(nr(),1);import{CloudFormationClient as Is,DescribeStackResourcesCommand as Ju,DescribeStacksCommand as Xu,paginateListStacks as zu}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as Yu,CreateInvalidationCommand as Qu}from"@aws-sdk/client-cloudfront";import{ECSClient as Zu}from"@aws-sdk/client-ecs";import{S3Client as ep}from"@aws-sdk/client-s3";import{GetParameterCommand as tp,PutParameterCommand as rp,SSMClient as np}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as op,STSClient as sp}from"@aws-sdk/client-sts";import{EMPTY as ip,normalizeErrorString as ap}from"@medplum/core";import{readdirSync as cp}from"node:fs";import Hu from"node:readline";var ze;function Ye(){ze=Hu.createInterface({input:process.stdin,output:process.stdout})}function Qe(){ze.close()}function c(e){ze.write(e+`
5
+ `)}function P(e){c(`
6
6
  `+e+`
7
- `)}function D(e,t=""){return new Promise(r=>{at.question(e+(t?" ("+t+")":"")+" ",n=>{r(n||t.toString())})})}async function ut(e,t,r=""){let n=e+" ["+t.map(o=>o===r?"("+o+")":o).join("|")+"]";for(;;){let o=await D(n)||r;if(t.includes(o))return o;c("Please choose one of the following options: "+t.join(", "))}}async function ue(e,t,r){return Number.parseInt(await ut(e,t.map(n=>n.toString()),r.toString()),10)}async function Z(e){return(await ut(e,["y","n"])).toLowerCase()==="y"}async function Te(e){if(!await Z(e))throw c("Exiting..."),new Error("User cancelled")}var pt=new Ns({}),up=new Qu({region:"us-east-1"}),nh=new ep({}),Oe=new tp({}),pp="medplum:environment";async function fr(){let e=[],t=Yu({client:pt},{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)for(let n of r.StackSummaries??ap)e.push(n);return e}async function pe(e){let t=await fr();for(let r of t){let n=r.StackName,o=await gr(n);if(o?.tag===e)return o}}async function gr(e){let t={};if(await $s(pt,e,t),await pt.config.region()!=="us-east-1")try{await $s(new Ns({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function $s(e,t,r){let n=new zu({StackName:t}),s=(await e.send(n))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===pp);if(!i)return;let a=await e.send(new Xu({StackName:t}));if(a.StackResources){e===pt&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)dp(l,r)}}function dp(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 dt(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: ${mp(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 mp(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function mt(e){let t=await up.send(new Zu({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function ft(e){let n=(await(await fetch("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(o=>o.tag_name.startsWith("v")?o.tag_name.slice(1):o.tag_name);return n.sort((o,s)=>ks.compare(s,o)),e?n.slice(0,n.indexOf(e)):n}async function gt(e,t,r){let n=new op({region:e});for(let[o,s]of Object.entries(r)){let i=t+o,a=typeof s=="object"?JSON.stringify(s):s.toString(),l=await fp(n,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await Te(`Do you want to overwrite "${i}"?`)),await gp(n,i,a)}}async function fp(e,t){let r=new rp({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(n){if(n.name==="ParameterNotFound")return;throw n}}async function gp(e,t,r){let n=new np({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(n)}function ee(e,t){if(console.log(`Config not found: ${e} (${B(e,t)})`),t){let n=Object.entries(t);if(n.length>0){console.log("Additional options:");for(let[o,s]of n)console.log(` ${o}: ${s}`)}}console.log();let r=lp(".",{withFileTypes:!0});if(r=r.filter(n=>n.isFile()&&n.name.startsWith("medplum.")&&n.name.endsWith(".json")).map(n=>n.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let n of r)console.log(` ${n.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${n})`)}}async function de(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new ip,r=new sp({}),n=await t.send(r),o=await t.config.region();console.log("AWS Region: ",o),console.log("AWS Account ID: ",n.Account),console.log("AWS Account ARN: ",n.Arn),console.log("AWS User ID: ",n.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",cp(t))}}async function Ds(e){let t=await pe(e);if(!t)throw await de(e),new Error(`Stack not found: ${e}`);dt(t)}import{ACMClient as Us,ListCertificatesCommand as hp,RequestCertificateCommand as yp}from"@aws-sdk/client-acm";import{CloudFrontClient as wp,CreatePublicKeyCommand as Ep}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as Sp,STSClient as Rp}from"@aws-sdk/client-sts";import{normalizeErrorString as Ap}from"@medplum/core";import{generateKeyPairSync as bp,randomUUID as Ms}from"node:crypto";import{existsSync as Pp}from"node:fs";var Ip=e=>`${e}DomainName`,_s=e=>`${e}SslCertArn`;async function Fs(){let e={apiPort:8103,region:"us-east-1"};ct(),I("MEDPLUM"),c("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),c(""),c("Most Medplum infrastructure is deployed using the AWS CDK."),c("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),c("This tool will help you create those resources."),c(""),c("Upon completion, this tool will:"),c(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),c(" 2. Optionally generate an AWS CloudFront signing key"),c(" 3. Optionally request SSL certificates from AWS Certificate Manager"),c(" 4. Optionally write server config settings to AWS Parameter Store"),c(""),c("The Medplum infra config file is an input to the Medplum CDK."),c("The Medplum CDK will create and manage the necessary AWS resources."),c(""),c("We will ask a series of questions to generate your infra config file."),c("Some questions have predefined options in [square brackets]."),c("Some questions have default values in (parentheses), which you can accept by pressing Enter."),c("Press Ctrl+C at any time to exit.");let t=await vp(e.region);t||(c("It appears that you do not have AWS credentials configured."),c("AWS credentials are not strictly required, but will enable some additional features."),c("If you intend to use AWS credentials, please configure them now."),await Te("Do you want to continue without AWS credentials?")),I("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await D("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),I("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await D("What is the config file name?",`medplum.${e.name}.config.json`);Pp(r)&&(c("Config file already exists."),await Te("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),C(r,e),I("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await D("Enter your AWS region:","us-east-1"),C(r,e),I("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await D("What is your AWS account number?",t),C(r,e),I("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let n="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await D("Enter your CloudFormation stack name?",n),C(r,e),I("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await D("Enter your base domain name:");C(r,e),I("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let o=await D("Enter your support email address:");I("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await D("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,C(r,e),I("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await D("Enter your web application domain name:","app."+e.domainName),C(r,e),I("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await D("Enter your storage domain name:","storage."+e.domainName),C(r,e),I("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await D("Enter your storage bucket name:",e.storageDomainName),C(r,e),I("MAX AVAILABILITY ZONES"),c("Medplum API servers can be deployed in multiple availability zones."),c("This provides redundancy and high availability."),c("However, it also increases the cost of the deployment."),c("If you want to use all availability zones, choose a large number such as 99."),c("If you want to restrict the number, for example to manage EIP limits,"),c("then choose a small number such as 2 or 3."),e.maxAzs=await ue("Enter the maximum number of availability zones:",[2,3,99],2),I("DATABASE INSTANCES"),c("Medplum uses a relational database to store data."),c("Medplum can create a new RDS database as part of the CloudFormation stack,"),c("or can set up your own database and enter the database name, username, and password."),await Z("Do you want to create a new RDS database as part of the CloudFormation stack?")?(c("Medplum will create a new RDS database as part of the CloudFormation stack."),c(""),c("If you need high availability, you can choose multiple instances."),c("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await ue("Enter the number of database instances:",[1,2],1)):(c("Medplum will not create a new RDS database."),c("Please create a new RDS database and enter the database name, username, and password."),c('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),C(r,e),I("SERVER INSTANCES"),c("Medplum uses AWS Fargate to run the API servers."),c("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),c("Fargate will automatically scale the number of servers up and down."),c("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await ue("Enter the number of server instances:",[1,2,3,4,6,8],1),C(r,e),I("SERVER MEMORY"),c("You can choose the amount of memory for each server instance."),c("The default is 512 MB, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await ue("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),C(r,e),I("SERVER CPU"),c("You can choose the amount of CPU for each server instance."),c("CPU is expressed as an integer using AWS CPU units"),c("The default is 256, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await ue("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),C(r,e),I("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let s=(await ft())[0]??"latest";e.serverImage=await D("Enter the server image:",`medplum/medplum-server:${s}`),C(r,e),I("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await xp(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,C(r,e)):(c("Unable to generate signing key."),c("Please manually create a signing key and enter the key ID and public key in the config file."),c('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),I("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await Cp(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:f}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let m=await Tp(e,a,u,f);e[_s(f)]=m,C(r,e)}I("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`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:o};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await Z("Do you want to store these values in AWS Parameter Store?"))await gt(e.region,`/medplum/${e.name}/`,l);else{let u=B(e.name,{server:!0});C(u,l),c("Skipping AWS Parameter Store."),c(`Writing values to local config file: ${u}`),c("Please add these values to AWS Parameter Store manually.")}I("DONE!"),c("Medplum configuration complete."),c("You can now proceed to deploying the Medplum infrastructure with CDK."),c("Run:"),c(""),c(` npx cdk bootstrap -c config=${r}`),c(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?c(` npx cdk deploy -c config=${r}`):c(` npx cdk deploy -c config=${r} --all`),c(""),c("See Medplum documentation for more information:"),c(""),c(" https://www.medplum.com/docs/self-hosting/install-on-aws"),c(""),lt()}async function vp(e){try{let t=new Rp({region:e}),r=new Sp({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Cp(e){let t=await Ls(e);if(e!=="us-east-1"){let r=await Ls("us-east-1");t.push(...r)}return t}async function Ls(e){try{let t=new Us({region:e}),r=new hp({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Tp(e,t,r,n){let o=e[Ip(n)],s=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===o);if(s)return c(`Found existing certificate for "${o}" in "${r}.`),s.CertificateArn;if(c(`No existing certificate found for "${o}" in "${r}.`),!await Z("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${_s(n)}" setting.`),"TODO";let i=await Op(r,o);return c("Certificate ARN: "+i),i}async function Op(e,t){try{let r=await ut("Validate certificate using DNS or email validation?",["dns","email"],"dns"),n=new Us({region:e}),o=new yp({DomainName:t,ValidationMethod:r.toUpperCase()});return(await n.send(o)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function xp(e,t){let r=Ms(),n=bp("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new wp({region:e}).send(new Ep({PublicKeyConfig:{Name:t,CallerReference:Ms(),EncodedKey:n.publicKey}}))).PublicKey?.Id,publicKey:n.publicKey,privateKey:n.privateKey,passphrase:r}}catch(o){console.log("Error: Unable to create signing key: ",Ap(o));return}}async function js(){let e=await fr();for(let t of e){let r=t.StackName,n=await gr(r);n&&(dt(n),console.log(""))}}import{PutObjectCommand as $p}from"@aws-sdk/client-s3";import{ContentType as H}from"@medplum/core";import Np from"fast-glob";import{createReadStream as kp,mkdtempSync as Dp,readdirSync as Mp,readFileSync as Lp,rmSync as Up,writeFileSync as _p}from"node:fs";import{tmpdir as Fp}from"node:os";import{join as ht,sep as jp}from"node:path";import{Readable as Bp}from"node:stream";import{pipeline as Wp}from"node:stream/promises";async function Bs(e,t){let r=G(e,t);if(!r)throw ee(e,t),new Error(`Config not found: ${e}`);let n=await pe(e);if(!n)throw await de(e),new Error(`Stack not found: ${e}`);let o=n.appBucket;if(!o)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 Kp("@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 Vp(s,o.PhysicalResourceId,t),n.appDistribution?.PhysicalResourceId&&!t.dryrun&&await mt(n.appDistribution.PhysicalResourceId),console.log("Done")}async function qp(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await fetch(r)).json()}async function Kp(e,t){let n=(await qp(e,t)).dist.tarball,o=Dp(ht(Fp(),"tarball-"));try{let s=await fetch(n);if(!s.body)throw new Error("Received empty response body");let i=Rn(o);return await Wp(Bp.fromWeb(s.body),i),ht(o,"package","dist")}catch(s){throw Up(o,{recursive:!0,force:!0}),s}}function Ws(e,t){for(let r of Mp(e,{withFileTypes:!0})){let n=ht(e,r.name);r.isDirectory()?Ws(n,t):r.isFile()&&n.endsWith(".js")&&Gp(n,t)}}function Gp(e,t){let r=Lp(e,"utf-8");for(let[n,o]of Object.entries(t))r=r.replaceAll(`__${n}__`,o);_p(e,r)}async function Vp(e,t,r){let n=[["assets/**/*.css",H.CSS,!0],["assets/**/*.css.map",H.JSON,!0],["assets/**/*.js",H.JAVASCRIPT,!0],["assets/**/*.js.map",H.JSON,!0],["assets/**/*.txt",H.TEXT,!0],["assets/**/*.ico",H.FAVICON,!0],["img/**/*.png",H.PNG,!0],["img/**/*.svg",H.SVG,!0],["robots.txt",H.TEXT,!0],["index.html",H.HTML,!1]];for(let o of n)await Hp({rootDir:e,bucketName:t,fileNamePattern:o[0],contentType:o[1],cached:o[2],dryrun:r.dryrun})}async function Hp(e){let t=Np.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Jp(ht(e.rootDir,r),e)}async function Jp(e,t){let r=kp(e),n=e.substring(t.rootDir.length+1).split(jp).join("/"),o={Bucket:t.bucketName,Key:n,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${n} to ${t.bucketName}...`),t.dryrun||await Oe.send(new $p(o))}import{GetBucketPolicyCommand as Xp,PutBucketPolicyCommand as zp}from"@aws-sdk/client-s3";async function Gs(e,t){if(!G(e,t))throw ee(e,t),new Error(`Config not found: ${e}`);let n=await pe(e);if(!n)throw await de(e),new Error(`Stack not found: ${e}`);try{await qs("App",n.appBucket,n.appDistribution,n.appOriginAccessIdentity,t)}catch(o){console.error(`Error updating App bucket policy: ${o.message}`)}try{await qs("Storage",n.storageBucket,n.storageDistribution,n.storageOriginAccessIdentity,t)}catch(o){console.error(`Error updating Storage bucket policy: ${o.message}`)}console.log("Done")}async function qs(e,t,r,n,o){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!n?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let s=t.PhysicalResourceId,i=n.PhysicalResourceId,a=await Yp(s);if(Zp(a,s,i))throw new Error(`${e} bucket already has policy statement`);ed(a,s,i),e==="Storage"&&o.guarddutyMalwareProtection&&td(a,s,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),o.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Qp(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await mt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Yp(e){let t=await Oe.send(new Xp({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Qp(e,t){await Oe.send(new zp({Bucket:e,Policy:JSON.stringify(t)}))}function Zp(e,t,r){return!!e?.Statement?.some(n=>n?.Effect==="Allow"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(n?.Action)&&n?.Action?.includes("s3:GetObject*")&&n?.Action?.includes("s3:GetBucket*")&&n?.Action?.includes("s3:List*")&&Array.isArray(n?.Resource)&&n?.Resource?.includes(`arn:aws:s3:::${t}`)&&n?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function ed(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}/*`]})}function td(e,t,r){e.Statement?.some(n=>n?.Effect==="Deny"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Ks(n,"s3:GetObject")&&Ks(n,"s3:GetObjectVersion")&&n?.Condition?.StringNotEquals?.["s3:ExistingObjectTag/GuardDutyMalwareScanStatus"]==="NO_THREATS_FOUND")||e.Statement?.push({Sid:"GuardDutyMalwareProtectionReadGate",Effect:"Deny",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject","s3:GetObjectVersion"],Resource:`arn:aws:s3:::${t}/*`,Condition:{StringNotEquals:{"s3:ExistingObjectTag/GuardDutyMalwareScanStatus":"NO_THREATS_FOUND"}}})}function Ks(e,t){return e.Action===t?!0:Array.isArray(e.Action)&&e.Action.includes(t)}async function Vs(e,t){try{ct();let r=G(e,t);if(!r)throw ee(e,t),new Error(`Config not found: ${e}`);let n=Sn(e)??{};if(!t.yes&&Object.keys(n).length===0){let o=B(e,{server:!0});if(console.log(re.yellow(`Config file ${o} not found!`)),!await Z("Do you want to proceed?")){console.log(re.red(`Run Aborted, please ensure ${o} is present and try again.`));return}}rd(r,n),od(r,n),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${r.name}" path.`),c(JSON.stringify({...n,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(re.yellow("Dry run - skipping updates!")):(t.yes||await Z("Do you want to store these values in AWS Parameter Store?"))&&await gt(r.region,`/medplum/${r.name}/`,n)}finally{lt()}}function rd(e,t){yt(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),yt(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),yt(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),yt(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function yt(e,t,r){if(nd(e,t))throw new Error(r)}function nd(e,t){return e!==void 0&&t!==void 0&&e!==t}function od(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}/binary/`)}var me=kr(mr(),1);import{spawnSync as sd}from"node:child_process";async function Js(e,t){let r=await A(t),n=G(e,t);if(!n)throw console.log(`Configuration file ${B(e)} not found`),ee(e,t),new Error(`Config not found: ${e}`);let o=n.serverImage.lastIndexOf(":"),s=n.serverImage.slice(0,o),i=await id(r,n),a=await Hs(i);for(;a;){if(t.toVersion&&me.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),n.serverImage=`${s}:${a}`,ad(e,n),await r.startAsyncRequest("/admin/super/migrate"),a=await Hs(a)}}async function id(e,t){let r=t.serverImage.lastIndexOf(":"),n=t.serverImage.slice(r+1);if(n==="latest"){n=(await e.get("/healthcheck")).version;let s=n.indexOf("-");s>-1&&(n=n.slice(0,s))}return n}async function Hs(e,t){let r=await ft(e),n=r[0];return r.filter(o=>o===n||o===t||me.gte(o,me.inc(e,"minor"))).pop()}function ad(e,t){let r=B(e);C(r,t);let n=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+n);let o=sd(n,{stdio:"inherit"});if(o.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${o.status}): ${o.stderr}`);console.log(o.stdout)}function Xs(){let e=new h("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Fs),e.command("list").description("List Medplum AWS CloudFormation stacks").action(js),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Ds),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(Vt(`Update the AWS Parameter Store config values.
7
+ `)}function N(e,t=""){return new Promise(r=>{ze.question(e+(t?" ("+t+")":"")+" ",n=>{r(n||t.toString())})})}async function Ze(e,t,r=""){let n=e+" ["+t.map(o=>o===r?"("+o+")":o).join("|")+"]";for(;;){let o=await N(n)||r;if(t.includes(o))return o;c("Please choose one of the following options: "+t.join(", "))}}async function ne(e,t,r){return Number.parseInt(await Ze(e,t.map(n=>n.toString()),r.toString()),10)}async function H(e){return(await Ze(e,["y","n"])).toLowerCase()==="y"}async function Se(e){if(!await H(e))throw c("Exiting..."),new Error("User cancelled")}var et=new Is({}),lp=new Yu({region:"us-east-1"}),zg=new Zu({}),Re=new ep({}),up="medplum:environment";async function or(){let e=[],t=zu({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)for(let n of r.StackSummaries??ip)e.push(n);return e}async function oe(e){let t=await or();for(let r of t){let n=r.StackName,o=await sr(n);if(o?.tag===e)return o}}async function sr(e){let t={};if(await Ps(et,e,t),await et.config.region()!=="us-east-1")try{await Ps(new Is({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Ps(e,t,r){let n=new Xu({StackName:t}),s=(await e.send(n))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===up);if(!i)return;let a=await e.send(new Ju({StackName:t}));if(a.StackResources){e===et&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)pp(l,r)}}function pp(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 tt(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: ${dp(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 dp(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function rt(e){let t=await lp.send(new Qu({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function nt(e){let n=(await(await fetch("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(o=>o.tag_name.startsWith("v")?o.tag_name.slice(1):o.tag_name);return n.sort((o,s)=>vs.compare(s,o)),e?n.slice(0,n.indexOf(e)):n}async function ot(e,t,r){let n=new np({region:e});for(let[o,s]of Object.entries(r)){let i=t+o,a=typeof s=="object"?JSON.stringify(s):s.toString(),l=await mp(n,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await Se(`Do you want to overwrite "${i}"?`)),await fp(n,i,a)}}async function mp(e,t){let r=new tp({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(n){if(n.name==="ParameterNotFound")return;throw n}}async function fp(e,t,r){let n=new rp({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(n)}function J(e,t){if(console.log(`Config not found: ${e} (${L(e,t)})`),t){let n=Object.entries(t);if(n.length>0){console.log("Additional options:");for(let[o,s]of n)console.log(` ${o}: ${s}`)}}console.log();let r=cp(".",{withFileTypes:!0});if(r=r.filter(n=>n.isFile()&&n.name.startsWith("medplum.")&&n.name.endsWith(".json")).map(n=>n.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let n of r)console.log(` ${n.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${n})`)}}async function se(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new sp,r=new op({}),n=await t.send(r),o=await t.config.region();console.log("AWS Region: ",o),console.log("AWS Account ID: ",n.Account),console.log("AWS Account ARN: ",n.Arn),console.log("AWS User ID: ",n.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",ap(t))}}async function Cs(e){let t=await oe(e);if(!t)throw await se(e),new Error(`Stack not found: ${e}`);tt(t)}import{ACMClient as xs,ListCertificatesCommand as gp,RequestCertificateCommand as hp}from"@aws-sdk/client-acm";import{CloudFrontClient as yp,CreatePublicKeyCommand as wp}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as Ep,STSClient as Sp}from"@aws-sdk/client-sts";import{normalizeErrorString as Rp}from"@medplum/core";import{generateKeyPairSync as bp,randomUUID as Ts}from"node:crypto";import{existsSync as Ap}from"node:fs";var Pp=e=>`${e}DomainName`,$s=e=>`${e}SslCertArn`;async function Ns(){let e={apiPort:8103,region:"us-east-1"};Ye(),P("MEDPLUM"),c("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),c(""),c("Most Medplum infrastructure is deployed using the AWS CDK."),c("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),c("This tool will help you create those resources."),c(""),c("Upon completion, this tool will:"),c(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),c(" 2. Optionally generate an AWS CloudFront signing key"),c(" 3. Optionally request SSL certificates from AWS Certificate Manager"),c(" 4. Optionally write server config settings to AWS Parameter Store"),c(""),c("The Medplum infra config file is an input to the Medplum CDK."),c("The Medplum CDK will create and manage the necessary AWS resources."),c(""),c("We will ask a series of questions to generate your infra config file."),c("Some questions have predefined options in [square brackets]."),c("Some questions have default values in (parentheses), which you can accept by pressing Enter."),c("Press Ctrl+C at any time to exit.");let t=await Ip(e.region);t||(c("It appears that you do not have AWS credentials configured."),c("AWS credentials are not strictly required, but will enable some additional features."),c("If you intend to use AWS credentials, please configure them now."),await Se("Do you want to continue without AWS credentials?")),P("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await N("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),P("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await N("What is the config file name?",`medplum.${e.name}.config.json`);Ap(r)&&(c("Config file already exists."),await Se("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),I(r,e),P("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await N("Enter your AWS region:","us-east-1"),I(r,e),P("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await N("What is your AWS account number?",t),I(r,e),P("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let n="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await N("Enter your CloudFormation stack name?",n),I(r,e),P("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await N("Enter your base domain name:");I(r,e),P("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let o=await N("Enter your support email address:");P("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await N("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,I(r,e),P("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await N("Enter your web application domain name:","app."+e.domainName),I(r,e),P("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await N("Enter your storage domain name:","storage."+e.domainName),I(r,e),P("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await N("Enter your storage bucket name:",e.storageDomainName),I(r,e),P("MAX AVAILABILITY ZONES"),c("Medplum API servers can be deployed in multiple availability zones."),c("This provides redundancy and high availability."),c("However, it also increases the cost of the deployment."),c("If you want to use all availability zones, choose a large number such as 99."),c("If you want to restrict the number, for example to manage EIP limits,"),c("then choose a small number such as 2 or 3."),e.maxAzs=await ne("Enter the maximum number of availability zones:",[2,3,99],2),P("DATABASE INSTANCES"),c("Medplum uses a relational database to store data."),c("Medplum can create a new RDS database as part of the CloudFormation stack,"),c("or can set up your own database and enter the database name, username, and password."),await H("Do you want to create a new RDS database as part of the CloudFormation stack?")?(c("Medplum will create a new RDS database as part of the CloudFormation stack."),c(""),c("If you need high availability, you can choose multiple instances."),c("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await ne("Enter the number of database instances:",[1,2],1)):(c("Medplum will not create a new RDS database."),c("Please create a new RDS database and enter the database name, username, and password."),c('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),I(r,e),P("SERVER INSTANCES"),c("Medplum uses AWS Fargate to run the API servers."),c("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),c("Fargate will automatically scale the number of servers up and down."),c("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await ne("Enter the number of server instances:",[1,2,3,4,6,8],1),I(r,e),P("SERVER MEMORY"),c("You can choose the amount of memory for each server instance."),c("The default is 512 MB, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await ne("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),I(r,e),P("SERVER CPU"),c("You can choose the amount of CPU for each server instance."),c("CPU is expressed as an integer using AWS CPU units"),c("The default is 256, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await ne("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),I(r,e),P("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let s=(await nt())[0]??"latest";e.serverImage=await N("Enter the server image:",`medplum/medplum-server:${s}`),I(r,e),P("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await Op(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,I(r,e)):(c("Unable to generate signing key."),c("Please manually create a signing key and enter the key ID and public key in the config file."),c('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),P("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await vp(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:m}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let f=await Cp(e,a,u,m);e[$s(m)]=f,I(r,e)}P("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`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:o};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await H("Do you want to store these values in AWS Parameter Store?"))await ot(e.region,`/medplum/${e.name}/`,l);else{let u=L(e.name,{server:!0});I(u,l),c("Skipping AWS Parameter Store."),c(`Writing values to local config file: ${u}`),c("Please add these values to AWS Parameter Store manually.")}P("DONE!"),c("Medplum configuration complete."),c("You can now proceed to deploying the Medplum infrastructure with CDK."),c("Run:"),c(""),c(` npx cdk bootstrap -c config=${r}`),c(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?c(` npx cdk deploy -c config=${r}`):c(` npx cdk deploy -c config=${r} --all`),c(""),c("See Medplum documentation for more information:"),c(""),c(" https://www.medplum.com/docs/self-hosting/install-on-aws"),c(""),Qe()}async function Ip(e){try{let t=new Sp({region:e}),r=new Ep({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function vp(e){let t=await Os(e);if(e!=="us-east-1"){let r=await Os("us-east-1");t.push(...r)}return t}async function Os(e){try{let t=new xs({region:e}),r=new gp({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Cp(e,t,r,n){let o=e[Pp(n)],s=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===o);if(s)return c(`Found existing certificate for "${o}" in "${r}.`),s.CertificateArn;if(c(`No existing certificate found for "${o}" in "${r}.`),!await H("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${$s(n)}" setting.`),"TODO";let i=await Tp(r,o);return c("Certificate ARN: "+i),i}async function Tp(e,t){try{let r=await Ze("Validate certificate using DNS or email validation?",["dns","email"],"dns"),n=new xs({region:e}),o=new hp({DomainName:t,ValidationMethod:r.toUpperCase()});return(await n.send(o)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Op(e,t){let r=Ts(),n=bp("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new yp({region:e}).send(new wp({PublicKeyConfig:{Name:t,CallerReference:Ts(),EncodedKey:n.publicKey}}))).PublicKey?.Id,publicKey:n.publicKey,privateKey:n.privateKey,passphrase:r}}catch(o){console.log("Error: Unable to create signing key: ",Rp(o));return}}async function ks(){let e=await or();for(let t of e){let r=t.StackName,n=await sr(r);n&&(tt(n),console.log(""))}}import{PutObjectCommand as xp}from"@aws-sdk/client-s3";import{ContentType as B}from"@medplum/core";import $p from"fast-glob";import{createReadStream as Np,mkdtempSync as kp,readdirSync as Dp,readFileSync as Mp,rmSync as Lp,writeFileSync as Up}from"node:fs";import{tmpdir as _p}from"node:os";import{join as st,sep as Fp}from"node:path";import{Readable as jp}from"node:stream";import{pipeline as Bp}from"node:stream/promises";async function Ds(e,t){let r=F(e,t);if(!r)throw J(e,t),new Error(`Config not found: ${e}`);let n=await oe(e);if(!n)throw await se(e),new Error(`Stack not found: ${e}`);let o=n.appBucket;if(!o)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 Wp("@medplum/app",i)}Ms(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 Gp(s,o.PhysicalResourceId,t),n.appDistribution?.PhysicalResourceId&&!t.dryrun&&await rt(n.appDistribution.PhysicalResourceId),console.log("Done")}async function qp(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await fetch(r)).json()}async function Wp(e,t){let n=(await qp(e,t)).dist.tarball,o=kp(st(_p(),"tarball-"));try{let s=await fetch(n);if(!s.body)throw new Error("Received empty response body");let i=fn(o);return await Bp(jp.fromWeb(s.body),i),st(o,"package","dist")}catch(s){throw Lp(o,{recursive:!0,force:!0}),s}}function Ms(e,t){for(let r of Dp(e,{withFileTypes:!0})){let n=st(e,r.name);r.isDirectory()?Ms(n,t):r.isFile()&&n.endsWith(".js")&&Kp(n,t)}}function Kp(e,t){let r=Mp(e,"utf-8");for(let[n,o]of Object.entries(t))r=r.replaceAll(`__${n}__`,o);Up(e,r)}async function Gp(e,t,r){let n=[["assets/**/*.css",B.CSS,!0],["assets/**/*.css.map",B.JSON,!0],["assets/**/*.js",B.JAVASCRIPT,!0],["assets/**/*.js.map",B.JSON,!0],["assets/**/*.txt",B.TEXT,!0],["assets/**/*.ico",B.FAVICON,!0],["img/**/*.png",B.PNG,!0],["img/**/*.svg",B.SVG,!0],["robots.txt",B.TEXT,!0],["index.html",B.HTML,!1]];for(let o of n)await Vp({rootDir:e,bucketName:t,fileNamePattern:o[0],contentType:o[1],cached:o[2],dryrun:r.dryrun})}async function Vp(e){let t=$p.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Hp(st(e.rootDir,r),e)}async function Hp(e,t){let r=Np(e),n=e.substring(t.rootDir.length+1).split(Fp).join("/"),o={Bucket:t.bucketName,Key:n,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${n} to ${t.bucketName}...`),t.dryrun||await Re.send(new xp(o))}import{GetBucketPolicyCommand as Jp,PutBucketPolicyCommand as Xp}from"@aws-sdk/client-s3";async function _s(e,t){if(!F(e,t))throw J(e,t),new Error(`Config not found: ${e}`);let n=await oe(e);if(!n)throw await se(e),new Error(`Stack not found: ${e}`);try{await Ls("App",n.appBucket,n.appDistribution,n.appOriginAccessIdentity,t)}catch(o){console.error(`Error updating App bucket policy: ${o.message}`)}try{await Ls("Storage",n.storageBucket,n.storageDistribution,n.storageOriginAccessIdentity,t)}catch(o){console.error(`Error updating Storage bucket policy: ${o.message}`)}console.log("Done")}async function Ls(e,t,r,n,o){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!n?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let s=t.PhysicalResourceId,i=n.PhysicalResourceId,a=await zp(s);if(Qp(a,s,i))throw new Error(`${e} bucket already has policy statement`);Zp(a,s,i),e==="Storage"&&o.guarddutyMalwareProtection&&ed(a,s,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),o.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Yp(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await rt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function zp(e){let t=await Re.send(new Jp({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Yp(e,t){await Re.send(new Xp({Bucket:e,Policy:JSON.stringify(t)}))}function Qp(e,t,r){return!!e?.Statement?.some(n=>n?.Effect==="Allow"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(n?.Action)&&n?.Action?.includes("s3:GetObject*")&&n?.Action?.includes("s3:GetBucket*")&&n?.Action?.includes("s3:List*")&&Array.isArray(n?.Resource)&&n?.Resource?.includes(`arn:aws:s3:::${t}`)&&n?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Zp(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}/*`]})}function ed(e,t,r){e.Statement?.some(n=>n?.Effect==="Deny"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Us(n,"s3:GetObject")&&Us(n,"s3:GetObjectVersion")&&n?.Condition?.StringNotEquals?.["s3:ExistingObjectTag/GuardDutyMalwareScanStatus"]==="NO_THREATS_FOUND")||e.Statement?.push({Sid:"GuardDutyMalwareProtectionReadGate",Effect:"Deny",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject","s3:GetObjectVersion"],Resource:`arn:aws:s3:::${t}/*`,Condition:{StringNotEquals:{"s3:ExistingObjectTag/GuardDutyMalwareScanStatus":"NO_THREATS_FOUND"}}})}function Us(e,t){return e.Action===t?!0:Array.isArray(e.Action)&&e.Action.includes(t)}async function Fs(e,t){try{Ye();let r=F(e,t);if(!r)throw J(e,t),new Error(`Config not found: ${e}`);let n=mn(e)??{};if(!t.yes&&Object.keys(n).length===0){let o=L(e,{server:!0});if(console.log(z.yellow(`Config file ${o} not found!`)),!await H("Do you want to proceed?")){console.log(z.red(`Run Aborted, please ensure ${o} is present and try again.`));return}}td(r,n),nd(r,n),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${r.name}" path.`),c(JSON.stringify({...n,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(z.yellow("Dry run - skipping updates!")):(t.yes||await H("Do you want to store these values in AWS Parameter Store?"))&&await ot(r.region,`/medplum/${r.name}/`,n)}finally{Qe()}}function td(e,t){it(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),it(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),it(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),it(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function it(e,t,r){if(rd(e,t))throw new Error(r)}function rd(e,t){return e!==void 0&&t!==void 0&&e!==t}function nd(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}/binary/`)}var ie=Ar(nr(),1);import{spawnSync as od}from"node:child_process";async function Bs(e,t){let r=await R(t),n=F(e,t);if(!n)throw console.log(`Configuration file ${L(e)} not found`),J(e,t),new Error(`Config not found: ${e}`);let o=n.serverImage.lastIndexOf(":"),s=n.serverImage.slice(0,o),i=await sd(r,n),a=await js(i);for(;a;){if(t.toVersion&&ie.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),n.serverImage=`${s}:${a}`,id(e,n),await r.startAsyncRequest("/admin/super/migrate"),a=await js(a)}}async function sd(e,t){let r=t.serverImage.lastIndexOf(":"),n=t.serverImage.slice(r+1);if(n==="latest"){n=(await e.get("/healthcheck")).version;let s=n.indexOf("-");s>-1&&(n=n.slice(0,s))}return n}async function js(e,t){let r=await nt(e),n=r[0];return r.filter(o=>o===n||o===t||ie.gte(o,ie.inc(e,"minor"))).pop()}function id(e,t){let r=L(e);I(r,t);let n=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+n);let o=od(n,{stdio:"inherit"});if(o.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${o.status}): ${o.stderr}`);console.log(o.stdout)}function qs(){let e=new h("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Ns),e.command("list").description("List Medplum AWS CloudFormation stacks").action(ks),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Cs),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(Lt(`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
- `+re.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",Vt("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(Vs),y(e,new h("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("--guardduty-malware-protection","Adds the GuardDuty Malware Protection for S3 read-gating deny to the storage bucket policy.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Gs),e}var zs=new h("save"),Ys=new h("deploy"),Qs=new h("create"),xe=new h("bot");y(xe,zs);y(xe,Ys);y(xe,Qs);var hr=new h("save-bot"),yr=new h("deploy-bot"),wr=new h("create-bot");zs.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await A(t);await wt(r,e)});Ys.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await A(t);await wt(r,e,!0)});Qs.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,n,o)=>{let s=await A(o);await Bt(s,e,t,r,n,o.runtimeVersion,!!o.writeConfig)});async function wt(e,t,r=!1){let n=En(t),o=[],s=[],i=0,a=0;for(let l of n)try{let u=await e.readResource("Bot",l.id);await Ft(e,l,u),i++,r&&(await jt(e,l,u),a++)}catch(u){o.push(u),s.push(`${l.name} [${l.id}]`)}if(console.log(`Number of bots saved: ${i}`),console.log(`Number of bots deployed: ${a}`),console.log(`Number of errors: ${o.length}`),o.length)throw new Error(`${o.length} bot(s) had failures. Bots with failures:
11
+ `+z.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",Lt("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(Fs),y(e,new h("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(Bs)),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(Ds),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("--guardduty-malware-protection","Adds the GuardDuty Malware Protection for S3 read-gating deny to the storage bucket policy.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(_s),e}var Ws=new h("save"),Ks=new h("deploy"),Gs=new h("create"),be=new h("bot");y(be,Ws);y(be,Ks);y(be,Gs);var ir=new h("save-bot"),ar=new h("deploy-bot"),cr=new h("create-bot");Ws.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await at(r,e)});Ks.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await R(t);await at(r,e,!0)});Gs.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,n,o)=>{let s=await R(o);await $t(s,e,t,r,n,o.runtimeVersion,!!o.writeConfig)});async function at(e,t,r=!1){let n=dn(t),o=[],s=[],i=0,a=0;for(let l of n)try{let u=await e.readResource("Bot",l.id);await Ot(e,l,u),i++,r&&(await xt(e,l,u),a++)}catch(u){o.push(u),s.push(`${l.name} [${l.id}]`)}if(console.log(`Number of bots saved: ${i}`),console.log(`Number of bots deployed: ${a}`),console.log(`Number of errors: ${o.length}`),o.length)throw new Error(`${o.length} bot(s) had failures. Bots with failures:
12
12
 
13
13
  ${s.join(`
14
- `)}`,{cause:o})}hr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await A(t);await wt(r,e)});yr.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await A(t);await wt(r,e,!0)});wr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,n,o)=>{let s=await A(o);await Bt(s,e,t,r,n)});import{EMPTY as cd,getRateLimitReset as ld,getStatus as Er,OperationOutcomeError as ud,sleep as Zs}from"@medplum/core";import{createReadStream as pd,createWriteStream as dd}from"node:fs";import{resolve as ri}from"node:path";import{createInterface as md}from"node:readline";import{Readable as fd}from"node:stream";import{pipeline as gd}from"node:stream/promises";var ni=new h("export"),oi=new h("import"),Et=new h("bulk");y(Et,ni);y(Et,oi);ni.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:n,targetDirectory:o}=e,s=await A(e),i=await s.bulkExport(t,r,n,{pollStatusOnAccepted:!0});for(let{type:a,url:l}of i.output??cd){let u=new URL(l),f=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",m=ri(o??"",f),S=await s.downloadResponse(l);if(!S.ok)throw new Error(`Download failed: ${S.status} ${S.statusText}`);if(!S.body)throw new Error("Download response missing body");let g=fd.fromWeb(S.body);await gd(g,dd(m)),console.log(`${m} is created`)}});oi.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:n,targetDirectory:o}=t,s=ri(o??process.cwd(),e),i=await A(t);await hd(s,Number.parseInt(r,10),i,n)});async function hd(e,t,r,n){let o=[],s=pd(e),i=md({input:s});for await(let a of i){let l=yd(a,n);o.push({resource:l,request:{method:"POST",url:l.resourceType}}),o.length%t===0&&(await ei(o,r),o=[])}o.length>0&&await ei(o,r)}async function ei(e,t){let r=e;for(;r.length>0;){let n;try{n=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:r},{maxRetries:0})}catch(s){if(!(s instanceof ud)||Er(s.outcome)!==429)throw s;await Zs(ti(s.outcome,t));continue}let o=[];for(let s=0;s<r.length;s++){let i=n.entry?.[s];i?.response?.outcome&&Er(i.response.outcome)===429?o.push(r[s]):X(i?.response)}if(o.length>0){let s=n.entry?.find(i=>i.response?.outcome&&Er(i.response.outcome)===429)?.response?.outcome;await Zs(ti(s,t))}r=o}}function ti(e,t){let r=e&&ld(e);return r!==void 0?r:Math.max(500,...t.rateLimitStatus().filter(n=>n.remainingUnits===0).map(n=>n.secondsUntilReset*1e3))}function yd(e,t){let r=JSON.parse(e);return t?wd(r):r}function wd(e){return e.resourceType==="ExplanationOfBenefit"?Ed(e):e}function Ed(e){return e.provider||(e.provider=Wt()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Wt())}),e}import Sr from"fast-glob";import{once as si}from"node:events";import{createReadStream as Sd}from"node:fs";import{open as Rd,stat as Ad}from"node:fs/promises";import{basename as bd,extname as Pd,resolve as Id}from"node:path";import{PassThrough as vd}from"node:stream";var Cd=25,Td=new Set([".dcm",".dicom",".ima"]),ii=Buffer.from("DICM"),ai=128,Od=ai+ii.length,xd=2;async function $d(e){if(bd(e).toUpperCase()==="DICOMDIR")return!1;let t=await Rd(e,"r");try{let r=Buffer.alloc(Od),{bytesRead:n}=await t.read(r,0,r.length,0);if(n===r.length&&r.subarray(ai).equals(ii)||n>=2&&r.readUInt16LE(0)===xd)return!0}finally{await t.close()}return Td.has(Pd(e).toLowerCase())}async function Nd(e){let t=new Set;for(let r of e){let n=await Ad(r).catch(()=>{});if(n?.isFile()){t.add(Id(r));continue}let o;if(n?.isDirectory())o=await Sr("**/*",{cwd:r,onlyFiles:!0,absolute:!0});else if(Sr.isDynamicPattern(r))o=await Sr(r,{onlyFiles:!0,absolute:!0,caseSensitiveMatch:!1});else throw new Error(`File not found: ${r}`);let s=0;for(let i of o)await $d(i)?t.add(i):s++;s>0&&console.log(`Skipped ${s} non-DICOM file(s) in "${r}"`)}return Array.from(t).sort((r,n)=>r.localeCompare(n))}async function $e(e,t){e.write(t)||await si(e,"drain")}async function kd(e,t){let r=Sd(e);try{for await(let n of r)t.write(n)||await si(t,"drain")}finally{r.destroy()}}async function Dd(e,t,r){try{for(let n of t)await $e(e,Buffer.from(`--${r}\r
15
- `)),await $e(e,Buffer.from(`Content-Type: application/dicom\r
16
- `)),await $e(e,Buffer.from(`\r
17
- `)),await kd(n,e),await $e(e,Buffer.from(`\r
18
- `));await $e(e,Buffer.from(`--${r}--\r
19
- `)),e.end()}catch(n){throw e.destroy(n),n}}var Md=new h("stow").description("Send DICOM instances via DICOMweb STOW-RS").argument("<files...>","DICOM files, directories, or quoted glob patterns to send").option("--batch-size <count>","Maximum number of instances per STOW-RS request",String(Cd)).action(async(e,t)=>{let r=Number.parseInt(t.batchSize,10);if(!Number.isInteger(r)||r<1)throw new Error(`Invalid batch size: ${t.batchSize}`);let n=await Nd(e);if(n.length===0)throw new Error("No DICOM files found");console.log(`Sending ${n.length} DICOM file(s)`);let o=await A(t);for(let s=0;s<n.length;s+=r){let i=n.slice(s,s+r),a=`medplum-${Date.now()}`,l=`multipart/related; type=application/dicom; boundary=${a}`,u=new vd,f=Dd(u,i,a),m=o.post("/dicomweb/studies",u,l);await f;let S=await m;console.log("STOW-RS response received",S)}}),Rr=new h("dicomweb");y(Rr,Md);import{formatHl7DateTime as Xd,Hl7Message as zd}from"@medplum/core";import St from"node:assert";import _d from"node:net";import{Hl7Message as Fd,OperationOutcomeError as fe,ReturnAckCategory as ci,sleep as jd,validationError as Bd}from"@medplum/core";import li from"iconv-lite";import{ReturnAckCategory as vy}from"@medplum/core";import{sleep as Vd}from"@medplum/core";import Hd from"node:net";var Ld=Object.defineProperty,Ud=(e,t,r)=>t in e?Ld(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,b=(e,t,r)=>Ud(e,typeof t!="symbol"?t+"":t,r),pi=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var Wd=class extends Event{constructor(e,t){super("message"),b(this,"connection"),b(this,"message"),this.connection=e,this.message=t}},qd=class extends Event{constructor(e,t){super("enhancedAckSent"),b(this,"connection"),b(this,"message"),this.connection=e,this.message=t}},Ne=class extends Event{constructor(e){super("error"),b(this,"error"),this.error=e}},Ar=class extends Event{constructor(e){super("warning"),b(this,"error"),this.error=e}},br=class extends Event{constructor(){super("close")}},ui="utf-8",Kd=5e3,Gd=60*1e3,di=class extends pi{constructor(e,t=ui,r,n={}){super(),b(this,"socket"),b(this,"encoding"),b(this,"enhancedMode"),b(this,"messagesPerMin"),b(this,"gracefulCloseTimeoutMs"),b(this,"chunks",[]),b(this,"pendingMessages",new Map),b(this,"responseQueue",[]),b(this,"lastMessageDispatchedTime",0),b(this,"responseQueueProcessing",!1),b(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=n.messagesPerMin,this.gracefulCloseTimeoutMs=n.gracefulCloseTimeoutMs??Kd,e.on("data",o=>{if(this.closing){this.dispatchEvent(new Ar(new fe({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(o);let s=this.parseMessages();for(let i of s)this.responseQueue.push(new Wd(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new Ne(i))})}catch(s){this.dispatchEvent(new Ne(s))}}),e.on("error",o=>{this.resetBuffer(),this.dispatchEvent(new Ne(o))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new br)}),this.addEventListener("message",o=>{let s;this.enhancedMode==="standard"?s=o.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(s=o.message.buildAck({ackCode:"AA"})),s&&(this.send(s),this.dispatchEvent(new qd(this,s)));let i=o.message.getSegment("MSA")?.getField(2)?.toString();if(!i)return;let a=this.getPendingMessage(i);if(!a){this.dispatchEvent(new Ar(new fe({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${i}' but there was no pending message with this control ID`}]})));return}let l=o.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();l&&(a.returnAck===ci.APPLICATION&&l==="CA"||(a.timer&&clearTimeout(a.timer),a.resolve(o.message),this.deletePendingMessage(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=li.encode(t,this.encoding),n=Buffer.alloc(r.length+3);n.writeInt8(11,0),r.copy(n,1),n.writeInt8(28,r.length+1),n.writeInt8(13,r.length+2),this.socket.write(n)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=Gd/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await jd(t-r)}let e=this.responseQueue.shift();e&&this.dispatchEvent(e),this.lastMessageDispatchedTime=Date.now()}this.responseQueueProcessing=!1}}parseMessages(){let e=[],t=Buffer.concat(this.chunks);if(this.resetBuffer(),t.length===0)return e;let r=0;for(;r<t.length;){for(;t[r]!==11&&r<t.length;)r++;let n=-1;for(let a=r+1;a<t.length-1;a++)if(t[a]===28&&t[a+1]===13){n=a+1;break}if(n===-1)break;let o=t.subarray(r,n+1).subarray(1,-2),s=li.decode(o,this.encoding),i=Fd.parse(s);e.push(i),r=n+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,n)=>{let o=e.getSegment("MSH")?.getField(10)?.toString();if(!o){n(new fe(Bd("Required field missing: MSH.10")));return}let s;t?.timeoutMs&&(s=setTimeout(()=>{this.deletePendingMessage(o),n(new fe({resourceType:"OperationOutcome",issue:[{severity:"error",code:"timeout",details:{text:"Client timeout"},diagnostics:`Request timed out after waiting ${t.timeoutMs} milliseconds for response`}]}))},t.timeoutMs)),this.setPendingMessage(o,{message:e,resolve:r,reject:n,returnAck:t?.returnAck??ci.APPLICATION,timer:s}),this.sendImpl(e)})}async close(){this.isClosed()||(this.closing=!0,this.socket.end(),this.drainPendingMessages(),await new Promise(e=>{let t=setTimeout(()=>{this.socket.destroy()},this.gracefulCloseTimeoutMs);this.socket.once("close",()=>{clearTimeout(t),e()})}))}drainPendingMessages(){if(!this.pendingMessages.size)return;let e=this.pendingMessages.size;for(let t of this.pendingMessages.values())t.timer&&clearTimeout(t.timer),t.reject(new fe({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Ne(new fe({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${e} messages were pending`}]}))),this.pendingMessages.clear()}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??ui}getEncoding(){return this.encoding}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}getPendingMessageCount(){return this.pendingMessages.size}getPendingMessage(e){return this.pendingMessages.get(e)}setPendingMessage(e,t){this.pendingMessages.set(e,t)}deletePendingMessage(e){this.pendingMessages.delete(e)}},mi=class extends pi{constructor(e){super(),b(this,"options"),b(this,"host"),b(this,"port"),b(this,"encoding"),b(this,"connection"),b(this,"keepAlive"),b(this,"socket"),b(this,"connectTimeout"),b(this,"deferredConnectionPromise"),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(){if(this.deferredConnectionPromise)return this.deferredConnectionPromise.promise;let e=this.deferredConnectionPromise=this.createDeferredConnectionPromise();return this.socket=_d.connect({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.registerSocketTimeoutListener(e)),this.registerSocketConnectListener(e),this.registerSocketErrorListener(e),this.registerSocketCloseListener(e),e.promise}registerSocketTimeoutListener(e){St(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let n=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,n)};t.on("timeout",r)}registerSocketConnectListener(e){St(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let n;this.connection=n=this.createConnection(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(n),e.resolve(n)};t.on("connect",r)}registerSocketErrorListener(e){St(this.socket);let t=this.socket,r=n=>{this.cleanupSocket(t),n.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,n.errors[0]):this.rejectDeferredPromise(e,n)};t.on("error",r)}registerSocketCloseListener(e){St(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t),this.rejectDeferredPromise(e,new Error("Socket closed before connection finished"))};t.on("close",r)}registerHl7ConnectionListeners(e){e.addEventListener("close",()=>{this.socket=void 0,this.connection=void 0,this.deferredConnectionPromise=void 0,this.dispatchEvent(new br)}),e.addEventListener("error",t=>{this.dispatchEvent(new Ne(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new Ar(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}rejectDeferredPromise(e,t){e.reject(t),this.deferredConnectionPromise===e&&(this.deferredConnectionPromise=void 0)}cleanupSocket(e){e.destroyed||e.destroy(),e===this.socket&&(this.socket=void 0)}createConnection(e,t,r,n){return new di(e,t,r,n)}async send(e){return(await this.connect()).send(e)}async sendAndWait(e,t){return(await this.connect()).sendAndWait(e,t)}async close(){if(this.deferredConnectionPromise&&this.rejectDeferredPromise(this.deferredConnectionPromise,new Error("Client closed while connecting")),this.connection){let e=this.connection;delete this.connection,await e.close()}else this.dispatchEvent(new br);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}};var Jd=1e4,fi=class{constructor(e){b(this,"handler"),b(this,"server"),b(this,"encoding"),b(this,"enhancedMode"),b(this,"messagesPerMin"),b(this,"connections",new Set),this.handler=e}async start(e,t,r,n){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),n?.messagesPerMin!==void 0&&this.setMessagesPerMin(n.messagesPerMin);let o=Hd.createServer(s=>{let i=new di(s,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(i),this.connections.add(i),i.addEventListener("close",()=>{this.connections.delete(i)})});return new Promise((s,i)=>{let a=u=>{o.listen(u,()=>{let f=o.address().port;s(f)})},l=u=>{u?.code==="EADDRINUSE"?o.close(()=>Vd(50).then(()=>a(e))):i(u)};o.on("error",l),o.once("listening",()=>{o.off("error",l)}),a(e),this.server=o})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let n;e?.forceDrainTimeoutMs!==-1&&(n=setTimeout(()=>{for(let o of this.connections)o.close().catch(console.error)},e?.forceDrainTimeoutMs??Jd)),this.server.close(o=>{if(o){r(o);return}n&&clearTimeout(n),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}};import{readFileSync as Yd}from"node:fs";var Qd=new h("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,n)=>{if(n.generateExample?r=em():n.file&&(r=Yd(n.file,"utf8")),!r)throw new Error("Missing HL7 message body");let o=new mi({host:e,port:Number.parseInt(t,10),encoding:n.encoding});try{let s=await o.sendAndWait(zd.parse(r));console.log(s.toString().replaceAll("\r",`
20
- `))}finally{await o.close()}}),Zd=new h("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{await new fi(n=>{n.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
21
- `)),n.send(o.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),Rt=new h("hl7");y(Rt,Qd);y(Rt,Zd);function em(){let e=Xd(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
14
+ `)}`,{cause:o})}ir.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await at(r,e)});ar.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await R(t);await at(r,e,!0)});cr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,n,o)=>{let s=await R(o);await $t(s,e,t,r,n)});import{EMPTY as ad,getRateLimitReset as cd,getStatus as lr,OperationOutcomeError as ld,sleep as Vs}from"@medplum/core";import{createReadStream as ud,createWriteStream as pd}from"node:fs";import{resolve as Xs}from"node:path";import{createInterface as dd}from"node:readline";import{Readable as md}from"node:stream";import{pipeline as fd}from"node:stream/promises";var zs=new h("export"),Ys=new h("import"),ct=new h("bulk");y(ct,zs);y(ct,Ys);zs.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:n,targetDirectory:o}=e,s=await R(e),i=await s.bulkExport(t,r,n,{pollStatusOnAccepted:!0});for(let{type:a,url:l}of i.output??ad){let u=new URL(l),m=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",f=Xs(o??"",m),S=await s.downloadResponse(l);if(!S.ok)throw new Error(`Download failed: ${S.status} ${S.statusText}`);if(!S.body)throw new Error("Download response missing body");let g=md.fromWeb(S.body);await fd(g,pd(f)),console.log(`${f} is created`)}});Ys.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:n,targetDirectory:o}=t,s=Xs(o??process.cwd(),e),i=await R(t);await gd(s,Number.parseInt(r,10),i,n)});async function gd(e,t,r,n){let o=[],s=ud(e),i=dd({input:s});for await(let a of i){let l=hd(a,n);o.push({resource:l,request:{method:"POST",url:l.resourceType}}),o.length%t===0&&(await Hs(o,r),o=[])}o.length>0&&await Hs(o,r)}async function Hs(e,t){let r=e;for(;r.length>0;){let n;try{n=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:r},{maxRetries:0})}catch(s){if(!(s instanceof ld)||lr(s.outcome)!==429)throw s;await Vs(Js(s.outcome,t));continue}let o=[];for(let s=0;s<r.length;s++){let i=n.entry?.[s];i?.response?.outcome&&lr(i.response.outcome)===429?o.push(r[s]):W(i?.response)}if(o.length>0){let s=n.entry?.find(i=>i.response?.outcome&&lr(i.response.outcome)===429)?.response?.outcome;await Vs(Js(s,t))}r=o}}function Js(e,t){let r=e&&cd(e);return r!==void 0?r:Math.max(500,...t.rateLimitStatus().filter(n=>n.remainingUnits===0).map(n=>n.secondsUntilReset*1e3))}function hd(e,t){let r=JSON.parse(e);return t?yd(r):r}function yd(e){return e.resourceType==="ExplanationOfBenefit"?wd(e):e}function wd(e){return e.provider||(e.provider=Nt()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Nt())}),e}import ur from"fast-glob";import{once as Qs}from"node:events";import{createReadStream as Ed}from"node:fs";import{open as Sd,stat as Rd}from"node:fs/promises";import{basename as bd,extname as Ad,resolve as Pd}from"node:path";import{PassThrough as Id}from"node:stream";var vd=25,Cd=new Set([".dcm",".dicom",".ima"]),Zs=Buffer.from("DICM"),ei=128,Td=ei+Zs.length,Od=2;async function xd(e){if(bd(e).toUpperCase()==="DICOMDIR")return!1;let t=await Sd(e,"r");try{let r=Buffer.alloc(Td),{bytesRead:n}=await t.read(r,0,r.length,0);if(n===r.length&&r.subarray(ei).equals(Zs)||n>=2&&r.readUInt16LE(0)===Od)return!0}finally{await t.close()}return Cd.has(Ad(e).toLowerCase())}async function $d(e){let t=new Set;for(let r of e){let n=await Rd(r).catch(()=>{});if(n?.isFile()){t.add(Pd(r));continue}let o;if(n?.isDirectory())o=await ur("**/*",{cwd:r,onlyFiles:!0,absolute:!0});else if(ur.isDynamicPattern(r))o=await ur(r,{onlyFiles:!0,absolute:!0,caseSensitiveMatch:!1});else throw new Error(`File not found: ${r}`);let s=0;for(let i of o)await xd(i)?t.add(i):s++;s>0&&console.log(`Skipped ${s} non-DICOM file(s) in "${r}"`)}return Array.from(t).sort((r,n)=>r.localeCompare(n))}async function Ae(e,t){e.write(t)||await Qs(e,"drain")}async function Nd(e,t){let r=Ed(e);try{for await(let n of r)t.write(n)||await Qs(t,"drain")}finally{r.destroy()}}async function kd(e,t,r){try{for(let n of t)await Ae(e,Buffer.from(`--${r}\r
15
+ `)),await Ae(e,Buffer.from(`Content-Type: application/dicom\r
16
+ `)),await Ae(e,Buffer.from(`\r
17
+ `)),await Nd(n,e),await Ae(e,Buffer.from(`\r
18
+ `));await Ae(e,Buffer.from(`--${r}--\r
19
+ `)),e.end()}catch(n){throw e.destroy(n),n}}var Dd=new h("stow").description("Send DICOM instances via DICOMweb STOW-RS").argument("<files...>","DICOM files, directories, or quoted glob patterns to send").option("--batch-size <count>","Maximum number of instances per STOW-RS request",String(vd)).action(async(e,t)=>{let r=Number.parseInt(t.batchSize,10);if(!Number.isInteger(r)||r<1)throw new Error(`Invalid batch size: ${t.batchSize}`);let n=await $d(e);if(n.length===0)throw new Error("No DICOM files found");console.log(`Sending ${n.length} DICOM file(s)`);let o=await R(t);for(let s=0;s<n.length;s+=r){let i=n.slice(s,s+r),a=`medplum-${Date.now()}`,l=`multipart/related; type=application/dicom; boundary=${a}`,u=new Id,m=kd(u,i,a),f=o.post("/dicomweb/studies",u,l);await m;let S=await f;console.log("STOW-RS response received",S)}}),pr=new h("dicomweb");y(pr,Dd);import{formatHl7DateTime as Jd,Hl7Message as Xd}from"@medplum/core";import lt from"node:assert";import Ud from"node:net";import{Hl7Message as _d,OperationOutcomeError as ae,ReturnAckCategory as ti,sleep as Fd,validationError as jd}from"@medplum/core";import ri from"iconv-lite";import{ReturnAckCategory as Ey}from"@medplum/core";import{sleep as Gd}from"@medplum/core";import Vd from"node:net";var Md=Object.defineProperty,Ld=(e,t,r)=>t in e?Md(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,b=(e,t,r)=>Ld(e,typeof t!="symbol"?t+"":t,r),oi=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var Bd=class extends Event{constructor(e,t){super("message"),b(this,"connection"),b(this,"message"),this.connection=e,this.message=t}},qd=class extends Event{constructor(e,t){super("enhancedAckSent"),b(this,"connection"),b(this,"message"),this.connection=e,this.message=t}},Pe=class extends Event{constructor(e){super("error"),b(this,"error"),this.error=e}},dr=class extends Event{constructor(e){super("warning"),b(this,"error"),this.error=e}},mr=class extends Event{constructor(){super("close")}},ni="utf-8",Wd=5e3,Kd=60*1e3,si=class extends oi{constructor(e,t=ni,r,n={}){super(),b(this,"socket"),b(this,"encoding"),b(this,"enhancedMode"),b(this,"messagesPerMin"),b(this,"gracefulCloseTimeoutMs"),b(this,"chunks",[]),b(this,"pendingMessages",new Map),b(this,"responseQueue",[]),b(this,"lastMessageDispatchedTime",0),b(this,"responseQueueProcessing",!1),b(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=n.messagesPerMin,this.gracefulCloseTimeoutMs=n.gracefulCloseTimeoutMs??Wd,e.on("data",o=>{if(this.closing){this.dispatchEvent(new dr(new ae({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(o);let s=this.parseMessages();for(let i of s)this.responseQueue.push(new Bd(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new Pe(i))})}catch(s){this.dispatchEvent(new Pe(s))}}),e.on("error",o=>{this.resetBuffer(),this.dispatchEvent(new Pe(o))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new mr)}),this.addEventListener("message",o=>{let s;this.enhancedMode==="standard"?s=o.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(s=o.message.buildAck({ackCode:"AA"})),s&&(this.send(s),this.dispatchEvent(new qd(this,s)));let i=o.message.getSegment("MSA")?.getField(2)?.toString();if(!i)return;let a=this.getPendingMessage(i);if(!a){this.dispatchEvent(new dr(new ae({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${i}' but there was no pending message with this control ID`}]})));return}let l=o.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();l&&(a.returnAck===ti.APPLICATION&&l==="CA"||(a.timer&&clearTimeout(a.timer),a.resolve(o.message),this.deletePendingMessage(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=ri.encode(t,this.encoding),n=Buffer.alloc(r.length+3);n.writeInt8(11,0),r.copy(n,1),n.writeInt8(28,r.length+1),n.writeInt8(13,r.length+2),this.socket.write(n)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=Kd/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await Fd(t-r)}let e=this.responseQueue.shift();e&&this.dispatchEvent(e),this.lastMessageDispatchedTime=Date.now()}this.responseQueueProcessing=!1}}parseMessages(){let e=[],t=Buffer.concat(this.chunks);if(this.resetBuffer(),t.length===0)return e;let r=0;for(;r<t.length;){for(;t[r]!==11&&r<t.length;)r++;let n=-1;for(let a=r+1;a<t.length-1;a++)if(t[a]===28&&t[a+1]===13){n=a+1;break}if(n===-1)break;let o=t.subarray(r,n+1).subarray(1,-2),s=ri.decode(o,this.encoding),i=_d.parse(s);e.push(i),r=n+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,n)=>{let o=e.getSegment("MSH")?.getField(10)?.toString();if(!o){n(new ae(jd("Required field missing: MSH.10")));return}let s;t?.timeoutMs&&(s=setTimeout(()=>{this.deletePendingMessage(o),n(new ae({resourceType:"OperationOutcome",issue:[{severity:"error",code:"timeout",details:{text:"Client timeout"},diagnostics:`Request timed out after waiting ${t.timeoutMs} milliseconds for response`}]}))},t.timeoutMs)),this.setPendingMessage(o,{message:e,resolve:r,reject:n,returnAck:t?.returnAck??ti.APPLICATION,timer:s}),this.sendImpl(e)})}async close(){this.isClosed()||(this.closing=!0,this.socket.end(),this.drainPendingMessages(),await new Promise(e=>{let t=setTimeout(()=>{this.socket.destroy()},this.gracefulCloseTimeoutMs);this.socket.once("close",()=>{clearTimeout(t),e()})}))}drainPendingMessages(){if(!this.pendingMessages.size)return;let e=this.pendingMessages.size;for(let t of this.pendingMessages.values())t.timer&&clearTimeout(t.timer),t.reject(new ae({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Pe(new ae({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${e} messages were pending`}]}))),this.pendingMessages.clear()}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??ni}getEncoding(){return this.encoding}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}getPendingMessageCount(){return this.pendingMessages.size}getPendingMessage(e){return this.pendingMessages.get(e)}setPendingMessage(e,t){this.pendingMessages.set(e,t)}deletePendingMessage(e){this.pendingMessages.delete(e)}},ii=class extends oi{constructor(e){super(),b(this,"options"),b(this,"host"),b(this,"port"),b(this,"encoding"),b(this,"connection"),b(this,"keepAlive"),b(this,"socket"),b(this,"connectTimeout"),b(this,"deferredConnectionPromise"),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(){if(this.deferredConnectionPromise)return this.deferredConnectionPromise.promise;let e=this.deferredConnectionPromise=this.createDeferredConnectionPromise();return this.socket=Ud.connect({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.registerSocketTimeoutListener(e)),this.registerSocketConnectListener(e),this.registerSocketErrorListener(e),this.registerSocketCloseListener(e),e.promise}registerSocketTimeoutListener(e){lt(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let n=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,n)};t.on("timeout",r)}registerSocketConnectListener(e){lt(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let n;this.connection=n=this.createConnection(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(n),e.resolve(n)};t.on("connect",r)}registerSocketErrorListener(e){lt(this.socket);let t=this.socket,r=n=>{this.cleanupSocket(t),n.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,n.errors[0]):this.rejectDeferredPromise(e,n)};t.on("error",r)}registerSocketCloseListener(e){lt(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t),this.rejectDeferredPromise(e,new Error("Socket closed before connection finished"))};t.on("close",r)}registerHl7ConnectionListeners(e){e.addEventListener("close",()=>{this.socket=void 0,this.connection=void 0,this.deferredConnectionPromise=void 0,this.dispatchEvent(new mr)}),e.addEventListener("error",t=>{this.dispatchEvent(new Pe(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new dr(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}rejectDeferredPromise(e,t){e.reject(t),this.deferredConnectionPromise===e&&(this.deferredConnectionPromise=void 0)}cleanupSocket(e){e.destroyed||e.destroy(),e===this.socket&&(this.socket=void 0)}createConnection(e,t,r,n){return new si(e,t,r,n)}async send(e){return(await this.connect()).send(e)}async sendAndWait(e,t){return(await this.connect()).sendAndWait(e,t)}async close(){if(this.deferredConnectionPromise&&this.rejectDeferredPromise(this.deferredConnectionPromise,new Error("Client closed while connecting")),this.connection){let e=this.connection;delete this.connection,await e.close()}else this.dispatchEvent(new mr);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}};var Hd=1e4,ai=class{constructor(e){b(this,"handler"),b(this,"server"),b(this,"encoding"),b(this,"enhancedMode"),b(this,"messagesPerMin"),b(this,"connections",new Set),this.handler=e}async start(e,t,r,n){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),n?.messagesPerMin!==void 0&&this.setMessagesPerMin(n.messagesPerMin);let o=Vd.createServer(s=>{let i=new si(s,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(i),this.connections.add(i),i.addEventListener("close",()=>{this.connections.delete(i)})});return new Promise((s,i)=>{let a=u=>{o.listen(u,()=>{let m=o.address().port;s(m)})},l=u=>{u?.code==="EADDRINUSE"?o.close(()=>Gd(50).then(()=>a(e))):i(u)};o.on("error",l),o.once("listening",()=>{o.off("error",l)}),a(e),this.server=o})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let n;e?.forceDrainTimeoutMs!==-1&&(n=setTimeout(()=>{for(let o of this.connections)o.close().catch(console.error)},e?.forceDrainTimeoutMs??Hd)),this.server.close(o=>{if(o){r(o);return}n&&clearTimeout(n),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}};import{readFileSync as zd}from"node:fs";var Yd=new h("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,n)=>{if(n.generateExample?r=Zd():n.file&&(r=zd(n.file,"utf8")),!r)throw new Error("Missing HL7 message body");let o=new ii({host:e,port:Number.parseInt(t,10),encoding:n.encoding});try{let s=await o.sendAndWait(Xd.parse(r));console.log(s.toString().replaceAll("\r",`
20
+ `))}finally{await o.close()}}),Qd=new h("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{await new ai(n=>{n.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
21
+ `)),n.send(o.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),ut=new h("hl7");y(ut,Yd);y(ut,Qd);function Zd(){let e=Jd(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
22
22
  EVN|A01|${e}||
23
23
  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|
24
- PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}import{readdirSync as tm}from"node:fs";import{homedir as rm}from"node:os";import{resolve as nm}from"node:path";var gi=new h("set"),hi=new h("remove"),yi=new h("list"),wi=new h("describe"),ge=new h("profile");y(ge,gi);y(ge,hi);y(ge,yi);y(ge,wi);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(e,t)=>{Ge(e,t)});hi.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new W(e).setObject("options",void 0),console.log(`${e} profile removed`)});yi.description("List all profiles saved").action(async()=>{let e=nm(rm(),".medplum"),t=tm(e),r=[];t.forEach(n=>{let o=n.split(".")[0],i=new W(o).getObject("options");i&&r.push({profileName:o,profile:i})}),console.log(r)});wi.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=An(e);console.log(t)});import{Option as om}from"commander";var Ei=new h("list"),Si=new h("current"),Ri=new h("switch"),Ai=new h("invite"),he=new h("project");y(he,Ei);y(he,Si);y(he,Ri);y(he,Ai);Ei.description("List of current projects").action(async e=>{let t=await A(e);sm(t)});function sm(e){let r=e.getLogins().map(n=>`${n.project.display} (${n.project.reference})`).join(`
24
+ PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}import{readdirSync as em}from"node:fs";import{homedir as tm}from"node:os";import{resolve as rm}from"node:path";var ci=new h("set"),li=new h("remove"),ui=new h("list"),pi=new h("describe"),ce=new h("profile");y(ce,ci);y(ce,li);y(ce,ui);y(ce,pi);ci.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)=>{De(e,t)});li.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new U(e).setObject("options",void 0),console.log(`${e} profile removed`)});ui.description("List all profiles saved").action(async()=>{let e=rm(tm(),".medplum"),t=em(e),r=[];t.forEach(n=>{let o=n.split(".")[0],i=new U(o).getObject("options");i&&r.push({profileName:o,profile:i})}),console.log(r)});pi.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=gn(e);console.log(t)});import{Option as nm}from"commander";var di=new h("list"),mi=new h("current"),fi=new h("switch"),gi=new h("invite"),le=new h("project");y(le,di);y(le,mi);y(le,fi);y(le,gi);di.description("List of current projects").action(async e=>{let t=await R(e);om(t)});function om(e){let r=e.getLogins().map(n=>`${n.project.display} (${n.project.reference})`).join(`
25
25
 
26
- `);console.log(r)}Si.description("Project you are currently on").action(async e=>{let r=(await A(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});Ri.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await A(t);await im(r,e)});Ai.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 om("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,n)=>{let o=await A(n),s=o.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],a={resourceType:n.role,firstName:e,lastName:t,email:r,sendEmail:!!n.sendEmail,admin:!!n.admin};await am(i,a,o)});async function im(e,t){let n=e.getLogins().find(o=>o.project.reference?.includes(t));if(!n)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(n),console.log(`Switched to project ${t}
27
- `)}async function am(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")}import{convertToTransactionBundle as cm}from"@medplum/core";var Pr=new h("delete"),Ir=new h("get"),vr=new h("patch"),Cr=new h("post"),Tr=new h("put");Pr.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await A(t);X(await r.delete(ke(r,e)))});Ir.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await A(t),n=await r.get(ke(r,e));t.asTransaction?X(cm(n)):X(n)});vr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await A(r);X(await n.patch(ke(n,e),Or(t)))});Cr.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let n=await A(r),o=r.preferAsync?{Prefer:"respond-async"}:void 0;X(await n.post(ke(n,e),Or(t),void 0,{headers:o}))});Tr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await A(r);X(await n.put(ke(n,e),Or(t)))});function Or(e){if(e)try{return JSON.parse(e)}catch{return e}}function ke(e,t){return["admin/","auth/","fhir/R4"].some(n=>t.startsWith(n))?t:e.fhirUrl(t).toString()}async function dm(e){let t=new h("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>",'OAuth scope (e.g., "openid offline_access")').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 um("--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(lm),t.configureHelp({showGlobalOptions:!0}),y(t,qt),y(t,Kt),y(t,Gt),y(t,Ir),y(t,Cr),y(t,vr),y(t,Tr),y(t,Pr),y(t,he),y(t,Et),y(t,xe),y(t,Y),y(t,hr),y(t,yr),y(t,wr),y(t,ge),y(t,Xs()),y(t,Rt),y(t,Rr);try{await t.parseAsync(e)}catch(r){mm(r)}}function mm(e){let t=1,r=!0;if(e instanceof bi&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){xr(e,!!process.env.VERBOSE);let n=e.cause;if(process.env.VERBOSE)if(Array.isArray(n))for(let o of n)xr(o,!0);else n instanceof Error&&xr(n,!0)}process.exit(t)}function xr(e,t=!1){if(t){console.error(e);return}e instanceof bi?process.stderr.write(`${$r(e)}
28
- `):process.stderr.write(`Error: ${$r(e)}
29
- `)}async function fm(){pm.config({quiet:!0}),await dm(process.argv)}import.meta.main&&fm().catch(e=>{console.error("Unhandled error:",$r(e)),process.exit(1)});export{mm as handleError,dm as main,fm as run};
26
+ `);console.log(r)}mi.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})`)});fi.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await R(t);await sm(r,e)});gi.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 nm("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,n)=>{let o=await R(n),s=o.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],a={resourceType:n.role,firstName:e,lastName:t,email:r,sendEmail:!!n.sendEmail,admin:!!n.admin};await im(i,a,o)});async function sm(e,t){let n=e.getLogins().find(o=>o.project.reference?.includes(t));if(!n)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(n),console.log(`Switched to project ${t}
27
+ `)}async function im(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")}import{convertToTransactionBundle as am}from"@medplum/core";var fr=new h("delete"),gr=new h("get"),hr=new h("patch"),yr=new h("post"),wr=new h("put");fr.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await R(t);W(await r.delete(Ie(r,e)))});gr.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await R(t),n=await r.get(Ie(r,e));t.asTransaction?W(am(n)):W(n)});hr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await R(r);W(await n.patch(Ie(n,e),Er(t)))});yr.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let n=await R(r),o=r.preferAsync?{Prefer:"respond-async"}:void 0;W(await n.post(Ie(n,e),Er(t),void 0,{headers:o}))});wr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await R(r);W(await n.put(Ie(n,e),Er(t)))});function Er(e){if(e)try{return JSON.parse(e)}catch{return e}}function Ie(e,t){return["admin/","auth/","fhir/R4"].some(n=>t.startsWith(n))?t:e.fhirUrl(t).toString()}async function pm(e){let t=new h("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>",'OAuth scope (e.g., "openid offline_access")').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 lm("--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(cm),t.configureHelp({showGlobalOptions:!0}),y(t,kt),y(t,Dt),y(t,Mt),y(t,gr),y(t,yr),y(t,hr),y(t,wr),y(t,fr),y(t,le),y(t,ct),y(t,be),y(t,G),y(t,ir),y(t,ar),y(t,cr),y(t,ce),y(t,qs()),y(t,ut),y(t,pr);try{await t.parseAsync(e)}catch(r){dm(r)}}function dm(e){let t=1,r=!0;if(e instanceof hi&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){Sr(e,!!process.env.VERBOSE);let n=e.cause;if(process.env.VERBOSE)if(Array.isArray(n))for(let o of n)Sr(o,!0);else n instanceof Error&&Sr(n,!0)}process.exit(t)}function Sr(e,t=!1){if(t){console.error(e);return}e instanceof hi?process.stderr.write(`${Rr(e)}
28
+ `):process.stderr.write(`Error: ${Rr(e)}
29
+ `)}async function mm(){um.config({quiet:!0}),await pm(process.argv)}import.meta.main&&mm().catch(e=>{console.error("Unhandled error:",Rr(e)),process.exit(1)});export{dm as handleError,pm as main,mm as run};
30
30
  //# sourceMappingURL=index.mjs.map