@medplum/cli 5.1.26 → 5.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +1,25 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Gi=Object.create;var Oe=Object.defineProperty;var Vi=Object.getOwnPropertyDescriptor;var Ji=Object.getOwnPropertyNames;var Xi=Object.getPrototypeOf,zi=Object.prototype.hasOwnProperty;var Yi=(e,t,r)=>t in e?Oe(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}},Qi=(e,t)=>{for(var r in t)Oe(e,r,{get:t[r],enumerable:!0})},Hr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ji(t))!zi.call(e,s)&&s!==r&&Oe(e,s,{get:()=>t[s],enumerable:!(n=Vi(t,s))||n.enumerable});return e};var L=(e,t,r)=>(r=e!=null?Gi(Xi(e)):{},Hr(t||!e||!e.__esModule?Oe(r,"default",{value:e,enumerable:!0}):r,e)),Zi=e=>Hr(Oe({},"__esModule",{value:!0}),e);var b=(e,t,r)=>Yi(e,typeof t!="symbol"?t+"":t,r);var Ee=w((wm,Hn)=>{"use strict";var _a="2.0.0",Ua=Number.MAX_SAFE_INTEGER||9007199254740991,ja=16,Fa=250,Ba=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Hn.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ja,MAX_SAFE_BUILD_LENGTH:Fa,MAX_SAFE_INTEGER:Ua,RELEASE_TYPES:Ba,SEMVER_SPEC_VERSION:_a,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Ue=w((Em,Gn)=>{"use strict";var Wa=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};Gn.exports=Wa});var Se=w((V,Vn)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:ar,MAX_SAFE_BUILD_LENGTH:Ka,MAX_LENGTH:qa}=Ee(),Ha=Ue();V=Vn.exports={};var Ga=V.re=[],Va=V.safeRe=[],p=V.src=[],Ja=V.safeSrc=[],d=V.t={},Xa=0,cr="[a-zA-Z0-9-]",za=[["\\s",1],["\\d",qa],[cr,Ka]],Ya=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=Ya(t),s=Xa++;Ha(e,s,t),d[e]=s,p[s]=t,Ja[s]=n,Ga[s]=new RegExp(t,r?"g":void 0),Va[s]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${cr}*`);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",`${cr}+`);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,${ar}})(?:\\.(\\d{1,${ar}}))?(?:\\.(\\d{1,${ar}}))?`);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 at=w((Sm,Jn)=>{"use strict";var Qa=Object.freeze({loose:!0}),Za=Object.freeze({}),ec=e=>e?typeof e!="object"?Qa:e:Za;Jn.exports=ec});var lr=w((Rm,Yn)=>{"use strict";var Xn=/^[0-9]+$/,zn=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=Xn.test(e),n=Xn.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},tc=(e,t)=>zn(t,e);Yn.exports={compareIdentifiers:zn,rcompareIdentifiers:tc}});var O=w((Am,Zn)=>{"use strict";var ct=Ue(),{MAX_LENGTH:Qn,MAX_SAFE_INTEGER:lt}=Ee(),{safeRe:ut,t:pt}=Se(),rc=at(),{compareIdentifiers:ur}=lr(),nc=(e,t)=>{let r=t.split(".");if(r.length>e.length)return!1;for(let n=0;n<r.length;n++)if(ur(e[n],r[n])!==0)return!1;return!0},pr=class e{constructor(t,r){if(r=rc(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>Qn)throw new TypeError(`version is longer than ${Qn} characters`);ct("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?ut[pt.LOOSE]:ut[pt.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>lt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>lt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>lt||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let o=+s;if(o>=0&&o<lt)return o}return s}):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(ct("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],s=t.prerelease[r];if(ct("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return ur(n,s)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],s=t.build[r];if(ct("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return ur(n,s)}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 s=`-${r}`.match(this.options.loose?ut[pt.PRERELEASELOOSE]:ut[pt.PRERELEASE]);if(!s||s[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 s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let o=[r,s];if(n===!1&&(o=[r]),nc(this.prerelease,r)){let i=this.prerelease[r.split(".").length];isNaN(i)&&(this.prerelease=o)}else this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Zn.exports=pr});var oe=w((bm,ts)=>{"use strict";var es=O(),sc=(e,t,r=!1)=>{if(e instanceof es)return e;try{return new es(e,t)}catch(n){if(!r)return null;throw n}};ts.exports=sc});var ns=w((Pm,rs)=>{"use strict";var oc=oe(),ic=(e,t)=>{let r=oc(e,t);return r?r.version:null};rs.exports=ic});var os=w((Im,ss)=>{"use strict";var ac=oe(),cc=(e,t)=>{let r=ac(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};ss.exports=cc});var cs=w((vm,as)=>{"use strict";var is=O(),lc=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new is(e instanceof is?e.version:e,r).inc(t,n,s).version}catch{return null}};as.exports=lc});var ps=w((Cm,us)=>{"use strict";var ls=oe(),uc=(e,t)=>{let r=ls(e,null,!0),n=ls(t,null,!0),s=r.compare(n);if(s===0)return null;let o=s>0,i=o?r:n,a=o?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"};us.exports=uc});var ms=w((Tm,ds)=>{"use strict";var pc=O(),dc=(e,t)=>new pc(e,t).major;ds.exports=dc});var hs=w((Om,fs)=>{"use strict";var mc=O(),fc=(e,t)=>new mc(e,t).minor;fs.exports=fc});var ys=w((xm,gs)=>{"use strict";var hc=O(),gc=(e,t)=>new hc(e,t).patch;gs.exports=gc});var Es=w(($m,ws)=>{"use strict";var yc=oe(),wc=(e,t)=>{let r=yc(e,t);return r&&r.prerelease.length?r.prerelease:null};ws.exports=wc});var D=w((Nm,Rs)=>{"use strict";var Ss=O(),Ec=(e,t,r)=>new Ss(e,r).compare(new Ss(t,r));Rs.exports=Ec});var bs=w((km,As)=>{"use strict";var Sc=D(),Rc=(e,t,r)=>Sc(t,e,r);As.exports=Rc});var Is=w((Lm,Ps)=>{"use strict";var Ac=D(),bc=(e,t)=>Ac(e,t,!0);Ps.exports=bc});var dt=w((Mm,Cs)=>{"use strict";var vs=O(),Pc=(e,t,r)=>{let n=new vs(e,r),s=new vs(t,r);return n.compare(s)||n.compareBuild(s)};Cs.exports=Pc});var Os=w((Dm,Ts)=>{"use strict";var Ic=dt(),vc=(e,t)=>e.sort((r,n)=>Ic(r,n,t));Ts.exports=vc});var $s=w((_m,xs)=>{"use strict";var Cc=dt(),Tc=(e,t)=>e.sort((r,n)=>Cc(n,r,t));xs.exports=Tc});var je=w((Um,Ns)=>{"use strict";var Oc=D(),xc=(e,t,r)=>Oc(e,t,r)>0;Ns.exports=xc});var mt=w((jm,ks)=>{"use strict";var $c=D(),Nc=(e,t,r)=>$c(e,t,r)<0;ks.exports=Nc});var dr=w((Fm,Ls)=>{"use strict";var kc=D(),Lc=(e,t,r)=>kc(e,t,r)===0;Ls.exports=Lc});var mr=w((Bm,Ms)=>{"use strict";var Mc=D(),Dc=(e,t,r)=>Mc(e,t,r)!==0;Ms.exports=Dc});var ft=w((Wm,Ds)=>{"use strict";var _c=D(),Uc=(e,t,r)=>_c(e,t,r)>=0;Ds.exports=Uc});var ht=w((Km,_s)=>{"use strict";var jc=D(),Fc=(e,t,r)=>jc(e,t,r)<=0;_s.exports=Fc});var fr=w((qm,Us)=>{"use strict";var Bc=dr(),Wc=mr(),Kc=je(),qc=ft(),Hc=mt(),Gc=ht(),Vc=(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 Bc(e,r,n);case"!=":return Wc(e,r,n);case">":return Kc(e,r,n);case">=":return qc(e,r,n);case"<":return Hc(e,r,n);case"<=":return Gc(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Us.exports=Vc});var Fs=w((Hm,js)=>{"use strict";var Jc=O(),Xc=oe(),{safeRe:gt,t:yt}=Se(),zc=(e,t)=>{if(e instanceof Jc)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?gt[yt.COERCEFULL]:gt[yt.COERCE]);else{let l=t.includePrerelease?gt[yt.COERCERTLFULL]:gt[yt.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],s=r[3]||"0",o=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Xc(`${n}.${s}.${o}${i}${a}`,t)};js.exports=zc});var Ws=w((Gm,Bs)=>{"use strict";var Yc=oe(),Qc=Ee(),Zc=O(),el=(e,t,r)=>{if(!Qc.RELEASE_TYPES.includes(t))return null;let n=tl(e,r);return n&&rl(n,t)},tl=(e,t)=>{let r=e instanceof Zc?e.version:e;return Yc(r,t)},rl=(e,t)=>{if(nl(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()},nl=e=>e.startsWith("pre");Bs.exports=el});var qs=w((Vm,Ks)=>{"use strict";var hr=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 s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}};Ks.exports=hr});var _=w((Jm,Js)=>{"use strict";var sl=/\s+/g,gr=class e{constructor(t,r){if(r=il(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof yr)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(sl," "),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(s=>!Gs(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&hl(s[0])){this.set=[s];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(fl,"");let n=((this.options.includePrerelease&&dl)|(this.options.loose&&ml))+":"+t,s=Hs.get(n);if(s)return s;let o=this.options.loose,i=o?N[x.HYPHENRANGELOOSE]:N[x.HYPHENRANGE];t=t.replace(i,vl(this.options.includePrerelease)),P("hyphen replace",t),t=t.replace(N[x.COMPARATORTRIM],ll),P("comparator trim",t),t=t.replace(N[x.TILDETRIM],ul),P("tilde trim",t),t=t.replace(N[x.CARETTRIM],pl),P("caret trim",t);let a=t.split(" ").map(m=>gl(m,this.options)).join(" ").split(/\s+/).map(m=>Il(m,this.options));o&&(a=a.filter(m=>(P("loose invalid filter",m,this.options),!!m.match(N[x.COMPARATORLOOSE])))),P("range list",a);let l=new Map,u=a.map(m=>new yr(m,this.options));for(let m of u){if(Gs(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let f=[...l.values()];return Hs.set(n,f),f}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Vs(n,r)&&t.set.some(s=>Vs(s,r)&&n.every(o=>s.every(i=>o.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new al(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(Cl(this.set[r],t,this.options))return!0;return!1}};Js.exports=gr;var ol=qs(),Hs=new ol,il=at(),yr=Fe(),P=Ue(),al=O(),{safeRe:N,src:cl,t:x,comparatorTrimReplace:ll,tildeTrimReplace:ul,caretTrimReplace:pl}=Se(),{FLAG_INCLUDE_PRERELEASE:dl,FLAG_LOOSE:ml}=Ee(),fl=new RegExp(cl[x.BUILD],"g"),Gs=e=>e.value==="<0.0.0-0",hl=e=>e.value==="",Vs=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(o=>s.intersects(o,t)),s=n.pop();return r},gl=(e,t)=>(e=e.replace(N[x.BUILD],""),P("comp",e,t),e=Sl(e,t),P("caret",e),e=wl(e,t),P("tildes",e),e=Al(e,t),P("xrange",e),e=Pl(e,t),P("stars",e),e),C=e=>!e||e.toLowerCase()==="x"||e==="*",yl=(e,t,r)=>C(e)&&!C(t)||C(t)&&r&&!C(r),wl=(e,t)=>e.trim().split(/\s+/).map(r=>El(r,t)).join(" "),El=(e,t)=>{let r=t.loose?N[x.TILDELOOSE]:N[x.TILDE],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,a,l)=>{P("tilde",e,s,o,i,a,l);let u;return C(o)?u="":C(i)?u=`>=${o}.0.0${n} <${+o+1}.0.0-0`:C(a)?u=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:l?(P("replaceTilde pr",l),u=`>=${o}.${i}.${a}-${l} <${o}.${+i+1}.0-0`):u=`>=${o}.${i}.${a} <${o}.${+i+1}.0-0`,P("tilde return",u),u})},Sl=(e,t)=>e.trim().split(/\s+/).map(r=>Rl(r,t)).join(" "),Rl=(e,t)=>{P("caret",e,t);let r=t.loose?N[x.CARETLOOSE]:N[x.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,a,l)=>{P("caret",e,s,o,i,a,l);let u;return C(o)?u="":C(i)?u=`>=${o}.0.0${n} <${+o+1}.0.0-0`:C(a)?o==="0"?u=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.0${n} <${+o+1}.0.0-0`:l?(P("replaceCaret pr",l),o==="0"?i==="0"?u=`>=${o}.${i}.${a}-${l} <${o}.${i}.${+a+1}-0`:u=`>=${o}.${i}.${a}-${l} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.${a}-${l} <${+o+1}.0.0-0`):(P("no pr"),o==="0"?i==="0"?u=`>=${o}.${i}.${a} <${o}.${i}.${+a+1}-0`:u=`>=${o}.${i}.${a} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.${a} <${+o+1}.0.0-0`),P("caret return",u),u})},Al=(e,t)=>(P("replaceXRanges",e,t),e.split(/\s+/).map(r=>bl(r,t)).join(" ")),bl=(e,t)=>{e=e.trim();let r=t.loose?N[x.XRANGELOOSE]:N[x.XRANGE];return e.replace(r,(n,s,o,i,a,l)=>{if(P("xRange",e,n,s,o,i,a,l),yl(o,i,a))return e;let u=C(o),f=u||C(i),m=f||C(a),S=m;return s==="="&&S&&(s=""),l=t.includePrerelease?"-0":"",u?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&S?(f&&(i=0),a=0,s===">"?(s=">=",f?(o=+o+1,i=0,a=0):(i=+i+1,a=0)):s==="<="&&(s="<",f?o=+o+1:i=+i+1),s==="<"&&(l="-0"),n=`${s+o}.${i}.${a}${l}`):f?n=`>=${o}.0.0${l} <${+o+1}.0.0-0`:m&&(n=`>=${o}.${i}.0${l} <${o}.${+i+1}.0-0`),P("xRange return",n),n})},Pl=(e,t)=>(P("replaceStars",e,t),e.trim().replace(N[x.STAR],"")),Il=(e,t)=>(P("replaceGTE0",e,t),e.trim().replace(N[t.includePrerelease?x.GTE0PRE:x.GTE0],"")),vl=e=>(t,r,n,s,o,i,a,l,u,f,m,S)=>(C(n)?r="":C(s)?r=`>=${n}.0.0${e?"-0":""}`:C(o)?r=`>=${n}.${s}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,C(u)?l="":C(f)?l=`<${+u+1}.0.0-0`:C(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()),Cl=(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!==yr.ANY&&e[n].semver.prerelease.length>0){let s=e[n].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}});var Fe=w((Xm,eo)=>{"use strict";var Be=Symbol("SemVer ANY"),Sr=class e{static get ANY(){return Be}constructor(t,r){if(r=Xs(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Er("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Be?this.value="":this.value=this.operator+this.semver.version,Er("comp",this)}parse(t){let r=this.options.loose?zs[Ys.COMPARATORLOOSE]:zs[Ys.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 Qs(n[2],this.options.loose):this.semver=Be}toString(){return this.value}test(t){if(Er("Comparator.test",t,this.options.loose),this.semver===Be||t===Be)return!0;if(typeof t=="string")try{t=new Qs(t,this.options)}catch{return!1}return wr(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 Zs(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Zs(this.value,r).test(t.semver):(r=Xs(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("=")||wr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||wr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};eo.exports=Sr;var Xs=at(),{safeRe:zs,t:Ys}=Se(),wr=fr(),Er=Ue(),Qs=O(),Zs=_()});var We=w((zm,to)=>{"use strict";var Tl=_(),Ol=(e,t,r)=>{try{t=new Tl(t,r)}catch{return!1}return t.test(e)};to.exports=Ol});var no=w((Ym,ro)=>{"use strict";var xl=_(),$l=(e,t)=>new xl(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));ro.exports=$l});var oo=w((Qm,so)=>{"use strict";var Nl=O(),kl=_(),Ll=(e,t,r)=>{let n=null,s=null,o=null;try{o=new kl(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===-1)&&(n=i,s=new Nl(n,r))}),n};so.exports=Ll});var ao=w((Zm,io)=>{"use strict";var Ml=O(),Dl=_(),_l=(e,t,r)=>{let n=null,s=null,o=null;try{o=new Dl(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===1)&&(n=i,s=new Ml(n,r))}),n};io.exports=_l});var uo=w((ef,lo)=>{"use strict";var Rr=O(),Ul=_(),co=je(),jl=(e,t)=>{e=new Ul(e,t);let r=new Rr("0.0.0");if(e.test(r)||(r=new Rr("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n<e.set.length;++n){let s=e.set[n],o=null;s.forEach(i=>{let a=new Rr(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||co(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),o&&(!r||co(r,o))&&(r=o)}return r&&e.test(r)?r:null};lo.exports=jl});var mo=w((tf,po)=>{"use strict";var Fl=_(),Bl=(e,t)=>{try{return new Fl(e,t).range||"*"}catch{return null}};po.exports=Bl});var wt=w((rf,yo)=>{"use strict";var Wl=O(),go=Fe(),{ANY:Kl}=go,ql=_(),Hl=We(),fo=je(),ho=mt(),Gl=ht(),Vl=ft(),Jl=(e,t,r,n)=>{e=new Wl(e,n),t=new ql(t,n);let s,o,i,a,l;switch(r){case">":s=fo,o=Gl,i=ho,a=">",l=">=";break;case"<":s=ho,o=Vl,i=fo,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Hl(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(h=>{h.semver===Kl&&(h=new go(">=0.0.0")),m=m||h,S=S||h,s(h.semver,m.semver,n)?m=h:i(h.semver,S.semver,n)&&(S=h)}),m.operator===a||m.operator===l||(!S.operator||S.operator===a)&&o(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};yo.exports=Jl});var Eo=w((nf,wo)=>{"use strict";var Xl=wt(),zl=(e,t,r)=>Xl(e,t,">",r);wo.exports=zl});var Ro=w((sf,So)=>{"use strict";var Yl=wt(),Ql=(e,t,r)=>Yl(e,t,"<",r);So.exports=Ql});var Po=w((of,bo)=>{"use strict";var Ao=_(),Zl=(e,t,r)=>(e=new Ao(e,r),t=new Ao(t,r),e.intersects(t,r));bo.exports=Zl});var vo=w((af,Io)=>{"use strict";var eu=We(),tu=D();Io.exports=(e,t,r)=>{let n=[],s=null,o=null,i=e.sort((f,m)=>tu(f,m,r));for(let f of i)eu(f,t,r)?(o=f,s||(s=f)):(o&&n.push([s,o]),o=null,s=null);s&&n.push([s,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 No=w((cf,$o)=>{"use strict";var Co=_(),Pr=Fe(),{ANY:Ar}=Pr,br=We(),Ir=D(),ru=(e,t,r={})=>{if(e===t)return!0;e=new Co(e,r),t=new Co(t,r);let n=!1;e:for(let s of e.set){for(let o of t.set){let i=su(s,o,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},nu=[new Pr(">=0.0.0-0")],To=[new Pr(">=0.0.0")],su=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Ar){if(t.length===1&&t[0].semver===Ar)return!0;r.includePrerelease?e=nu:e=To}if(t.length===1&&t[0].semver===Ar){if(r.includePrerelease)return!0;t=To}let n=new Set,s,o;for(let h of e)h.operator===">"||h.operator===">="?s=Oo(s,h,r):h.operator==="<"||h.operator==="<="?o=xo(o,h,r):n.add(h.semver);if(n.size>1)return null;let i;if(s&&o){if(i=Ir(s.semver,o.semver,r),i>0)return null;if(i===0&&(s.operator!==">="||o.operator!=="<="))return null}for(let h of n){if(s&&!br(h,String(s),r)||o&&!br(h,String(o),r))return null;for(let fe of t)if(!br(h,String(fe),r))return!1;return!0}let a,l,u,f,m=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1,S=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;m&&m.prerelease.length===1&&o.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let h of t){if(f=f||h.operator===">"||h.operator===">=",u=u||h.operator==="<"||h.operator==="<=",s){if(S&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===S.major&&h.semver.minor===S.minor&&h.semver.patch===S.patch&&(S=!1),h.operator===">"||h.operator===">="){if(a=Oo(s,h,r),a===h&&a!==s)return!1}else if(s.operator===">="&&!h.test(s.semver))return!1}if(o){if(m&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===m.major&&h.semver.minor===m.minor&&h.semver.patch===m.patch&&(m=!1),h.operator==="<"||h.operator==="<="){if(l=xo(o,h,r),l===h&&l!==o)return!1}else if(o.operator==="<="&&!h.test(o.semver))return!1}if(!h.operator&&(o||s)&&i!==0)return!1}return!(s&&u&&!o&&i!==0||o&&f&&!s&&i!==0||S||m)},Oo=(e,t,r)=>{if(!e)return t;let n=Ir(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},xo=(e,t,r)=>{if(!e)return t;let n=Ir(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};$o.exports=ru});var Cr=w((lf,Mo)=>{"use strict";var vr=Se(),ko=Ee(),ou=O(),Lo=lr(),iu=oe(),au=ns(),cu=os(),lu=cs(),uu=ps(),pu=ms(),du=hs(),mu=ys(),fu=Es(),hu=D(),gu=bs(),yu=Is(),wu=dt(),Eu=Os(),Su=$s(),Ru=je(),Au=mt(),bu=dr(),Pu=mr(),Iu=ft(),vu=ht(),Cu=fr(),Tu=Fs(),Ou=Ws(),xu=Fe(),$u=_(),Nu=We(),ku=no(),Lu=oo(),Mu=ao(),Du=uo(),_u=mo(),Uu=wt(),ju=Eo(),Fu=Ro(),Bu=Po(),Wu=vo(),Ku=No();Mo.exports={parse:iu,valid:au,clean:cu,inc:lu,diff:uu,major:pu,minor:du,patch:mu,prerelease:fu,compare:hu,rcompare:gu,compareLoose:yu,compareBuild:wu,sort:Eu,rsort:Su,gt:Ru,lt:Au,eq:bu,neq:Pu,gte:Iu,lte:vu,cmp:Cu,coerce:Tu,truncate:Ou,Comparator:xu,Range:$u,satisfies:Nu,toComparators:ku,maxSatisfying:Lu,minSatisfying:Mu,minVersion:Du,validRange:_u,outside:Uu,gtr:ju,ltr:Fu,intersects:Bu,simplifyRange:Wu,subset:Ku,SemVer:ou,re:vr.re,src:vr.src,tokens:vr.t,SEMVER_SPEC_VERSION:ko.SEMVER_SPEC_VERSION,RELEASE_TYPES:ko.RELEASE_TYPES,compareIdentifiers:Lo.compareIdentifiers,rcompareIdentifiers:Lo.rcompareIdentifiers}});var Dp={};Qi(Dp,{handleError:()=>Ki,main:()=>Wi,run:()=>qi});module.exports=Zi(Dp);var Te=require("@medplum/core"),ze=require("commander"),Bi=L(require("dotenv"),1);var F=require("@medplum/core"),De=require("commander");var Jr=require("@medplum/core");var Gr=require("@medplum/core"),X=require("node:fs"),Vr=require("node:os"),Bt=require("node:path");var K=class extends Gr.ClientStorage{constructor(r){super();b(this,"dirName");b(this,"fileName");this.dirName=(0,Bt.resolve)((0,Vr.homedir)(),".medplum"),this.fileName=(0,Bt.resolve)(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,n){let s=this.readFile()??{};n?s[r]=n:delete s[r],this.writeFile(s)}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((0,X.existsSync)(this.fileName))return JSON.parse((0,X.readFileSync)(this.fileName,"utf8"))}writeFile(r){(0,X.existsSync)(this.dirName)||(0,X.mkdirSync)(this.dirName),(0,X.writeFileSync)(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function A(e,t=!0){let r=e.profile??"default",n=new K(r),s=n.getObject("options");if(r!=="default"&&!s)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:o,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:f,clientSecret:m}=ea(e,n),S=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await ta(e.baseUrl,S);let h=new Jr.MedplumClient({fetch:S,baseUrl:o,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:n,onUnauthenticated:ra,verbose:e.verbose});return t&&(a?h.setAccessToken(a):f&&m&&(h.setBasicAuth(f,m),s?.authType!=="basic"&&await h.startClientLogin(f,m))),h}function ea(e,t){let r=t.getObject("options"),n=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",s=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,o=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:s,accessToken:o,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}async function ta(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 ra(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var H=require("@medplum/core"),En=require("commander");var zr=require("node:buffer");var ce=new TextEncoder,Wt=new TextDecoder,Wp=2**32;function Xr(...e){let t=e.reduce((s,{length:o})=>s+o,0),r=new Uint8Array(t),n=0;for(let s of e)r.set(s,n),n+=s.length;return r}var Ye=e=>zr.Buffer.from(e).toString("base64url");var le=class extends Error{constructor(r,n){super(r,n);b(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};b(le,"code","ERR_JOSE_GENERIC");var M=class extends le{constructor(){super(...arguments);b(this,"code","ERR_JOSE_NOT_SUPPORTED")}};b(M,"code","ERR_JOSE_NOT_SUPPORTED");var z=class extends le{constructor(){super(...arguments);b(this,"code","ERR_JWS_INVALID")}};b(z,"code","ERR_JWS_INVALID");var xe=class extends le{constructor(){super(...arguments);b(this,"code","ERR_JWT_INVALID")}};b(xe,"code","ERR_JWT_INVALID");var Yr,Qr,Kt=class extends(Qr=le,Yr=Symbol.asyncIterator,Qr){constructor(r="multiple matching keys found in the JSON Web Key Set",n){super(r,n);b(this,Yr);b(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};b(Kt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Zr=L(require("node:util"),1),Qe=e=>Zr.types.isKeyObject(e);var en=L(require("node:crypto"),1),tn=L(require("node:util"),1),sa=en.webcrypto,rn=sa,he=e=>tn.types.isCryptoKey(e);function q(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function $e(e,t){return e.name===t}function qt(e){return parseInt(e.name.slice(4),10)}function oa(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ia(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function nn(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!$e(e.algorithm,"HMAC"))throw q("HMAC");let n=parseInt(t.slice(2),10);if(qt(e.algorithm.hash)!==n)throw q(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!$e(e.algorithm,"RSASSA-PKCS1-v1_5"))throw q("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(qt(e.algorithm.hash)!==n)throw q(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!$e(e.algorithm,"RSA-PSS"))throw q("RSA-PSS");let n=parseInt(t.slice(2),10);if(qt(e.algorithm.hash)!==n)throw q(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw q("Ed25519 or Ed448");break}case"Ed25519":{if(!$e(e.algorithm,"Ed25519"))throw q("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!$e(e.algorithm,"ECDSA"))throw q("ECDSA");let n=oa(t);if(e.algorithm.namedCurve!==n)throw q(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ia(e,r)}function sn(e,t,...r){if(r=r.filter(Boolean),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 Ne=(e,...t)=>sn("Key must be ",e,...t);function Ht(e,t,...r){return sn(`Key for the ${e} algorithm must be `,t,...r)}var Gt=e=>Qe(e)||he(e),Y=["KeyObject"];(globalThis.CryptoKey||rn?.CryptoKey)&&Y.push("CryptoKey");var aa=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(let o of s){if(r.has(o))return!1;r.add(o)}}return!0},on=aa;function ca(e){return typeof e=="object"&&e!==null}function ke(e){if(!ca(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var pn=require("node:crypto");function te(e){return ke(e)&&typeof e.kty=="string"}function an(e){return e.kty!=="oct"&&typeof e.d=="string"}function cn(e){return e.kty!=="oct"&&typeof e.d>"u"}function ln(e){return te(e)&&e.kty==="oct"&&typeof e.k=="string"}var la=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new M("Unsupported key curve for this operation")}},ua=(e,t)=>{let r;if(he(e))r=pn.KeyObject.from(e);else if(Qe(e))r=e;else{if(te(e))return e.crv;throw new TypeError(Ne(e,...Y))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let n=r.asymmetricKeyDetails.namedCurve;return t?n:la(n)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},dn=ua;var mn=require("node:crypto"),Vt=(e,t)=>{let r;try{e instanceof mn.KeyObject?r=e.asymmetricKeyDetails?.modulusLength:r=Buffer.from(e.n,"base64url").byteLength<<3}catch{}if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};var ge=e=>e?.[Symbol.toStringTag],Jt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},pa=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&te(t)){if(ln(t)&&Jt(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Gt(t))throw new TypeError(Ht(e,t,...Y,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${ge(t)} instances for symmetric algorithms must be of type "secret"`)}},da=(e,t,r,n)=>{if(n&&te(t))switch(r){case"sign":if(an(t)&&Jt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(cn(t)&&Jt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Gt(t))throw new TypeError(Ht(e,t,...Y,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${ge(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${ge(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${ge(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${ge(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${ge(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function fn(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?pa(t,r,n,e):da(t,r,n,e)}var dd=fn.bind(void 0,!1),hn=fn.bind(void 0,!0);function ma(e,t,r,n,s){if(s.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 new Set;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 o;r!==void 0?o=new Map([...Object.entries(r),...t.entries()]):o=t;for(let i of n.crit){if(!o.has(i))throw new M(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(o.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var gn=ma;function Xt(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Le=require("node:crypto");var fa=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function zt(e,t){let r,n,s;if(t instanceof Le.KeyObject)r=t.asymmetricKeyType,n=t.asymmetricKeyDetails;else switch(s=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let o;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Vt(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:i,mgf1HashAlgorithm:a,saltLength:l}=n,u=parseInt(e.slice(-3),10);if(i!==void 0&&(i!==`sha${u}`||a!==i))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(l!==void 0&&l>u>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Vt(t,e),o={padding:Le.constants.RSA_PKCS1_PSS_PADDING,saltLength:Le.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(r!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let i=dn(t),a=fa.get(e);if(i!==a)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${a}, got ${i}`);o={dsaEncoding:"ieee-p1363"};break}default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return s?{format:"jwk",key:t,...o}:o?{...o,key:t}:t}var Ze=L(require("node:crypto"),1),yn=require("node:util");function Yt(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var ye=require("node:crypto");function Qt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Ne(t,...Y));return(0,ye.createSecretKey)(t)}if(t instanceof ye.KeyObject)return t;if(he(t))return nn(t,e,r),ye.KeyObject.from(t);if(te(t))return e.startsWith("HS")?(0,ye.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError(Ne(t,...Y,"Uint8Array","JSON Web Key"))}var ha=(0,yn.promisify)(Ze.sign),ga=async(e,t,r)=>{let n=Qt(e,t,"sign");if(e.startsWith("HS")){let s=Ze.createHmac(Yt(e),n);return s.update(r),s.digest()}return ha(Xt(e),r,zt(e,n))},wn=ga;var re=e=>Math.floor(e.getTime()/1e3);var ya=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,et=e=>{let t=ya.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*3600);break;case"day":case"days":case"d":s=Math.round(r*86400);break;case"week":case"weeks":case"w":s=Math.round(r*604800);break;default:s=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-s:s};var tt=class{constructor(t){b(this,"_payload");b(this,"_protectedHeader");b(this,"_unprotectedHeader");if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!on(this._protectedHeader,this._unprotectedHeader))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},s=gn(z,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),o=!0;if(s.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');hn(i,t,"sign");let a=this._payload;o&&(a=ce.encode(Ye(a)));let l;this._protectedHeader?l=ce.encode(Ye(JSON.stringify(this._protectedHeader))):l=ce.encode("");let u=Xr(l,ce.encode("."),a),f=await wn(i,t,u),m={signature:Ye(f),payload:""};return o&&(m.payload=Wt.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=Wt.decode(l)),m}};var rt=class{constructor(t){b(this,"_flattened");this._flattened=new tt(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};function ue(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var nt=class{constructor(t={}){b(this,"_payload");if(!ke(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:ue("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:ue("setNotBefore",re(t))}:this._payload={...this._payload,nbf:re(new Date)+et(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:ue("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:ue("setExpirationTime",re(t))}:this._payload={...this._payload,exp:re(new Date)+et(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:re(new Date)}:t instanceof Date?this._payload={...this._payload,iat:ue("setIssuedAt",re(t))}:typeof t=="string"?this._payload={...this._payload,iat:ue("setIssuedAt",re(new Date)+et(t))}:this._payload={...this._payload,iat:ue("setIssuedAt",t)},this}};var Me=class extends nt{constructor(){super(...arguments);b(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,n){let s=new rt(ce.encode(JSON.stringify(this._payload)));if(s.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new xe("JWTs MUST NOT use unencoded payload");return s.sign(r,n)}};var we=require("node:crypto"),ne=require("node:fs"),Q=require("node:path"),Sn=require("node:util/types"),Rn=require("tar");function Z(e){console.log(JSON.stringify(e,null,2))}async function Zt(e,t,r){let n=t.source,s=st(n);if(!s)return;console.log("Saving source code...");let o=await e.createAttachment({data:s,filename:(0,Q.basename)(n),contentType:Sa(n)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:o});console.log("Success! New bot version: "+i.meta?.versionId)}async function er(e,t,r){let n=t.dist??t.source,s=st(n);if(!s)return;console.log("Deploying bot...");let o=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:s,filename:(0,Q.basename)(n)});console.log("Deploy result: "+o.issue?.[0]?.details?.text)}async function tr(e,t,r,n,s,o,i){let a={name:t,description:"",runtimeVersion:o},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:s};await Zt(e,f,u),await er(e,f,u),console.log(`Success! Bot created: ${u.id}`),i&&wa(f)}function An(e){let t=new RegExp("^"+Ea(e).replaceAll(String.raw`\*`,".*")+"$"),r=G()?.bots?.filter(n=>t.test(n.name));return r||[]}function j(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 v(e,t){(0,ne.writeFileSync)((0,Q.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function G(e,t){let r=j(e,t),n=st(r);if(n)return JSON.parse(n)}function bn(e){let t=st(j(e,{server:!0}));if(t)return JSON.parse(t)}function st(e){let t=(0,Q.resolve)(e);return(0,ne.existsSync)(t)?(0,ne.readFileSync)(t,"utf8"):""}function wa(e){let t=G()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ne.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Ea(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Pn(e){let n=0,s=0;return(0,Rn.extract)({cwd:e,filter:(o,i)=>{if(n++,n>100)throw new Error("Tar extractor reached max number of files");if(s+=i.size,s>10485760)throw new Error("Tar extractor reached max size");return!0}})}function rr(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function Sa(e){let t=(0,Q.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?H.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?H.ContentType.TYPESCRIPT:H.ContentType.TEXT}function ot(e,t){let r=new K(e),n={name:e,...t};return r.setObject("options",n),n}function In(e){return new K(e).getObject("options")}async function vn(e,t){let r={typ:"JWT",alg:H.OAuthSigningAlgorithm.HS256},n=Math.floor(Date.now()/1e3),s={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:n,iat:n,exp:n+604800},o=(0,H.encodeBase64)(JSON.stringify(r)),i=(0,H.encodeBase64)(JSON.stringify(s)),a=`${o}.${i}`,l=(0,we.createHmac)("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Cn(e,t){let r=(0,we.createPrivateKey)((0,ne.readFileSync)((0,Q.resolve)(t.privateKeyPath))),n=await new Me({}).setProtectedHeader({typ:"JWT",alg:H.OAuthSigningAlgorithm.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,we.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(n)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var g=class extends En.Command{action(t){let r=Ra(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 Ra(e,t){return async r=>{let n=e.registeredArguments.length,s=r.slice(0,n);s[n]=e.optsWithGlobals();try{let o=t(...s);(0,Sn.isPromise)(o)&&await o}finally{e.resetOptionDefaults()}}}var $n=new g("status").aliases(["info","list","ls"]),Nn=new g("ping"),kn=new g("push"),Ln=new g("reload-config"),Mn=new g("upgrade"),Dn=new g("stats"),se=new g("agent");y(se,$n);y(se,Nn);y(se,kn);y(se,Ln);y(se,Mn);y(se,Dn);$n.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 De.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await it({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let n=Un(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"}}})});Nn.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),s=await _n(n,t,r),o=Number.parseInt(r.count,10);if(Number.isNaN(o))throw new Error("--count <count> must be an integer if specified");try{let i=await n.pushToAgent(s,e,`PING ${o}`,F.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});kn.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",F.ContentType.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,n)=>{let s=await A(n),o=await _n(s,r,n),i;try{i=await s.pushToAgent(o,{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)});Ln.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 De.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await it({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Mn.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 De.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{let r={};t.agentVersion&&(r.version=t.agentVersion),t.force&&(r.force=!0),await it({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 De.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await it({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:n}=Un(r.result,{required:["stats"]}),s;try{s=JSON.parse(n)}catch(o){console.error(`Failed to parse stats for agent ${r.agent.id}: ${(0,F.normalizeErrorString)(o)}`)}return{id:r.agent.id,name:r.agent.name,stats:s}},renderSuccessfulRows:r=>{for(let n=0;n<r.length;n++)n>0&&console.info(),Aa(r[n])}})});var Tn=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function On(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function xn(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 Aa(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 Tn)r[i]=On(e.stats[i]);let n=new Set([...Tn,"channelStats","clientStats"]);for(let[i,a]of Object.entries(e.stats))n.has(i)||(r[i]=On(a));console.table(r);let s=xn(e.stats.channelStats);s.length&&(console.info("Channel Stats:"),console.table(s));let o=xn(e.stats.clientStats);o.length&&(console.info("Client Stats:"),console.table(o))}async function it({operation:e,agentIds:t,options:r,params:n={},parseSuccessfulResponse:s,renderSuccessfulRows:o}){let i=va(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[T,J]of Object.entries(n))u.append(T,J.toString());let f;try{let T=a.fhirUrl("Agent",e);T.search=u.toString(),f=await a.get(T,{cache:"reload"})}catch(T){throw new Error(`Operation '${e}' failed`,{cause:T})}if(r.output==="json"){console.info(JSON.stringify(f,null,2));return}let m=[],S=[];switch(f.resourceType){case"Bundle":{let T=ba(f);for(let J of T)J.result.resourceType==="Parameters"||(0,F.isOk)(J.result)?m.push(J):S.push(J);break}case"Parameters":case"OperationOutcome":{let T=await a.searchOne("Agent",u,{cache:"reload"});if(!T)throw new Error("Agent not found");f.resourceType==="Parameters"?m.push({agent:T,result:f}):S.push({agent:T,result:f});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(f)}`)}let h=[];for(let T of m){let J=s(T);h.push(J)}let fe=[];for(let T of S){let Ft=T.result.issue?.[0],Hi={id:T.agent.id,name:T.agent.name,severity:Ft.severity,code:Ft.code,details:Ft.details?.text??"No details to show"};fe.push(Hi)}console.info(`
3
- ${h.length} successful response(s):
4
- `),o?h.length?o(h):console.info("No successful responses received"):console.table(h.length?h:"No successful responses received"),console.info(),fe.length&&(console.info(`${fe.length} failed response(s):`),console.info(),console.table(fe))}async function _n(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{jn(r.criteria);let s=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!s?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(s.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=s.entry[0].resource?.id}return{reference:`Agent/${n}`}}function ba(e){let t=[];for(let r of e.entry??F.EMPTY){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(Pa(r.resource))}return t}function Pa(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 Un(e,t){let r={},n=t.required,s=t.optional;for(let o of n){let i=e.parameter?.find(l=>l.name===o);if(!i)throw new Error(`Failed to find parameter '${o}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${o}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${o}'`);r[o]=i[a]}if(s?.length)for(let o of s){let i=e.parameter?.find(l=>l.name===o);if(!i)continue;let a=Ia(o,i);r[o]=a}return r}function Ia(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 va(e,t){if(!Array.isArray(e))throw new Error("Invalid agent IDs array");if(e.length){if(t.criteria)throw new Error("Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive");for(let r of e)if(!(0,F.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return jn(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function jn(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(s){throw new Error(t,{cause:s})}if(!n.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}var B=require("@medplum/core"),Fn=require("node:child_process"),Bn=require("node:http"),Wn=require("node:os");var Kn=B.MEDPLUM_CLI_CLIENT_ID,qn="http://localhost:9615",nr=new g("login"),sr=new g("whoami"),or=new g("token");nr.action(async e=>{let t=e.profile??"default",r=ot(t,e),n=await A(e,!1);await Ca(n,r)});sr.action(async e=>{let t=await A(e);xa(t)});or.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 Ca(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await $a(e);break;case"basic":e.setBasicAuth(t.clientId,t.clientSecret);break;case"client-credentials":e.setBasicAuth(t.clientId,t.clientSecret),await e.startClientLogin(t.clientId,t.clientSecret);break;case"jwt-bearer":await vn(e,t);break;case"jwt-assertion":await Cn(e,t);break}}async function Ta(e){let t=(0,Bn.createServer)(async(r,n)=>{let s=new URL(r.url,"http://localhost:9615"),o=s.searchParams.get("code");if(r.method==="OPTIONS"){n.writeHead(200,{Allow:"GET, POST","Content-Type":B.ContentType.TEXT}),n.end("OK");return}if(s.pathname==="/"&&o)try{let i=await e.processCode(o,{clientId:Kn,redirectUri:qn});n.writeHead(200,{"Content-Type":B.ContentType.TEXT}),n.end(`Signed in as ${(0,B.getDisplayString)(i)}. You may close this window.`)}catch(i){n.writeHead(400,{"Content-Type":B.ContentType.TEXT}),n.end(`Error: ${(0,B.normalizeErrorString)(i)}`)}finally{t.close(),process.exit(0)}else n.writeHead(404,{"Content-Type":B.ContentType.TEXT}),n.end("Not found")}).listen(9615)}async function Oa(e){let t=(0,Wn.platform)(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}return new Promise((n,s)=>{(0,Fn.exec)(r,(o,i,a)=>{if(o){s(o);return}if(a){s(new Error("Could not open browser: "+a));return}n()})})}function xa(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 $a(e){await Ta(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Kn),t.searchParams.set("redirect_uri",qn),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Oa(t.toString())}var _e="\x1B[0m",Na="\x1B[1m",ka="\x1B[31m",La="\x1B[32m",Ma="\x1B[33m",Da="\x1B[34m",pe={red:e=>`${ka}${e}${_e}`,green:e=>`${La}${e}${_e}`,yellow:e=>`${Ma}${e}${_e}`,blue:e=>`${Da}${e}${_e}`,bold:e=>`${Na}${e}${_e}`},ir=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>pe.bold(r));var ee=require("@aws-sdk/client-cloudformation"),Pt=require("@aws-sdk/client-cloudfront"),Uo=require("@aws-sdk/client-ecs"),jo=require("@aws-sdk/client-s3"),Ae=require("@aws-sdk/client-ssm"),It=require("@aws-sdk/client-sts"),vt=require("@medplum/core"),Fo=require("node:fs"),Bo=L(Cr(),1);var Do=L(require("node:readline"),1),Et;function St(){Et=Do.default.createInterface({input:process.stdin,output:process.stdout})}function Rt(){Et.close()}function c(e){Et.write(e+`
5
- `)}function I(e){c(`
2
+ "use strict";var ca=Object.create;var $e=Object.defineProperty;var la=Object.getOwnPropertyDescriptor;var ua=Object.getOwnPropertyNames;var pa=Object.getPrototypeOf,da=Object.prototype.hasOwnProperty;var Yr=e=>{throw TypeError(e)};var ma=(e,t,r)=>t in e?$e(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}},fa=(e,t)=>{for(var r in t)$e(e,r,{get:t[r],enumerable:!0})},Qr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ua(t))!da.call(e,s)&&s!==r&&$e(e,s,{get:()=>t[s],enumerable:!(n=la(t,s))||n.enumerable});return e};var ee=(e,t,r)=>(r=e!=null?ca(pa(e)):{},Qr(t||!e||!e.__esModule?$e(r,"default",{value:e,enumerable:!0}):r,e)),ga=e=>Qr($e({},"__esModule",{value:!0}),e);var k=(e,t,r)=>ma(e,typeof t!="symbol"?t+"":t,r),Zr=(e,t,r)=>t.has(e)||Yr("Cannot "+r);var R=(e,t,r)=>(Zr(e,t,"read from private field"),r?r.call(e):t.get(e)),_=(e,t,r)=>t.has(e)?Yr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),j=(e,t,r,n)=>(Zr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Re=w((ym,as)=>{"use strict";var Qa="2.0.0",Za=Number.MAX_SAFE_INTEGER||9007199254740991,ec=16,tc=250,rc=["major","premajor","minor","preminor","patch","prepatch","prerelease"];as.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ec,MAX_SAFE_BUILD_LENGTH:tc,MAX_SAFE_INTEGER:Za,RELEASE_TYPES:rc,SEMVER_SPEC_VERSION:Qa,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var je=w((wm,cs)=>{"use strict";var nc=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};cs.exports=nc});var Ae=w((Q,ls)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:mr,MAX_SAFE_BUILD_LENGTH:sc,MAX_LENGTH:oc}=Re(),ic=je();Q=ls.exports={};var ac=Q.re=[],cc=Q.safeRe=[],p=Q.src=[],lc=Q.safeSrc=[],d=Q.t={},uc=0,fr="[a-zA-Z0-9-]",pc=[["\\s",1],["\\d",oc],[fr,sc]],dc=e=>{for(let[t,r]of pc)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=dc(t),s=uc++;ic(e,s,t),d[e]=s,p[s]=t,lc[s]=n,ac[s]=new RegExp(t,r?"g":void 0),cc[s]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${fr}*`);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",`${fr}+`);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,${mr}})(?:\\.(\\d{1,${mr}}))?(?:\\.(\\d{1,${mr}}))?`);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);Q.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);Q.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);Q.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 pt=w((Em,us)=>{"use strict";var mc=Object.freeze({loose:!0}),fc=Object.freeze({}),gc=e=>e?typeof e!="object"?mc:e:fc;us.exports=gc});var gr=w((Sm,ms)=>{"use strict";var ps=/^[0-9]+$/,ds=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=ps.test(e),n=ps.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},hc=(e,t)=>ds(t,e);ms.exports={compareIdentifiers:ds,rcompareIdentifiers:hc}});var x=w((Rm,gs)=>{"use strict";var dt=je(),{MAX_LENGTH:fs,MAX_SAFE_INTEGER:mt}=Re(),{safeRe:ft,t:gt}=Ae(),yc=pt(),{compareIdentifiers:hr}=gr(),wc=(e,t)=>{let r=t.split(".");if(r.length>e.length)return!1;for(let n=0;n<r.length;n++)if(hr(e[n],r[n])!==0)return!1;return!0},yr=class e{constructor(t,r){if(r=yc(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>fs)throw new TypeError(`version is longer than ${fs} characters`);dt("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?ft[gt.LOOSE]:ft[gt.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>mt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>mt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>mt||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let o=+s;if(o>=0&&o<mt)return o}return s}):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(dt("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],s=t.prerelease[r];if(dt("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return hr(n,s)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],s=t.build[r];if(dt("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return hr(n,s)}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 s=`-${r}`.match(this.options.loose?ft[gt.PRERELEASELOOSE]:ft[gt.PRERELEASE]);if(!s||s[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 s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let o=[r,s];if(n===!1&&(o=[r]),wc(this.prerelease,r)){let i=this.prerelease[r.split(".").length];isNaN(i)&&(this.prerelease=o)}else this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};gs.exports=yr});var ce=w((Am,ys)=>{"use strict";var hs=x(),Ec=(e,t,r=!1)=>{if(e instanceof hs)return e;try{return new hs(e,t)}catch(n){if(!r)return null;throw n}};ys.exports=Ec});var Es=w((bm,ws)=>{"use strict";var Sc=ce(),Rc=(e,t)=>{let r=Sc(e,t);return r?r.version:null};ws.exports=Rc});var Rs=w((Pm,Ss)=>{"use strict";var Ac=ce(),bc=(e,t)=>{let r=Ac(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Ss.exports=bc});var Ps=w((vm,bs)=>{"use strict";var As=x(),Pc=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new As(e instanceof As?e.version:e,r).inc(t,n,s).version}catch{return null}};bs.exports=Pc});var Cs=w((Im,Is)=>{"use strict";var vs=ce(),vc=(e,t)=>{let r=vs(e,null,!0),n=vs(t,null,!0),s=r.compare(n);if(s===0)return null;let o=s>0,i=o?r:n,a=o?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"};Is.exports=vc});var Os=w((Cm,Ts)=>{"use strict";var Ic=x(),Cc=(e,t)=>new Ic(e,t).major;Ts.exports=Cc});var $s=w((Tm,xs)=>{"use strict";var Tc=x(),Oc=(e,t)=>new Tc(e,t).minor;xs.exports=Oc});var ks=w((Om,Ns)=>{"use strict";var xc=x(),$c=(e,t)=>new xc(e,t).patch;Ns.exports=$c});var Ds=w((xm,Ls)=>{"use strict";var Nc=ce(),kc=(e,t)=>{let r=Nc(e,t);return r&&r.prerelease.length?r.prerelease:null};Ls.exports=kc});var B=w(($m,Us)=>{"use strict";var Ms=x(),Lc=(e,t,r)=>new Ms(e,r).compare(new Ms(t,r));Us.exports=Lc});var js=w((Nm,_s)=>{"use strict";var Dc=B(),Mc=(e,t,r)=>Dc(t,e,r);_s.exports=Mc});var Bs=w((km,Fs)=>{"use strict";var Uc=B(),_c=(e,t)=>Uc(e,t,!0);Fs.exports=_c});var ht=w((Lm,qs)=>{"use strict";var Ws=x(),jc=(e,t,r)=>{let n=new Ws(e,r),s=new Ws(t,r);return n.compare(s)||n.compareBuild(s)};qs.exports=jc});var Gs=w((Dm,Ks)=>{"use strict";var Fc=ht(),Bc=(e,t)=>e.sort((r,n)=>Fc(r,n,t));Ks.exports=Bc});var Hs=w((Mm,Vs)=>{"use strict";var Wc=ht(),qc=(e,t)=>e.sort((r,n)=>Wc(n,r,t));Vs.exports=qc});var Fe=w((Um,Js)=>{"use strict";var Kc=B(),Gc=(e,t,r)=>Kc(e,t,r)>0;Js.exports=Gc});var yt=w((_m,Xs)=>{"use strict";var Vc=B(),Hc=(e,t,r)=>Vc(e,t,r)<0;Xs.exports=Hc});var wr=w((jm,zs)=>{"use strict";var Jc=B(),Xc=(e,t,r)=>Jc(e,t,r)===0;zs.exports=Xc});var Er=w((Fm,Ys)=>{"use strict";var zc=B(),Yc=(e,t,r)=>zc(e,t,r)!==0;Ys.exports=Yc});var wt=w((Bm,Qs)=>{"use strict";var Qc=B(),Zc=(e,t,r)=>Qc(e,t,r)>=0;Qs.exports=Zc});var Et=w((Wm,Zs)=>{"use strict";var el=B(),tl=(e,t,r)=>el(e,t,r)<=0;Zs.exports=tl});var Sr=w((qm,eo)=>{"use strict";var rl=wr(),nl=Er(),sl=Fe(),ol=wt(),il=yt(),al=Et(),cl=(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 rl(e,r,n);case"!=":return nl(e,r,n);case">":return sl(e,r,n);case">=":return ol(e,r,n);case"<":return il(e,r,n);case"<=":return al(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};eo.exports=cl});var ro=w((Km,to)=>{"use strict";var ll=x(),ul=ce(),{safeRe:St,t:Rt}=Ae(),pl=(e,t)=>{if(e instanceof ll)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?St[Rt.COERCEFULL]:St[Rt.COERCE]);else{let l=t.includePrerelease?St[Rt.COERCERTLFULL]:St[Rt.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],s=r[3]||"0",o=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return ul(`${n}.${s}.${o}${i}${a}`,t)};to.exports=pl});var so=w((Gm,no)=>{"use strict";var dl=ce(),ml=Re(),fl=x(),gl=(e,t,r)=>{if(!ml.RELEASE_TYPES.includes(t))return null;let n=hl(e,r);return n&&yl(n,t)},hl=(e,t)=>{let r=e instanceof fl?e.version:e;return dl(r,t)},yl=(e,t)=>{if(wl(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()},wl=e=>e.startsWith("pre");no.exports=gl});var io=w((Vm,oo)=>{"use strict";var Rr=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 s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}};oo.exports=Rr});var W=w((Hm,uo)=>{"use strict";var El=/\s+/g,Ar=class e{constructor(t,r){if(r=Rl(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof br)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(El," "),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(s=>!co(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&xl(s[0])){this.set=[s];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(Ol,"");let n=((this.options.includePrerelease&&Cl)|(this.options.loose&&Tl))+":"+t,s=ao.get(n);if(s)return s;let o=this.options.loose,i=o?L[$.HYPHENRANGELOOSE]:L[$.HYPHENRANGE];t=t.replace(i,Bl(this.options.includePrerelease)),P("hyphen replace",t),t=t.replace(L[$.COMPARATORTRIM],Pl),P("comparator trim",t),t=t.replace(L[$.TILDETRIM],vl),P("tilde trim",t),t=t.replace(L[$.CARETTRIM],Il),P("caret trim",t);let a=t.split(" ").map(m=>$l(m,this.options)).join(" ").split(/\s+/).map(m=>Fl(m,this.options));o&&(a=a.filter(m=>(P("loose invalid filter",m,this.options),!!m.match(L[$.COMPARATORLOOSE])))),P("range list",a);let l=new Map,u=a.map(m=>new br(m,this.options));for(let m of u){if(co(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let f=[...l.values()];return ao.set(n,f),f}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(s=>lo(s,r)&&n.every(o=>s.every(i=>o.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new Al(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(Wl(this.set[r],t,this.options))return!0;return!1}};uo.exports=Ar;var Sl=io(),ao=new Sl,Rl=pt(),br=Be(),P=je(),Al=x(),{safeRe:L,src:bl,t:$,comparatorTrimReplace:Pl,tildeTrimReplace:vl,caretTrimReplace:Il}=Ae(),{FLAG_INCLUDE_PRERELEASE:Cl,FLAG_LOOSE:Tl}=Re(),Ol=new RegExp(bl[$.BUILD],"g"),co=e=>e.value==="<0.0.0-0",xl=e=>e.value==="",lo=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(o=>s.intersects(o,t)),s=n.pop();return r},$l=(e,t)=>(e=e.replace(L[$.BUILD],""),P("comp",e,t),e=Dl(e,t),P("caret",e),e=kl(e,t),P("tildes",e),e=Ul(e,t),P("xrange",e),e=jl(e,t),P("stars",e),e),T=e=>!e||e.toLowerCase()==="x"||e==="*",Nl=(e,t,r)=>T(e)&&!T(t)||T(t)&&r&&!T(r),kl=(e,t)=>e.trim().split(/\s+/).map(r=>Ll(r,t)).join(" "),Ll=(e,t)=>{let r=t.loose?L[$.TILDELOOSE]:L[$.TILDE],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,a,l)=>{P("tilde",e,s,o,i,a,l);let u;return T(o)?u="":T(i)?u=`>=${o}.0.0${n} <${+o+1}.0.0-0`:T(a)?u=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:l?(P("replaceTilde pr",l),u=`>=${o}.${i}.${a}-${l} <${o}.${+i+1}.0-0`):u=`>=${o}.${i}.${a} <${o}.${+i+1}.0-0`,P("tilde return",u),u})},Dl=(e,t)=>e.trim().split(/\s+/).map(r=>Ml(r,t)).join(" "),Ml=(e,t)=>{P("caret",e,t);let r=t.loose?L[$.CARETLOOSE]:L[$.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,a,l)=>{P("caret",e,s,o,i,a,l);let u;return T(o)?u="":T(i)?u=`>=${o}.0.0${n} <${+o+1}.0.0-0`:T(a)?o==="0"?u=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.0${n} <${+o+1}.0.0-0`:l?(P("replaceCaret pr",l),o==="0"?i==="0"?u=`>=${o}.${i}.${a}-${l} <${o}.${i}.${+a+1}-0`:u=`>=${o}.${i}.${a}-${l} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.${a}-${l} <${+o+1}.0.0-0`):(P("no pr"),o==="0"?i==="0"?u=`>=${o}.${i}.${a} <${o}.${i}.${+a+1}-0`:u=`>=${o}.${i}.${a} <${o}.${+i+1}.0-0`:u=`>=${o}.${i}.${a} <${+o+1}.0.0-0`),P("caret return",u),u})},Ul=(e,t)=>(P("replaceXRanges",e,t),e.split(/\s+/).map(r=>_l(r,t)).join(" ")),_l=(e,t)=>{e=e.trim();let r=t.loose?L[$.XRANGELOOSE]:L[$.XRANGE];return e.replace(r,(n,s,o,i,a,l)=>{if(P("xRange",e,n,s,o,i,a,l),Nl(o,i,a))return e;let u=T(o),f=u||T(i),m=f||T(a),S=m;return s==="="&&S&&(s=""),l=t.includePrerelease?"-0":"",u?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&S?(f&&(i=0),a=0,s===">"?(s=">=",f?(o=+o+1,i=0,a=0):(i=+i+1,a=0)):s==="<="&&(s="<",f?o=+o+1:i=+i+1),s==="<"&&(l="-0"),n=`${s+o}.${i}.${a}${l}`):f?n=`>=${o}.0.0${l} <${+o+1}.0.0-0`:m&&(n=`>=${o}.${i}.0${l} <${o}.${+i+1}.0-0`),P("xRange return",n),n})},jl=(e,t)=>(P("replaceStars",e,t),e.trim().replace(L[$.STAR],"")),Fl=(e,t)=>(P("replaceGTE0",e,t),e.trim().replace(L[t.includePrerelease?$.GTE0PRE:$.GTE0],"")),Bl=e=>(t,r,n,s,o,i,a,l,u,f,m,S)=>(T(n)?r="":T(s)?r=`>=${n}.0.0${e?"-0":""}`:T(o)?r=`>=${n}.${s}.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()),Wl=(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!==br.ANY&&e[n].semver.prerelease.length>0){let s=e[n].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}});var Be=w((Jm,yo)=>{"use strict";var We=Symbol("SemVer ANY"),Ir=class e{static get ANY(){return We}constructor(t,r){if(r=po(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),vr("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,vr("comp",this)}parse(t){let r=this.options.loose?mo[fo.COMPARATORLOOSE]:mo[fo.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 go(n[2],this.options.loose):this.semver=We}toString(){return this.value}test(t){if(vr("Comparator.test",t,this.options.loose),this.semver===We||t===We)return!0;if(typeof t=="string")try{t=new go(t,this.options)}catch{return!1}return Pr(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 ho(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new ho(this.value,r).test(t.semver):(r=po(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("=")||Pr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||Pr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};yo.exports=Ir;var po=pt(),{safeRe:mo,t:fo}=Ae(),Pr=Sr(),vr=je(),go=x(),ho=W()});var qe=w((Xm,wo)=>{"use strict";var ql=W(),Kl=(e,t,r)=>{try{t=new ql(t,r)}catch{return!1}return t.test(e)};wo.exports=Kl});var So=w((zm,Eo)=>{"use strict";var Gl=W(),Vl=(e,t)=>new Gl(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));Eo.exports=Vl});var Ao=w((Ym,Ro)=>{"use strict";var Hl=x(),Jl=W(),Xl=(e,t,r)=>{let n=null,s=null,o=null;try{o=new Jl(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===-1)&&(n=i,s=new Hl(n,r))}),n};Ro.exports=Xl});var Po=w((Qm,bo)=>{"use strict";var zl=x(),Yl=W(),Ql=(e,t,r)=>{let n=null,s=null,o=null;try{o=new Yl(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===1)&&(n=i,s=new zl(n,r))}),n};bo.exports=Ql});var Co=w((Zm,Io)=>{"use strict";var Cr=x(),Zl=W(),vo=Fe(),eu=(e,t)=>{e=new Zl(e,t);let r=new Cr("0.0.0");if(e.test(r)||(r=new Cr("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n<e.set.length;++n){let s=e.set[n],o=null;s.forEach(i=>{let a=new Cr(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||vo(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),o&&(!r||vo(r,o))&&(r=o)}return r&&e.test(r)?r:null};Io.exports=eu});var Oo=w((ef,To)=>{"use strict";var tu=W(),ru=(e,t)=>{try{return new tu(e,t).range||"*"}catch{return null}};To.exports=ru});var At=w((tf,ko)=>{"use strict";var nu=x(),No=Be(),{ANY:su}=No,ou=W(),iu=qe(),xo=Fe(),$o=yt(),au=Et(),cu=wt(),lu=(e,t,r,n)=>{e=new nu(e,n),t=new ou(t,n);let s,o,i,a,l;switch(r){case">":s=xo,o=au,i=$o,a=">",l=">=";break;case"<":s=$o,o=cu,i=xo,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(iu(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===su&&(g=new No(">=0.0.0")),m=m||g,S=S||g,s(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)&&o(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};ko.exports=lu});var Do=w((rf,Lo)=>{"use strict";var uu=At(),pu=(e,t,r)=>uu(e,t,">",r);Lo.exports=pu});var Uo=w((nf,Mo)=>{"use strict";var du=At(),mu=(e,t,r)=>du(e,t,"<",r);Mo.exports=mu});var Fo=w((sf,jo)=>{"use strict";var _o=W(),fu=(e,t,r)=>(e=new _o(e,r),t=new _o(t,r),e.intersects(t,r));jo.exports=fu});var Wo=w((of,Bo)=>{"use strict";var gu=qe(),hu=B();Bo.exports=(e,t,r)=>{let n=[],s=null,o=null,i=e.sort((f,m)=>hu(f,m,r));for(let f of i)gu(f,t,r)?(o=f,s||(s=f)):(o&&n.push([s,o]),o=null,s=null);s&&n.push([s,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 Jo=w((af,Ho)=>{"use strict";var qo=W(),xr=Be(),{ANY:Tr}=xr,Or=qe(),$r=B(),yu=(e,t,r={})=>{if(e===t)return!0;e=new qo(e,r),t=new qo(t,r);let n=!1;e:for(let s of e.set){for(let o of t.set){let i=Eu(s,o,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},wu=[new xr(">=0.0.0-0")],Ko=[new xr(">=0.0.0")],Eu=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Tr){if(t.length===1&&t[0].semver===Tr)return!0;r.includePrerelease?e=wu:e=Ko}if(t.length===1&&t[0].semver===Tr){if(r.includePrerelease)return!0;t=Ko}let n=new Set,s,o;for(let g of e)g.operator===">"||g.operator===">="?s=Go(s,g,r):g.operator==="<"||g.operator==="<="?o=Vo(o,g,r):n.add(g.semver);if(n.size>1)return null;let i;if(s&&o){if(i=$r(s.semver,o.semver,r),i>0)return null;if(i===0&&(s.operator!==">="||o.operator!=="<="))return null}for(let g of n){if(s&&!Or(g,String(s),r)||o&&!Or(g,String(o),r))return null;for(let oe of t)if(!Or(g,String(oe),r))return!1;return!0}let a,l,u,f,m=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1,S=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;m&&m.prerelease.length===1&&o.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==="<=",s){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=Go(s,g,r),a===g&&a!==s)return!1}else if(s.operator===">="&&!g.test(s.semver))return!1}if(o){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=Vo(o,g,r),l===g&&l!==o)return!1}else if(o.operator==="<="&&!g.test(o.semver))return!1}if(!g.operator&&(o||s)&&i!==0)return!1}return!(s&&u&&!o&&i!==0||o&&f&&!s&&i!==0||S||m)},Go=(e,t,r)=>{if(!e)return t;let n=$r(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},Vo=(e,t,r)=>{if(!e)return t;let n=$r(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};Ho.exports=yu});var kr=w((cf,Yo)=>{"use strict";var Nr=Ae(),Xo=Re(),Su=x(),zo=gr(),Ru=ce(),Au=Es(),bu=Rs(),Pu=Ps(),vu=Cs(),Iu=Os(),Cu=$s(),Tu=ks(),Ou=Ds(),xu=B(),$u=js(),Nu=Bs(),ku=ht(),Lu=Gs(),Du=Hs(),Mu=Fe(),Uu=yt(),_u=wr(),ju=Er(),Fu=wt(),Bu=Et(),Wu=Sr(),qu=ro(),Ku=so(),Gu=Be(),Vu=W(),Hu=qe(),Ju=So(),Xu=Ao(),zu=Po(),Yu=Co(),Qu=Oo(),Zu=At(),ep=Do(),tp=Uo(),rp=Fo(),np=Wo(),sp=Jo();Yo.exports={parse:Ru,valid:Au,clean:bu,inc:Pu,diff:vu,major:Iu,minor:Cu,patch:Tu,prerelease:Ou,compare:xu,rcompare:$u,compareLoose:Nu,compareBuild:ku,sort:Lu,rsort:Du,gt:Mu,lt:Uu,eq:_u,neq:ju,gte:Fu,lte:Bu,cmp:Wu,coerce:qu,truncate:Ku,Comparator:Gu,Range:Vu,satisfies:Hu,toComparators:Ju,maxSatisfying:Xu,minSatisfying:zu,minVersion:Yu,validRange:Qu,outside:Zu,gtr:ep,ltr:tp,intersects:rp,simplifyRange:np,subset:sp,SemVer:Su,re:Nr.re,src:Nr.src,tokens:Nr.t,SEMVER_SPEC_VERSION:Xo.SEMVER_SPEC_VERSION,RELEASE_TYPES:Xo.RELEASE_TYPES,compareIdentifiers:zo.compareIdentifiers,rcompareIdentifiers:zo.rcompareIdentifiers}});var Yp={};fa(Yp,{handleError:()=>oa,main:()=>sa,run:()=>ia});module.exports=ga(Yp);var xe=require("@medplum/core"),Ye=require("commander"),na=ee(require("dotenv"),1);var G=require("@medplum/core"),Ue=require("commander");var rn=require("@medplum/core");var en=require("@medplum/core"),te=require("node:fs"),tn=require("node:os"),Kt=require("node:path");var J=class extends en.ClientStorage{constructor(r){super();k(this,"dirName");k(this,"fileName");this.dirName=(0,Kt.resolve)((0,tn.homedir)(),".medplum"),this.fileName=(0,Kt.resolve)(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,n){let s=this.readFile()??{};n?s[r]=n:delete s[r],this.writeFile(s)}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((0,te.existsSync)(this.fileName))return JSON.parse((0,te.readFileSync)(this.fileName,"utf8"))}writeFile(r){(0,te.existsSync)(this.dirName)||(0,te.mkdirSync)(this.dirName),(0,te.writeFileSync)(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function b(e,t=!0){let r=e.profile??"default",n=new J(r),s=n.getObject("options");if(r!=="default"&&!s)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:o,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:f,clientSecret:m}=ha(e,n),S=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await ya(e.baseUrl,S);let g=new rn.MedplumClient({fetch:S,baseUrl:o,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:n,onUnauthenticated:wa,verbose:e.verbose});return t&&(a?g.setAccessToken(a):f&&m&&(g.setBasicAuth(f,m),s?.authType!=="basic"&&await g.startClientLogin(f,m))),g}function ha(e,t){let r=t.getObject("options"),n=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",s=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,o=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:s,accessToken:o,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}async function ya(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 wa(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var D=require("@medplum/core"),Ln=require("commander");var Qe=new TextEncoder,Gt=new TextDecoder,Ea=new TextDecoder("utf-8",{fatal:!0}),nd=2**32;function nn(...e){let t=e.reduce((s,{length:o})=>s+o,0),r=new Uint8Array(t),n=0;for(let s of e)r.set(s,n),n+=s.length;return r}function Ze(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 et=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Sa(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function sn(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 on(e,t,r){let n=e.algorithm;if(n.name!==t.name)throw et(t.name);if(t.hash&&n.hash?.name!==t.hash)throw et(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw et(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&n.length!==t.length)throw et(t.length,"algorithm.length");Sa(e,r)}function Ra(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 Vt=(e,t,...r)=>Ra(`Key for the ${e} algorithm must be `,t,...r);var pe=class extends Error{constructor(r,n){super(r,n);k(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};k(pe,"code","ERR_JOSE_GENERIC");var X=class extends pe{constructor(){super(...arguments);k(this,"code","ERR_JOSE_NOT_SUPPORTED")}};k(X,"code","ERR_JOSE_NOT_SUPPORTED");var z=class extends pe{constructor(){super(...arguments);k(this,"code","ERR_JWS_INVALID")}};k(z,"code","ERR_JWS_INVALID");var Ne=class extends pe{constructor(){super(...arguments);k(this,"code","ERR_JWT_INVALID")}};k(Ne,"code","ERR_JWT_INVALID");var an,cn,Ht=class extends(cn=pe,an=Symbol.asyncIterator,cn){constructor(r="multiple matching keys found in the JSON Web Key Set",n){super(r,n);k(this,an,async function*(){});k(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};k(Ht,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Jt=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Aa=e=>e?.[Symbol.toStringTag]==="KeyObject",ln=e=>Jt(e)||Aa(e);function un(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 pn(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 Xt="The input to be decoded is not correctly encoded.";function dn(e){if(Uint8Array.fromBase64)try{return Uint8Array.fromBase64(typeof e=="string"?e:Gt.decode(e),{alphabet:"base64url"})}catch(r){throw new TypeError(Xt,{cause:r})}let t=e;if(t instanceof Uint8Array&&(t=Gt.decode(t)),t.includes("+")||t.includes("/"))throw new TypeError(Xt);t=t.replace(/-/g,"+").replace(/_/g,"/");try{return pn(t)}catch{throw new TypeError(Xt)}}function tt(e){let t=e;return typeof t=="string"&&(t=Qe.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):un(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function zt(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 mn(...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 fn=e=>zt(e)&&typeof e.kty=="string",gn=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),hn=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,yn=e=>e.kty==="oct"&&typeof e.k=="string";function Yt(e,t){if(e)throw new TypeError(`${t} can only be called once`)}async function wn(e,t){if(t.kty==="RSA"&&"oth"in t&&t.oth!==void 0)throw new X('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');if(!e.kty.includes(t.kty))throw new X('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),s={...t};return s.kty!=="AKP"&&delete s.alg,delete s.use,crypto.subtle.importKey("jwk",s,r,t.ext??!n,t.key_ops??e.usages[n?1:0])}var Qt=e=>e[Symbol.toStringTag],Pa=(e,t,r)=>{let{alg:n}=e;if(t.use!==void 0){let s=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==s)throw new TypeError(`Invalid key for this operation, its "use" must be "${s}" 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 s=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(s&&!t.key_ops.includes(s))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${s}" when present`)}};function va(e,t,r){let{alg:n,secret:s}=e,o=r==="decrypt"||r==="sign";if(s&&t instanceof Uint8Array)return[Sn,t];if(fn(t)){if(s?!yn(t):!(o?gn(t):hn(t)))throw new TypeError(s?'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 ${o?"private":"public"} JWK`);return Pa(e,t,r),[bn,t]}if(!ln(t))throw new TypeError(s?Vt(n,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):Vt(n,t,"CryptoKey","KeyObject","JSON Web Key"));if(s){if(t.type!=="secret")throw new TypeError(`${Qt(t)} instances for symmetric algorithms must be of type "secret"`)}else{if(t.type==="secret")throw new TypeError(`${Qt(t)} instances for asymmetric algorithms must not be of type "secret"`);let i=o?"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(`${Qt(t)} instances for asymmetric algorithm ${a} must be of type "${i}"`)}}return Jt(t)?[Rn,t]:[An,t]}var Sn=0,Rn=1,An=2,bn=3,Zt,Ia={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function rt(e,t,r){Zt||=new WeakMap;let n=Zt.get(e);return r&&(n?n[t]=r:Zt.set(e,{[t]:r})),r??n?.[t]}var En=async(e,t,r)=>rt(e,r.alg)??rt(e,r.alg,await wn(r,{...t,alg:r.alg})),Ca=(e,t)=>{let r=rt(e,t.alg);if(r)return r;let n=e.type==="public",s=t.usages[n?0:1],{asymmetricKeyType:o}=e,i=Ia[e.asymmetricKeyDetails?.namedCurve],a=t.resolve?.({crv:i,asymmetricKeyType:o})??t.subtle;return rt(e,t.alg,e.toCryptoKey(a,n,s))};async function Pn(e,t,r){let n=va(e,t,r);switch(n[0]){case Sn:case Rn:return n[1];case bn:{let s=n[1];if(s.k)return dn(s.k);if(!Object.isFrozen(s)){let{key_ops:o}=s;Array.isArray(o)&&Object.freeze(o),Object.freeze(s)}return En(s,s,e)}case An:{let s=n[1];return s.type==="secret"?s.export():"toCryptoKey"in s&&typeof s.toCryptoKey=="function"?Ca(s,e):En(s,s.export({format:"jwk"}),e)}}}function vn(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var In={__proto__:null,b64:!0};function Cn(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 Tn(e,t,r,n,s){if(s.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 o=r===void 0?t:{__proto__:null,...r,...t};for(let i of n.crit){if(!(i in o))throw new X(`Extension Header Parameter "${i}" is not recognized`);if(!Object.hasOwn(s,i)||s[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(o[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 Ta(e,t,r){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,e.subtle,!1,[r]):(on(t,e.subtle,r),e.minRsaBits&&sn(e.alg,t),t)}async function On(e,t,r){let n=await Ta(e,t,"sign"),s=await crypto.subtle.sign(e.signing,n,r);return new Uint8Array(s)}var ke=[["verify"],["sign"]];function er(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:ke}}function ge(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:ke,minRsaBits:2048}}function tr(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:ke}}function xn(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:ke}}function rr(e){let r={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:r,signing:r,usages:ke}}var Oa=vn({HS256:er(256),HS384:er(384),HS512:er(512),RS256:ge(256),RS384:ge(384),RS512:ge(512),PS256:ge(256,32),PS384:ge(384,48),PS512:ge(512,64),ES256:tr("P-256",256),ES384:tr("P-384",384),ES512:tr("P-521",512),EdDSA:xn(),Ed25519:xn(),"ML-DSA-44":rr(44),"ML-DSA-65":rr(65),"ML-DSA-87":rr(87)});function $n(e){let t=Oa[e];if(!t)throw new X(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}var nt=e=>Math.floor(e.getTime()/1e3),xa={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},$a=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Nn(e){let t=$a.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=Math.round(r*xa[t[3][0].toLowerCase()]);return t[1]==="-"||t[4]==="ago"?-n:n}function sr(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function nr(e,t){return typeof e=="number"?sr(t,e):e instanceof Date?sr(t,nt(e)):nt(new Date)+Nn(e)}var O,st=class{constructor(t){_(this,O);if(!zt(t))throw new TypeError("JWT Claims Set MUST be an object");j(this,O,structuredClone(t))}data(){return Qe.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=nr(t,"setNotBefore")}set exp(t){R(this,O).exp=nr(t,"setExpirationTime")}set iat(t){t===void 0?R(this,O).iat=nt(new Date):typeof t=="string"?R(this,O).iat=sr("setIssuedAt",nt(new Date)+Nn(t)):R(this,O).iat=nr(t,"setIssuedAt")}};O=new WeakMap;function ot(e){return e?.b64===!1&&Array.isArray(e.crit)&&e.crit.includes("b64")}async function kn(e,t){let{protectedHeader:r,unprotectedHeader:n}=e;if(!r&&!n)throw new z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!mn(r,n))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...r,...n};Cn(z,r);let o=Tn(z,In,e.crit,r,s),i=!0;if(o.includes("b64")&&(i=r.b64,typeof i!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=s;if(typeof a!="string"||!a)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=$n(a),u,f;if(i){let Z=e.encoded??=[];Z[0]??=tt(e.payload),Z[1]??=Ze(Z[0]),u=Z[0],f=Z[1]}else f=e.payload,u="";let m,S;r?(m=tt(JSON.stringify(r)),S=Ze(m)):(m="",S=new Uint8Array);let g=nn(S,Ze("."),f),oe=await Pn(l,t,"sign"),I=await On(l,oe,g),U={signature:tt(I),payload:u};return r&&(U.protected=m),n&&(U.header=n),U}var Le,he,ye,it=class{constructor(t){_(this,Le);_(this,he);_(this,ye);if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");j(this,Le,t)}setProtectedHeader(t){return Yt(R(this,he),"setProtectedHeader"),j(this,he,t),this}setUnprotectedHeader(t){return Yt(R(this,ye),"setUnprotectedHeader"),j(this,ye,t),this}async sign(t,r){return kn({payload:R(this,Le),protectedHeader:R(this,he),unprotectedHeader:R(this,ye),crit:r?.crit},t)}};Le=new WeakMap,he=new WeakMap,ye=new WeakMap;var we,De,at=class{constructor(t){_(this,we);_(this,De);j(this,we,new it(t))}setProtectedHeader(t){return R(this,we).setProtectedHeader(t),j(this,De,t),this}async sign(t,r){if(ot(R(this,De)))throw new TypeError("use the flattened module for creating JWS with b64: false");let n=await R(this,we).sign(t,r);return`${n.protected}.${n.payload}.${n.signature}`}};we=new WeakMap,De=new WeakMap;var Ee,F,Me=class{constructor(t={}){_(this,Ee);_(this,F);j(this,F,new st(t))}setIssuer(t){return R(this,F).iss=t,this}setSubject(t){return R(this,F).sub=t,this}setAudience(t){return R(this,F).aud=t,this}setJti(t){return R(this,F).jti=t,this}setNotBefore(t){return R(this,F).nbf=t,this}setExpirationTime(t){return R(this,F).exp=t,this}setIssuedAt(t){return R(this,F).iat=t,this}setProtectedHeader(t){return j(this,Ee,t),this}async sign(t,r){let n=new at(R(this,F).data());if(n.setProtectedHeader(R(this,Ee)),ot(R(this,Ee)))throw new Ne("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};Ee=new WeakMap,F=new WeakMap;var Se=require("node:crypto"),ie=require("node:fs"),re=require("node:path"),Dn=require("node:util/types"),Mn=require("tar");function ne(e){console.log(JSON.stringify(e,null,2))}async function or(e,t,r){let n=t.source,s=ct(n);if(!s)return;console.log("Saving source code...");let o=await e.createAttachment({data:s,filename:(0,re.basename)(n),contentType:La(n)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:o});console.log("Success! New bot version: "+i.meta?.versionId)}async function ir(e,t,r){let n=t.dist??t.source,s=ct(n);if(!s)return;console.log("Deploying bot...");let o=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:s,filename:(0,re.basename)(n)});if(console.log("Deploy result: "+o.issue?.[0]?.details?.text),!(0,D.isOk)(o))throw new Error(`Bot deploy failed: ${(0,D.normalizeErrorString)(o)}`)}async function ar(e,t,r,n,s,o,i){let a={name:t,description:"",runtimeVersion:o},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:s};await or(e,f,u),await ir(e,f,u),console.log(`Success! Bot created: ${u.id}`),i&&Na(f)}function Un(e){let t=new RegExp("^"+ka(e).replaceAll(String.raw`\*`,".*")+"$"),r=Y()?.bots?.filter(n=>t.test(n.name));return r||[]}function K(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){(0,ie.writeFileSync)((0,re.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function Y(e,t){let r=K(e,t),n=ct(r);if(n)return JSON.parse(n)}function _n(e){let t=ct(K(e,{server:!0}));if(t)return JSON.parse(t)}function ct(e){let t=(0,re.resolve)(e);return(0,ie.existsSync)(t)?(0,ie.readFileSync)(t,"utf8"):""}function Na(e){let t=Y()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ie.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function ka(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function jn(e){let n=0,s=0;return(0,Mn.extract)({cwd:e,filter:(o,i)=>{if(n++,n>100)throw new Error("Tar extractor reached max number of files");if(s+=i.size,s>10485760)throw new Error("Tar extractor reached max size");return!0}})}function cr(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function La(e){let t=(0,re.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?D.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?D.ContentType.TYPESCRIPT:D.ContentType.TEXT}function lt(e,t){let r=new J(e),n={name:e,...t};return r.setObject("options",n),n}function Fn(e){return new J(e).getObject("options")}async function Bn(e,t){let r={typ:"JWT",alg:D.OAuthSigningAlgorithm.HS256},n=Math.floor(Date.now()/1e3),s={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:n,iat:n,exp:n+604800},o=(0,D.encodeBase64)(JSON.stringify(r)),i=(0,D.encodeBase64)(JSON.stringify(s)),a=`${o}.${i}`,l=(0,Se.createHmac)("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Wn(e,t){let r=(0,Se.createPrivateKey)((0,ie.readFileSync)((0,re.resolve)(t.privateKeyPath))),n=await new Me({}).setProtectedHeader({typ:"JWT",alg:D.OAuthSigningAlgorithm.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,Se.randomBytes)(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 Ln.Command{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,s=r.slice(0,n);s[n]=e.optsWithGlobals();try{let o=t(...s);(0,Dn.isPromise)(o)&&await o}finally{e.resetOptionDefaults()}}}var Vn=new h("status").aliases(["info","list","ls"]),Hn=new h("ping"),Jn=new h("push"),Xn=new h("reload-config"),zn=new h("upgrade"),Yn=new h("stats"),ae=new h("agent");y(ae,Vn);y(ae,Hn);y(ae,Jn);y(ae,Xn);y(ae,zn);y(ae,Yn);Vn.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 Ue.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await ut({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let n=Zn(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"}}})});Hn.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 b(r),s=await Qn(n,t,r),o=Number.parseInt(r.count,10);if(Number.isNaN(o))throw new Error("--count <count> must be an integer if specified");try{let i=await n.pushToAgent(s,e,`PING ${o}`,G.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});Jn.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",G.ContentType.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,n)=>{let s=await b(n),o=await Qn(s,r,n),i;try{i=await s.pushToAgent(o,{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)});Xn.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 Ue.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await ut({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});zn.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 Ue.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{let r={};t.agentVersion&&(r.version=t.agentVersion),t.force&&(r.force=!0),await ut({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:n=>({id:n.agent.id,name:n.agent.name,version:t.agentVersion??"latest"})})});Yn.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 Ue.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await ut({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:n}=Zn(r.result,{required:["stats"]}),s;try{s=JSON.parse(n)}catch(o){console.error(`Failed to parse stats for agent ${r.agent.id}: ${(0,G.normalizeErrorString)(o)}`)}return{id:r.agent.id,name:r.agent.name,stats:s}},renderSuccessfulRows:r=>{for(let n=0;n<r.length;n++)n>0&&console.info(),Ma(r[n])}})});var qn=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function Kn(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function Gn(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 Ma(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 qn)r[i]=Kn(e.stats[i]);let n=new Set([...qn,"channelStats","clientStats"]);for(let[i,a]of Object.entries(e.stats))n.has(i)||(r[i]=Kn(a));console.table(r);let s=Gn(e.stats.channelStats);s.length&&(console.info("Channel Stats:"),console.table(s));let o=Gn(e.stats.clientStats);o.length&&(console.info("Client Stats:"),console.table(o))}async function ut({operation:e,agentIds:t,options:r,params:n={},parseSuccessfulResponse:s,renderSuccessfulRows:o}){let i=Fa(t,r),a=await b(r),l=i.type==="criteria"?i.criteria:`Agent?_id=${i.ids.join(",")}`,u=new URLSearchParams(l.split("?")[1]);for(let[I,U]of Object.entries(n))u.append(I,U.toString());let f;try{let I=a.fhirUrl("Agent",e);I.search=u.toString(),f=await a.get(I,{cache:"reload"})}catch(I){throw new Error(`Operation '${e}' failed`,{cause:I})}if(r.output==="json"){console.info(JSON.stringify(f,null,2));return}let m=[],S=[];switch(f.resourceType){case"Bundle":{let I=Ua(f);for(let U of I)U.result.resourceType==="Parameters"||(0,G.isOk)(U.result)?m.push(U):S.push(U);break}case"Parameters":case"OperationOutcome":{let I=await a.searchOne("Agent",u,{cache:"reload"});if(!I)throw new Error("Agent not found");f.resourceType==="Parameters"?m.push({agent:I,result:f}):S.push({agent:I,result:f});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(f)}`)}let g=[];for(let I of m){let U=s(I);g.push(U)}let oe=[];for(let I of S){let Z=I.result.issue?.[0],aa={id:I.agent.id,name:I.agent.name,severity:Z.severity,code:Z.code,details:Z.details?.text??"No details to show"};oe.push(aa)}console.info(`
3
+ ${g.length} successful response(s):
4
+ `),o?g.length?o(g):console.info("No successful responses received"):console.table(g.length?g:"No successful responses received"),console.info(),oe.length&&(console.info(`${oe.length} failed response(s):`),console.info(),console.table(oe))}async function Qn(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{es(r.criteria);let s=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!s?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(s.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=s.entry[0].resource?.id}return{reference:`Agent/${n}`}}function Ua(e){let t=[];for(let r of e.entry??G.EMPTY){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(_a(r.resource))}return t}function _a(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 Zn(e,t){let r={},n=t.required,s=t.optional;for(let o of n){let i=e.parameter?.find(l=>l.name===o);if(!i)throw new Error(`Failed to find parameter '${o}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${o}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${o}'`);r[o]=i[a]}if(s?.length)for(let o of s){let i=e.parameter?.find(l=>l.name===o);if(!i)continue;let a=ja(o,i);r[o]=a}return r}function ja(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 Fa(e,t){if(!Array.isArray(e))throw new Error("Invalid agent IDs array");if(e.length){if(t.criteria)throw new Error("Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive");for(let r of e)if(!(0,G.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return es(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function es(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(s){throw new Error(t,{cause:s})}if(!n.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}var V=require("@medplum/core"),ts=require("node:child_process"),rs=require("node:http"),ns=require("node:os"),ss=require("node:util");var Ba=(0,ss.promisify)(ts.exec),os=V.MEDPLUM_CLI_CLIENT_ID,is="http://localhost:9615",lr=new h("login"),ur=new h("whoami"),pr=new h("token");lr.action(async e=>{let t=e.profile??"default",r=lt(t,e),n=await b(e,!1);await Wa(n,r)});ur.action(async e=>{let t=await b(e);Ga(t)});pr.action(async e=>{let t=await b(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function Wa(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Va(e);break;case"basic":e.setBasicAuth(t.clientId,t.clientSecret);break;case"client-credentials":e.setBasicAuth(t.clientId,t.clientSecret),await e.startClientLogin(t.clientId,t.clientSecret);break;case"jwt-bearer":await Bn(e,t);break;case"jwt-assertion":await Wn(e,t);break}}async function qa(e){let t=(0,rs.createServer)(async(r,n)=>{let s=new URL(r.url,"http://localhost:9615"),o=s.searchParams.get("code");if(r.method==="OPTIONS"){n.writeHead(200,{Allow:"GET, POST","Content-Type":V.ContentType.TEXT}),n.end("OK");return}if(s.pathname==="/"&&o)try{let i=await e.processCode(o,{clientId:os,redirectUri:is});n.writeHead(200,{"Content-Type":V.ContentType.TEXT}),n.end(`Signed in as ${(0,V.getDisplayString)(i)}. You may close this window.`)}catch(i){n.writeHead(400,{"Content-Type":V.ContentType.TEXT}),n.end(`Error: ${(0,V.normalizeErrorString)(i)}`)}finally{t.close(),process.exit(0)}else n.writeHead(404,{"Content-Type":V.ContentType.TEXT}),n.end("Not found")}).listen(9615)}async function Ka(e){let t=(0,ns.platform)(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}await Ba(r)}function Ga(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 Va(e){await qa(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",os),t.searchParams.set("redirect_uri",is),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Ka(t.toString())}var _e="\x1B[0m",Ha="\x1B[1m",Ja="\x1B[31m",Xa="\x1B[32m",za="\x1B[33m",Ya="\x1B[34m",de={red:e=>`${Ja}${e}${_e}`,green:e=>`${Xa}${e}${_e}`,yellow:e=>`${za}${e}${_e}`,blue:e=>`${Ya}${e}${_e}`,bold:e=>`${Ha}${e}${_e}`},dr=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>de.bold(r));var se=require("@aws-sdk/client-cloudformation"),Tt=require("@aws-sdk/client-cloudfront"),ei=require("@aws-sdk/client-ecs"),ti=require("@aws-sdk/client-s3"),Pe=require("@aws-sdk/client-ssm"),Ot=require("@aws-sdk/client-sts"),xt=require("@medplum/core"),ri=require("node:fs"),ni=ee(kr(),1);var Qo=ee(require("node:readline"),1),bt;function Pt(){bt=Qo.default.createInterface({input:process.stdin,output:process.stdout})}function vt(){bt.close()}function c(e){bt.write(e+`
5
+ `)}function v(e){c(`
6
6
  `+e+`
7
- `)}function k(e,t=""){return new Promise(r=>{Et.question(e+(t?" ("+t+")":"")+" ",n=>{r(n||t.toString())})})}async function At(e,t,r=""){let n=e+" ["+t.map(s=>s===r?"("+s+")":s).join("|")+"]";for(;;){let s=await k(n)||r;if(t.includes(s))return s;c("Please choose one of the following options: "+t.join(", "))}}async function Re(e,t,r){return Number.parseInt(await At(e,t.map(n=>n.toString()),r.toString()),10)}async function ie(e){return(await At(e,["y","n"])).toLowerCase()==="y"}async function Ke(e){if(!await ie(e))throw c("Exiting..."),new Error("User cancelled")}var bt=new ee.CloudFormationClient({}),qu=new Pt.CloudFrontClient({region:"us-east-1"}),mf=new Uo.ECSClient({}),qe=new jo.S3Client({}),Hu="medplum:environment";async function Tr(){let e=[],t=(0,ee.paginateListStacks)({client:bt},{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??vt.EMPTY)e.push(n);return e}async function be(e){let t=await Tr();for(let r of t){let n=r.StackName,s=await Or(n);if(s?.tag===e)return s}}async function Or(e){let t={};if(await _o(bt,e,t),await bt.config.region()!=="us-east-1")try{await _o(new ee.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function _o(e,t,r){let n=new ee.DescribeStacksCommand({StackName:t}),o=(await e.send(n))?.Stacks?.[0],i=o?.Tags?.find(l=>l.Key===Hu);if(!i)return;let a=await e.send(new ee.DescribeStackResourcesCommand({StackName:t}));if(a.StackResources){e===bt&&(r.stack=o,r.tag=i.Value);for(let l of a.StackResources)Gu(l,r)}}function Gu(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 Ct(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: ${Vu(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 Vu(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Tt(e){let t=await qu.send(new Pt.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Ot(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(s=>s.tag_name.startsWith("v")?s.tag_name.slice(1):s.tag_name);return n.sort((s,o)=>Bo.compare(o,s)),e?n.slice(0,n.indexOf(e)):n}async function xt(e,t,r){let n=new Ae.SSMClient({region:e});for(let[s,o]of Object.entries(r)){let i=t+s,a=typeof o=="object"?JSON.stringify(o):o.toString(),l=await Ju(n,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await Ke(`Do you want to overwrite "${i}"?`)),await Xu(n,i,a)}}async function Ju(e,t){let r=new Ae.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(n){if(n.name==="ParameterNotFound")return;throw n}}async function Xu(e,t,r){let n=new Ae.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(n)}function ae(e,t){if(console.log(`Config not found: ${e} (${j(e,t)})`),t){let n=Object.entries(t);if(n.length>0){console.log("Additional options:");for(let[s,o]of n)console.log(` ${s}: ${o}`)}}console.log();let r=(0,Fo.readdirSync)(".",{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 Pe(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new It.STSClient,r=new It.GetCallerIdentityCommand({}),n=await t.send(r),s=await t.config.region();console.log("AWS Region: ",s),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",(0,vt.normalizeErrorString)(t))}}async function Wo(e){let t=await be(e);if(!t)throw await Pe(e),new Error(`Stack not found: ${e}`);Ct(t)}var de=require("@aws-sdk/client-acm"),$t=require("@aws-sdk/client-cloudfront"),Nt=require("@aws-sdk/client-sts"),qo=require("@medplum/core"),He=require("node:crypto"),Ho=require("node:fs");var zu=e=>`${e}DomainName`,Go=e=>`${e}SslCertArn`;async function Vo(){let e={apiPort:8103,region:"us-east-1"};St(),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 Yu(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 Ke("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 k("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 k("What is the config file name?",`medplum.${e.name}.config.json`);(0,Ho.existsSync)(r)&&(c("Config file already exists."),await Ke("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),v(r,e),I("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await k("Enter your AWS region:","us-east-1"),v(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 k("What is your AWS account number?",t),v(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 k("Enter your CloudFormation stack name?",n),v(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 k("Enter your base domain name:");v(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 s=await k("Enter your support email address:");I("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await k("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,v(r,e),I("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await k("Enter your web application domain name:","app."+e.domainName),v(r,e),I("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await k("Enter your storage domain name:","storage."+e.domainName),v(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 k("Enter your storage bucket name:",e.storageDomainName),v(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 Re("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 ie("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 Re("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"),v(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 Re("Enter the number of server instances:",[1,2,3,4,6,8],1),v(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 Re("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),v(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 Re("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),v(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 o=(await Ot())[0]??"latest";e.serverImage=await k("Enter the server image:",`medplum/medplum-server:${o}`),v(r,e),I("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await tp(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,v(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 Qu(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 Zu(e,a,u,f);e[Go(f)]=m,v(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:s};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await ie("Do you want to store these values in AWS Parameter Store?"))await xt(e.region,`/medplum/${e.name}/`,l);else{let u=j(e.name,{server:!0});v(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(""),Rt()}async function Yu(e){try{let t=new Nt.STSClient({region:e}),r=new Nt.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Qu(e){let t=await Ko(e);if(e!=="us-east-1"){let r=await Ko("us-east-1");t.push(...r)}return t}async function Ko(e){try{let t=new de.ACMClient({region:e}),r=new de.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Zu(e,t,r,n){let s=e[zu(n)],o=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===s);if(o)return c(`Found existing certificate for "${s}" in "${r}.`),o.CertificateArn;if(c(`No existing certificate found for "${s}" in "${r}.`),!await ie("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${Go(n)}" setting.`),"TODO";let i=await ep(r,s);return c("Certificate ARN: "+i),i}async function ep(e,t){try{let r=await At("Validate certificate using DNS or email validation?",["dns","email"],"dns"),n=new de.ACMClient({region:e}),s=new de.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await n.send(s)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function tp(e,t){let r=(0,He.randomUUID)(),n=(0,He.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new $t.CloudFrontClient({region:e}).send(new $t.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,He.randomUUID)(),EncodedKey:n.publicKey}}))).PublicKey?.Id,publicKey:n.publicKey,privateKey:n.privateKey,passphrase:r}}catch(s){console.log("Error: Unable to create signing key: ",(0,qo.normalizeErrorString)(s));return}}async function Jo(){let e=await Tr();for(let t of e){let r=t.StackName,n=await Or(r);n&&(Ct(n),console.log(""))}}var Xo=require("@aws-sdk/client-s3"),W=require("@medplum/core"),zo=L(require("fast-glob"),1),U=require("node:fs"),Yo=require("node:os"),me=require("node:path"),Qo=require("node:stream"),Zo=require("node:stream/promises");async function ei(e,t){let r=G(e,t);if(!r)throw ae(e,t),new Error(`Config not found: ${e}`);let n=await be(e);if(!n)throw await Pe(e),new Error(`Stack not found: ${e}`);let s=n.appBucket;if(!s)throw new Error(`App bucket not found for stack ${e}`);let o;if(t.tarPath)o=t.tarPath;else{let i=t?.toVersion??"latest";o=await np("@medplum/app",i)}ti(o,{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 op(o,s.PhysicalResourceId,t),n.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Tt(n.appDistribution.PhysicalResourceId),console.log("Done")}async function rp(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await fetch(r)).json()}async function np(e,t){let n=(await rp(e,t)).dist.tarball,s=(0,U.mkdtempSync)((0,me.join)((0,Yo.tmpdir)(),"tarball-"));try{let o=await fetch(n);if(!o.body)throw new Error("Received empty response body");let i=Pn(s);return await(0,Zo.pipeline)(Qo.Readable.fromWeb(o.body),i),(0,me.join)(s,"package","dist")}catch(o){throw(0,U.rmSync)(s,{recursive:!0,force:!0}),o}}function ti(e,t){for(let r of(0,U.readdirSync)(e,{withFileTypes:!0})){let n=(0,me.join)(e,r.name);r.isDirectory()?ti(n,t):r.isFile()&&n.endsWith(".js")&&sp(n,t)}}function sp(e,t){let r=(0,U.readFileSync)(e,"utf-8");for(let[n,s]of Object.entries(t))r=r.replaceAll(`__${n}__`,s);(0,U.writeFileSync)(e,r)}async function op(e,t,r){let n=[["assets/**/*.css",W.ContentType.CSS,!0],["assets/**/*.css.map",W.ContentType.JSON,!0],["assets/**/*.js",W.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",W.ContentType.JSON,!0],["assets/**/*.txt",W.ContentType.TEXT,!0],["assets/**/*.ico",W.ContentType.FAVICON,!0],["img/**/*.png",W.ContentType.PNG,!0],["img/**/*.svg",W.ContentType.SVG,!0],["robots.txt",W.ContentType.TEXT,!0],["index.html",W.ContentType.HTML,!1]];for(let s of n)await ip({rootDir:e,bucketName:t,fileNamePattern:s[0],contentType:s[1],cached:s[2],dryrun:r.dryrun})}async function ip(e){let t=zo.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await ap((0,me.join)(e.rootDir,r),e)}async function ap(e,t){let r=(0,U.createReadStream)(e),n=e.substring(t.rootDir.length+1).split(me.sep).join("/"),s={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 qe.send(new Xo.PutObjectCommand(s))}var kt=require("@aws-sdk/client-s3");async function si(e,t){if(!G(e,t))throw ae(e,t),new Error(`Config not found: ${e}`);let n=await be(e);if(!n)throw await Pe(e),new Error(`Stack not found: ${e}`);try{await ri("App",n.appBucket,n.appDistribution,n.appOriginAccessIdentity,t)}catch(s){console.error(`Error updating App bucket policy: ${s.message}`)}try{await ri("Storage",n.storageBucket,n.storageDistribution,n.storageOriginAccessIdentity,t)}catch(s){console.error(`Error updating Storage bucket policy: ${s.message}`)}console.log("Done")}async function ri(e,t,r,n,s){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 o=t.PhysicalResourceId,i=n.PhysicalResourceId,a=await cp(o);if(up(a,o,i))throw new Error(`${e} bucket already has policy statement`);pp(a,o,i),e==="Storage"&&s.guarddutyMalwareProtection&&dp(a,o,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),s.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await lp(o,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Tt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function cp(e){let t=await qe.send(new kt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function lp(e,t){await qe.send(new kt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function up(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 pp(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 dp(e,t,r){e.Statement?.some(n=>n?.Effect==="Deny"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&ni(n,"s3:GetObject")&&ni(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 ni(e,t){return e.Action===t?!0:Array.isArray(e.Action)&&e.Action.includes(t)}async function oi(e,t){try{St();let r=G(e,t);if(!r)throw ae(e,t),new Error(`Config not found: ${e}`);let n=bn(e)??{};if(!t.yes&&Object.keys(n).length===0){let s=j(e,{server:!0});if(console.log(pe.yellow(`Config file ${s} not found!`)),!await ie("Do you want to proceed?")){console.log(pe.red(`Run Aborted, please ensure ${s} is present and try again.`));return}}mp(r,n),hp(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(pe.yellow("Dry run - skipping updates!")):(t.yes||await ie("Do you want to store these values in AWS Parameter Store?"))&&await xt(r.region,`/medplum/${r.name}/`,n)}finally{Rt()}}function mp(e,t){Lt(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Lt(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Lt(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Lt(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Lt(e,t,r){if(fp(e,t))throw new Error(r)}function fp(e,t){return e!==void 0&&t!==void 0&&e!==t}function hp(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 ai=require("node:child_process"),Ie=L(Cr(),1);async function ci(e,t){let r=await A(t),n=G(e,t);if(!n)throw console.log(`Configuration file ${j(e)} not found`),ae(e,t),new Error(`Config not found: ${e}`);let s=n.serverImage.lastIndexOf(":"),o=n.serverImage.slice(0,s),i=await gp(r,n),a=await ii(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=`${o}:${a}`,yp(e,n),await r.startAsyncRequest("/admin/super/migrate"),a=await ii(a)}}async function gp(e,t){let r=t.serverImage.lastIndexOf(":"),n=t.serverImage.slice(r+1);if(n==="latest"){n=(await e.get("/healthcheck")).version;let o=n.indexOf("-");o>-1&&(n=n.slice(0,o))}return n}async function ii(e,t){let r=await Ot(e),n=r[0];return r.filter(s=>s===n||s===t||Ie.gte(s,Ie.inc(e,"minor"))).pop()}function yp(e,t){let r=j(e);v(r,t);let n=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+n);let s=(0,ai.spawnSync)(n,{stdio:"inherit"});if(s.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${s.status}): ${s.stderr}`);console.log(s.stdout)}function li(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Vo),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Jo),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Wo),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(ir(`Update the AWS Parameter Store config values.
7
+ `)}function M(e,t=""){return new Promise(r=>{bt.question(e+(t?" ("+t+")":"")+" ",n=>{r(n||t.toString())})})}async function It(e,t,r=""){let n=e+" ["+t.map(s=>s===r?"("+s+")":s).join("|")+"]";for(;;){let s=await M(n)||r;if(t.includes(s))return s;c("Please choose one of the following options: "+t.join(", "))}}async function be(e,t,r){return Number.parseInt(await It(e,t.map(n=>n.toString()),r.toString()),10)}async function le(e){return(await It(e,["y","n"])).toLowerCase()==="y"}async function Ke(e){if(!await le(e))throw c("Exiting..."),new Error("User cancelled")}var Ct=new se.CloudFormationClient({}),op=new Tt.CloudFrontClient({region:"us-east-1"}),df=new ei.ECSClient({}),Ge=new ti.S3Client({}),ip="medplum:environment";async function Lr(){let e=[],t=(0,se.paginateListStacks)({client:Ct},{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??xt.EMPTY)e.push(n);return e}async function ve(e){let t=await Lr();for(let r of t){let n=r.StackName,s=await Dr(n);if(s?.tag===e)return s}}async function Dr(e){let t={};if(await Zo(Ct,e,t),await Ct.config.region()!=="us-east-1")try{await Zo(new se.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Zo(e,t,r){let n=new se.DescribeStacksCommand({StackName:t}),o=(await e.send(n))?.Stacks?.[0],i=o?.Tags?.find(l=>l.Key===ip);if(!i)return;let a=await e.send(new se.DescribeStackResourcesCommand({StackName:t}));if(a.StackResources){e===Ct&&(r.stack=o,r.tag=i.Value);for(let l of a.StackResources)ap(l,r)}}function ap(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 $t(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: ${cp(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 cp(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Nt(e){let t=await op.send(new Tt.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function kt(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(s=>s.tag_name.startsWith("v")?s.tag_name.slice(1):s.tag_name);return n.sort((s,o)=>ni.compare(o,s)),e?n.slice(0,n.indexOf(e)):n}async function Lt(e,t,r){let n=new Pe.SSMClient({region:e});for(let[s,o]of Object.entries(r)){let i=t+s,a=typeof o=="object"?JSON.stringify(o):o.toString(),l=await lp(n,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await Ke(`Do you want to overwrite "${i}"?`)),await up(n,i,a)}}async function lp(e,t){let r=new Pe.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(n){if(n.name==="ParameterNotFound")return;throw n}}async function up(e,t,r){let n=new Pe.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(n)}function ue(e,t){if(console.log(`Config not found: ${e} (${K(e,t)})`),t){let n=Object.entries(t);if(n.length>0){console.log("Additional options:");for(let[s,o]of n)console.log(` ${s}: ${o}`)}}console.log();let r=(0,ri.readdirSync)(".",{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 Ie(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new Ot.STSClient,r=new Ot.GetCallerIdentityCommand({}),n=await t.send(r),s=await t.config.region();console.log("AWS Region: ",s),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",(0,xt.normalizeErrorString)(t))}}async function si(e){let t=await ve(e);if(!t)throw await Ie(e),new Error(`Stack not found: ${e}`);$t(t)}var me=require("@aws-sdk/client-acm"),Dt=require("@aws-sdk/client-cloudfront"),Mt=require("@aws-sdk/client-sts"),ii=require("@medplum/core"),Ve=require("node:crypto"),ai=require("node:fs");var pp=e=>`${e}DomainName`,ci=e=>`${e}SslCertArn`;async function li(){let e={apiPort:8103,region:"us-east-1"};Pt(),v("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 dp(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 Ke("Do you want to continue without AWS credentials?")),v("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 M("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),v("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await M("What is the config file name?",`medplum.${e.name}.config.json`);(0,ai.existsSync)(r)&&(c("Config file already exists."),await Ke("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),C(r,e),v("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await M("Enter your AWS region:","us-east-1"),C(r,e),v("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 M("What is your AWS account number?",t),C(r,e),v("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 M("Enter your CloudFormation stack name?",n),C(r,e),v("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 M("Enter your base domain name:");C(r,e),v("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 s=await M("Enter your support email address:");v("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await M("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,C(r,e),v("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await M("Enter your web application domain name:","app."+e.domainName),C(r,e),v("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await M("Enter your storage domain name:","storage."+e.domainName),C(r,e),v("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 M("Enter your storage bucket name:",e.storageDomainName),C(r,e),v("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 be("Enter the maximum number of availability zones:",[2,3,99],2),v("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 le("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 be("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),v("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 be("Enter the number of server instances:",[1,2,3,4,6,8],1),C(r,e),v("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 be("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),C(r,e),v("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 be("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),C(r,e),v("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 o=(await kt())[0]??"latest";e.serverImage=await M("Enter the server image:",`medplum/medplum-server:${o}`),C(r,e),v("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await hp(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.')),v("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await mp(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 fp(e,a,u,f);e[ci(f)]=m,C(r,e)}v("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:s};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await le("Do you want to store these values in AWS Parameter Store?"))await Lt(e.region,`/medplum/${e.name}/`,l);else{let u=K(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.")}v("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(""),vt()}async function dp(e){try{let t=new Mt.STSClient({region:e}),r=new Mt.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function mp(e){let t=await oi(e);if(e!=="us-east-1"){let r=await oi("us-east-1");t.push(...r)}return t}async function oi(e){try{let t=new me.ACMClient({region:e}),r=new me.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function fp(e,t,r,n){let s=e[pp(n)],o=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===s);if(o)return c(`Found existing certificate for "${s}" in "${r}.`),o.CertificateArn;if(c(`No existing certificate found for "${s}" in "${r}.`),!await le("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${ci(n)}" setting.`),"TODO";let i=await gp(r,s);return c("Certificate ARN: "+i),i}async function gp(e,t){try{let r=await It("Validate certificate using DNS or email validation?",["dns","email"],"dns"),n=new me.ACMClient({region:e}),s=new me.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await n.send(s)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function hp(e,t){let r=(0,Ve.randomUUID)(),n=(0,Ve.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new Dt.CloudFrontClient({region:e}).send(new Dt.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,Ve.randomUUID)(),EncodedKey:n.publicKey}}))).PublicKey?.Id,publicKey:n.publicKey,privateKey:n.privateKey,passphrase:r}}catch(s){console.log("Error: Unable to create signing key: ",(0,ii.normalizeErrorString)(s));return}}async function ui(){let e=await Lr();for(let t of e){let r=t.StackName,n=await Dr(r);n&&($t(n),console.log(""))}}var pi=require("@aws-sdk/client-s3"),H=require("@medplum/core"),di=ee(require("fast-glob"),1),q=require("node:fs"),mi=require("node:os"),fe=require("node:path"),fi=require("node:stream"),gi=require("node:stream/promises");async function hi(e,t){let r=Y(e,t);if(!r)throw ue(e,t),new Error(`Config not found: ${e}`);let n=await ve(e);if(!n)throw await Ie(e),new Error(`Stack not found: ${e}`);let s=n.appBucket;if(!s)throw new Error(`App bucket not found for stack ${e}`);let o;if(t.tarPath)o=t.tarPath;else{let i=t?.toVersion??"latest";o=await wp("@medplum/app",i)}yi(o,{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 Sp(o,s.PhysicalResourceId,t),n.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Nt(n.appDistribution.PhysicalResourceId),console.log("Done")}async function yp(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await fetch(r)).json()}async function wp(e,t){let n=(await yp(e,t)).dist.tarball,s=(0,q.mkdtempSync)((0,fe.join)((0,mi.tmpdir)(),"tarball-"));try{let o=await fetch(n);if(!o.body)throw new Error("Received empty response body");let i=jn(s);return await(0,gi.pipeline)(fi.Readable.fromWeb(o.body),i),(0,fe.join)(s,"package","dist")}catch(o){throw(0,q.rmSync)(s,{recursive:!0,force:!0}),o}}function yi(e,t){for(let r of(0,q.readdirSync)(e,{withFileTypes:!0})){let n=(0,fe.join)(e,r.name);r.isDirectory()?yi(n,t):r.isFile()&&n.endsWith(".js")&&Ep(n,t)}}function Ep(e,t){let r=(0,q.readFileSync)(e,"utf-8");for(let[n,s]of Object.entries(t))r=r.replaceAll(`__${n}__`,s);(0,q.writeFileSync)(e,r)}async function Sp(e,t,r){let n=[["assets/**/*.css",H.ContentType.CSS,!0],["assets/**/*.css.map",H.ContentType.JSON,!0],["assets/**/*.js",H.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",H.ContentType.JSON,!0],["assets/**/*.txt",H.ContentType.TEXT,!0],["assets/**/*.ico",H.ContentType.FAVICON,!0],["img/**/*.png",H.ContentType.PNG,!0],["img/**/*.svg",H.ContentType.SVG,!0],["robots.txt",H.ContentType.TEXT,!0],["index.html",H.ContentType.HTML,!1]];for(let s of n)await Rp({rootDir:e,bucketName:t,fileNamePattern:s[0],contentType:s[1],cached:s[2],dryrun:r.dryrun})}async function Rp(e){let t=di.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Ap((0,fe.join)(e.rootDir,r),e)}async function Ap(e,t){let r=(0,q.createReadStream)(e),n=e.substring(t.rootDir.length+1).split(fe.sep).join("/"),s={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 Ge.send(new pi.PutObjectCommand(s))}var Ut=require("@aws-sdk/client-s3");async function Si(e,t){if(!Y(e,t))throw ue(e,t),new Error(`Config not found: ${e}`);let n=await ve(e);if(!n)throw await Ie(e),new Error(`Stack not found: ${e}`);try{await wi("App",n.appBucket,n.appDistribution,n.appOriginAccessIdentity,t)}catch(s){console.error(`Error updating App bucket policy: ${s.message}`)}try{await wi("Storage",n.storageBucket,n.storageDistribution,n.storageOriginAccessIdentity,t)}catch(s){console.error(`Error updating Storage bucket policy: ${s.message}`)}console.log("Done")}async function wi(e,t,r,n,s){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 o=t.PhysicalResourceId,i=n.PhysicalResourceId,a=await bp(o);if(vp(a,o,i))throw new Error(`${e} bucket already has policy statement`);Ip(a,o,i),e==="Storage"&&s.guarddutyMalwareProtection&&Cp(a,o,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),s.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Pp(o,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Nt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function bp(e){let t=await Ge.send(new Ut.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Pp(e,t){await Ge.send(new Ut.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function vp(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 Ip(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 Cp(e,t,r){e.Statement?.some(n=>n?.Effect==="Deny"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Ei(n,"s3:GetObject")&&Ei(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 Ei(e,t){return e.Action===t?!0:Array.isArray(e.Action)&&e.Action.includes(t)}async function Ri(e,t){try{Pt();let r=Y(e,t);if(!r)throw ue(e,t),new Error(`Config not found: ${e}`);let n=_n(e)??{};if(!t.yes&&Object.keys(n).length===0){let s=K(e,{server:!0});if(console.log(de.yellow(`Config file ${s} not found!`)),!await le("Do you want to proceed?")){console.log(de.red(`Run Aborted, please ensure ${s} is present and try again.`));return}}Tp(r,n),xp(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(de.yellow("Dry run - skipping updates!")):(t.yes||await le("Do you want to store these values in AWS Parameter Store?"))&&await Lt(r.region,`/medplum/${r.name}/`,n)}finally{vt()}}function Tp(e,t){_t(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),_t(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),_t(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),_t(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function _t(e,t,r){if(Op(e,t))throw new Error(r)}function Op(e,t){return e!==void 0&&t!==void 0&&e!==t}function xp(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 bi=require("node:child_process"),Ce=ee(kr(),1);async function Pi(e,t){let r=await b(t),n=Y(e,t);if(!n)throw console.log(`Configuration file ${K(e)} not found`),ue(e,t),new Error(`Config not found: ${e}`);let s=n.serverImage.lastIndexOf(":"),o=n.serverImage.slice(0,s),i=await $p(r,n),a=await Ai(i);for(;a;){if(t.toVersion&&Ce.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),n.serverImage=`${o}:${a}`,Np(e,n),await r.startAsyncRequest("/admin/super/migrate"),a=await Ai(a)}}async function $p(e,t){let r=t.serverImage.lastIndexOf(":"),n=t.serverImage.slice(r+1);if(n==="latest"){n=(await e.get("/healthcheck")).version;let o=n.indexOf("-");o>-1&&(n=n.slice(0,o))}return n}async function Ai(e,t){let r=await kt(e),n=r[0];return r.filter(s=>s===n||s===t||Ce.gte(s,Ce.inc(e,"minor"))).pop()}function Np(e,t){let r=K(e);C(r,t);let n=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+n);let s=(0,bi.spawnSync)(n,{stdio:"inherit"});if(s.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${s.status}): ${s.stderr}`);console.log(s.stdout)}function vi(){let e=new h("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(li),e.command("list").description("List Medplum AWS CloudFormation stacks").action(ui),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(si),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(dr(`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
- `+pe.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",ir("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(oi),y(e,new g("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(ci)),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(ei),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(si),e}var ui=new g("save"),pi=new g("deploy"),di=new g("create"),Ge=new g("bot");y(Ge,ui);y(Ge,pi);y(Ge,di);var xr=new g("save-bot"),$r=new g("deploy-bot"),Nr=new g("create-bot");ui.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await A(t);await Mt(r,e)});pi.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await A(t);await Mt(r,e,!0)});di.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,s)=>{let o=await A(s);await tr(o,e,t,r,n,s.runtimeVersion,!!s.writeConfig)});async function Mt(e,t,r=!1){let n=An(t),s=[],o=[],i=0,a=0;for(let l of n)try{let u=await e.readResource("Bot",l.id);await Zt(e,l,u),i++,r&&(await er(e,l,u),a++)}catch(u){s.push(u),o.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: ${s.length}`),s.length)throw new Error(`${s.length} bot(s) had failures. Bots with failures:
11
+ `+de.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",dr("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(Ri),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(Pi)),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(hi),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(Si),e}var Ii=new h("save"),Ci=new h("deploy"),Ti=new h("create"),He=new h("bot");y(He,Ii);y(He,Ci);y(He,Ti);var Mr=new h("save-bot"),Ur=new h("deploy-bot"),_r=new h("create-bot");Ii.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await b(t);await jt(r,e)});Ci.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await b(t);await jt(r,e,!0)});Ti.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,s)=>{let o=await b(s);await ar(o,e,t,r,n,s.runtimeVersion,!!s.writeConfig)});async function jt(e,t,r=!1){let n=Un(t),s=[],o=[],i=0,a=0;for(let l of n)try{let u=await e.readResource("Bot",l.id);await or(e,l,u),i++,r&&(await ir(e,l,u),a++)}catch(u){s.push(u),o.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: ${s.length}`),s.length)throw new Error(`${s.length} bot(s) had failures. Bots with failures:
12
12
 
13
13
  ${o.join(`
14
- `)}`,{cause:s})}xr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await A(t);await Mt(r,e)});$r.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await A(t);await Mt(r,e,!0)});Nr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,n,s)=>{let o=await A(s);await tr(o,e,t,r,n)});var kr=require("@medplum/core"),Dt=require("node:fs"),Lr=require("node:path"),fi=require("node:readline"),hi=require("node:stream"),gi=require("node:stream/promises");var yi=new g("export"),wi=new g("import"),_t=new g("bulk");y(_t,yi);y(_t,wi);yi.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:s}=e,o=await A(e),i=await o.bulkExport(t,r,n,{pollStatusOnAccepted:!0});for(let{type:a,url:l}of i.output??kr.EMPTY){let u=new URL(l),f=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",m=(0,Lr.resolve)(s??"",f),S=await o.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 h=hi.Readable.fromWeb(S.body);await(0,gi.pipeline)(h,(0,Dt.createWriteStream)(m)),console.log(`${m} is created`)}});wi.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:s}=t,o=(0,Lr.resolve)(s??process.cwd(),e),i=await A(t);await wp(o,Number.parseInt(r,10),i,n)});async function wp(e,t,r,n){let s=[],o=(0,Dt.createReadStream)(e),i=(0,fi.createInterface)({input:o});for await(let a of i){let l=Ep(a,n);s.push({resource:l,request:{method:"POST",url:l.resourceType}}),s.length%t===0&&(await mi(s,r),s=[])}s.length>0&&await mi(s,r)}async function mi(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let n of r.entry??kr.EMPTY)Z(n.response)}function Ep(e,t){let r=JSON.parse(e);return t?Sp(r):r}function Sp(e){return e.resourceType==="ExplanationOfBenefit"?Rp(e):e}function Rp(e){return e.provider||(e.provider=rr()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=rr())}),e}var Ut=require("@medplum/core");var Ve=L(require("node:assert"),1),Ri=L(require("node:net"),1),$=require("@medplum/core"),Mr=L(require("iconv-lite"),1),vp=require("@medplum/core");var Pi=require("@medplum/core"),Ii=L(require("node:net"),1),Ap=Object.defineProperty,bp=(e,t,r)=>t in e?Ap(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,R=(e,t,r)=>bp(e,typeof t!="symbol"?t+"":t,r),Si=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var Pp=class extends Event{constructor(e,t){super("message"),R(this,"connection"),R(this,"message"),this.connection=e,this.message=t}},Ip=class extends Event{constructor(e,t){super("enhancedAckSent"),R(this,"connection"),R(this,"message"),this.connection=e,this.message=t}},Je=class extends Event{constructor(e){super("error"),R(this,"error"),this.error=e}},Dr=class extends Event{constructor(e){super("warning"),R(this,"error"),this.error=e}},_r=class extends Event{constructor(){super("close")}},Ei="utf-8",Cp=5e3,Tp=60*1e3,Ai=class extends Si{constructor(e,t=Ei,r,n={}){super(),R(this,"socket"),R(this,"encoding"),R(this,"enhancedMode"),R(this,"messagesPerMin"),R(this,"gracefulCloseTimeoutMs"),R(this,"chunks",[]),R(this,"pendingMessages",new Map),R(this,"responseQueue",[]),R(this,"lastMessageDispatchedTime",0),R(this,"responseQueueProcessing",!1),R(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=n.messagesPerMin,this.gracefulCloseTimeoutMs=n.gracefulCloseTimeoutMs??Cp,e.on("data",s=>{if(this.closing){this.dispatchEvent(new Dr(new $.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(s);let o=this.parseMessages();for(let i of o)this.responseQueue.push(new Pp(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new Je(i))})}catch(o){this.dispatchEvent(new Je(o))}}),e.on("error",s=>{this.resetBuffer(),this.dispatchEvent(new Je(s))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new _r)}),this.addEventListener("message",s=>{let o;this.enhancedMode==="standard"?o=s.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(o=s.message.buildAck({ackCode:"AA"})),o&&(this.send(o),this.dispatchEvent(new Ip(this,o)));let i=s.message.getSegment("MSA")?.getField(2)?.toString();if(!i)return;let a=this.getPendingMessage(i);if(!a){this.dispatchEvent(new Dr(new $.OperationOutcomeError({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=s.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();l&&(a.returnAck===$.ReturnAckCategory.APPLICATION&&l==="CA"||(a.timer&&clearTimeout(a.timer),a.resolve(s.message),this.deletePendingMessage(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Mr.default.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=Tp/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await(0,$.sleep)(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 s=t.subarray(r,n+1).subarray(1,-2),o=Mr.default.decode(s,this.encoding),i=$.Hl7Message.parse(o);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 s=e.getSegment("MSH")?.getField(10)?.toString();if(!s){n(new $.OperationOutcomeError((0,$.validationError)("Required field missing: MSH.10")));return}let o;t?.timeoutMs&&(o=setTimeout(()=>{this.deletePendingMessage(s),n(new $.OperationOutcomeError({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(s,{message:e,resolve:r,reject:n,returnAck:t?.returnAck??$.ReturnAckCategory.APPLICATION,timer:o}),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 $.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Je(new $.OperationOutcomeError({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??Ei}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)}},bi=class extends Si{constructor(e){super(),R(this,"options"),R(this,"host"),R(this,"port"),R(this,"encoding"),R(this,"connection"),R(this,"keepAlive"),R(this,"socket"),R(this,"connectTimeout"),R(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=Ri.default.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){(0,Ve.default)(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){(0,Ve.default)(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){(0,Ve.default)(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){(0,Ve.default)(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 _r)}),e.addEventListener("error",t=>{this.dispatchEvent(new Je(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 Ai(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 _r);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}};var Op=1e4,vi=class{constructor(e){R(this,"handler"),R(this,"server"),R(this,"encoding"),R(this,"enhancedMode"),R(this,"messagesPerMin"),R(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 s=Ii.default.createServer(o=>{let i=new Ai(o,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(i),this.connections.add(i),i.addEventListener("close",()=>{this.connections.delete(i)})});return new Promise((o,i)=>{let a=u=>{s.listen(u,()=>{let f=s.address().port;o(f)})},l=u=>{u?.code==="EADDRINUSE"?s.close(()=>(0,Pi.sleep)(50).then(()=>a(e))):i(u)};s.on("error",l),s.once("listening",()=>{s.off("error",l)}),a(e),this.server=s})}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 s of this.connections)s.close().catch(console.error)},e?.forceDrainTimeoutMs??Op)),this.server.close(s=>{if(s){r(s);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}};var Ci=require("node:fs");var xp=new g("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,n)=>{if(n.generateExample?r=Np():n.file&&(r=(0,Ci.readFileSync)(n.file,"utf8")),!r)throw new Error("Missing HL7 message body");let s=new bi({host:e,port:Number.parseInt(t,10),encoding:n.encoding});try{let o=await s.sendAndWait(Ut.Hl7Message.parse(r));console.log(o.toString().replaceAll("\r",`
15
- `))}finally{await s.close()}}),$p=new g("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{await new vi(n=>{n.addEventListener("message",({message:s})=>{console.log(s.toString().replaceAll("\r",`
16
- `)),n.send(s.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),jt=new g("hl7");y(jt,xp);y(jt,$p);function Np(){let e=(0,Ut.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
14
+ `)}`,{cause:s})}Mr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await b(t);await jt(r,e)});Ur.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await b(t);await jt(r,e,!0)});_r.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,n,s)=>{let o=await b(s);await ar(o,e,t,r,n)});var jr=require("@medplum/core"),Ft=require("node:fs"),Fr=require("node:path"),xi=require("node:readline"),$i=require("node:stream"),Ni=require("node:stream/promises");var ki=new h("export"),Li=new h("import"),Bt=new h("bulk");y(Bt,ki);y(Bt,Li);ki.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:s}=e,o=await b(e),i=await o.bulkExport(t,r,n,{pollStatusOnAccepted:!0});for(let{type:a,url:l}of i.output??jr.EMPTY){let u=new URL(l),f=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",m=(0,Fr.resolve)(s??"",f),S=await o.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=$i.Readable.fromWeb(S.body);await(0,Ni.pipeline)(g,(0,Ft.createWriteStream)(m)),console.log(`${m} is created`)}});Li.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:s}=t,o=(0,Fr.resolve)(s??process.cwd(),e),i=await b(t);await kp(o,Number.parseInt(r,10),i,n)});async function kp(e,t,r,n){let s=[],o=(0,Ft.createReadStream)(e),i=(0,xi.createInterface)({input:o});for await(let a of i){let l=Lp(a,n);s.push({resource:l,request:{method:"POST",url:l.resourceType}}),s.length%t===0&&(await Oi(s,r),s=[])}s.length>0&&await Oi(s,r)}async function Oi(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let n of r.entry??jr.EMPTY)ne(n.response)}function Lp(e,t){let r=JSON.parse(e);return t?Dp(r):r}function Dp(e){return e.resourceType==="ExplanationOfBenefit"?Mp(e):e}function Mp(e){return e.provider||(e.provider=cr()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=cr())}),e}var Wt=require("@medplum/core");var Je=ee(require("node:assert"),1),Ui=ee(require("node:net"),1),N=require("@medplum/core"),Br=ee(require("iconv-lite"),1),Bp=require("@medplum/core");var Fi=require("@medplum/core"),Bi=ee(require("node:net"),1),Up=Object.defineProperty,_p=(e,t,r)=>t in e?Up(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t,r)=>_p(e,typeof t!="symbol"?t+"":t,r),Mi=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var jp=class extends Event{constructor(e,t){super("message"),A(this,"connection"),A(this,"message"),this.connection=e,this.message=t}},Fp=class extends Event{constructor(e,t){super("enhancedAckSent"),A(this,"connection"),A(this,"message"),this.connection=e,this.message=t}},Xe=class extends Event{constructor(e){super("error"),A(this,"error"),this.error=e}},Wr=class extends Event{constructor(e){super("warning"),A(this,"error"),this.error=e}},qr=class extends Event{constructor(){super("close")}},Di="utf-8",Wp=5e3,qp=60*1e3,_i=class extends Mi{constructor(e,t=Di,r,n={}){super(),A(this,"socket"),A(this,"encoding"),A(this,"enhancedMode"),A(this,"messagesPerMin"),A(this,"gracefulCloseTimeoutMs"),A(this,"chunks",[]),A(this,"pendingMessages",new Map),A(this,"responseQueue",[]),A(this,"lastMessageDispatchedTime",0),A(this,"responseQueueProcessing",!1),A(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=n.messagesPerMin,this.gracefulCloseTimeoutMs=n.gracefulCloseTimeoutMs??Wp,e.on("data",s=>{if(this.closing){this.dispatchEvent(new Wr(new N.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(s);let o=this.parseMessages();for(let i of o)this.responseQueue.push(new jp(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new Xe(i))})}catch(o){this.dispatchEvent(new Xe(o))}}),e.on("error",s=>{this.resetBuffer(),this.dispatchEvent(new Xe(s))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new qr)}),this.addEventListener("message",s=>{let o;this.enhancedMode==="standard"?o=s.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(o=s.message.buildAck({ackCode:"AA"})),o&&(this.send(o),this.dispatchEvent(new Fp(this,o)));let i=s.message.getSegment("MSA")?.getField(2)?.toString();if(!i)return;let a=this.getPendingMessage(i);if(!a){this.dispatchEvent(new Wr(new N.OperationOutcomeError({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=s.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();l&&(a.returnAck===N.ReturnAckCategory.APPLICATION&&l==="CA"||(a.timer&&clearTimeout(a.timer),a.resolve(s.message),this.deletePendingMessage(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Br.default.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=qp/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await(0,N.sleep)(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 s=t.subarray(r,n+1).subarray(1,-2),o=Br.default.decode(s,this.encoding),i=N.Hl7Message.parse(o);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 s=e.getSegment("MSH")?.getField(10)?.toString();if(!s){n(new N.OperationOutcomeError((0,N.validationError)("Required field missing: MSH.10")));return}let o;t?.timeoutMs&&(o=setTimeout(()=>{this.deletePendingMessage(s),n(new N.OperationOutcomeError({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(s,{message:e,resolve:r,reject:n,returnAck:t?.returnAck??N.ReturnAckCategory.APPLICATION,timer:o}),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 N.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Xe(new N.OperationOutcomeError({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??Di}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)}},ji=class extends Mi{constructor(e){super(),A(this,"options"),A(this,"host"),A(this,"port"),A(this,"encoding"),A(this,"connection"),A(this,"keepAlive"),A(this,"socket"),A(this,"connectTimeout"),A(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=Ui.default.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){(0,Je.default)(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){(0,Je.default)(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){(0,Je.default)(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){(0,Je.default)(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 qr)}),e.addEventListener("error",t=>{this.dispatchEvent(new Xe(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new Wr(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 _i(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 qr);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}};var Kp=1e4,Wi=class{constructor(e){A(this,"handler"),A(this,"server"),A(this,"encoding"),A(this,"enhancedMode"),A(this,"messagesPerMin"),A(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 s=Bi.default.createServer(o=>{let i=new _i(o,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(i),this.connections.add(i),i.addEventListener("close",()=>{this.connections.delete(i)})});return new Promise((o,i)=>{let a=u=>{s.listen(u,()=>{let f=s.address().port;o(f)})},l=u=>{u?.code==="EADDRINUSE"?s.close(()=>(0,Fi.sleep)(50).then(()=>a(e))):i(u)};s.on("error",l),s.once("listening",()=>{s.off("error",l)}),a(e),this.server=s})}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 s of this.connections)s.close().catch(console.error)},e?.forceDrainTimeoutMs??Kp)),this.server.close(s=>{if(s){r(s);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}};var qi=require("node:fs");var Gp=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=Hp():n.file&&(r=(0,qi.readFileSync)(n.file,"utf8")),!r)throw new Error("Missing HL7 message body");let s=new ji({host:e,port:Number.parseInt(t,10),encoding:n.encoding});try{let o=await s.sendAndWait(Wt.Hl7Message.parse(r));console.log(o.toString().replaceAll("\r",`
15
+ `))}finally{await s.close()}}),Vp=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 Wi(n=>{n.addEventListener("message",({message:s})=>{console.log(s.toString().replaceAll("\r",`
16
+ `)),n.send(s.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),qt=new h("hl7");y(qt,Gp);y(qt,Vp);function Hp(){let e=(0,Wt.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
17
17
  EVN|A01|${e}||
18
18
  PID|1|12345|12345^^^HOSP^MR|123456|DOE^JOHN^MIDDLE^SUFFIX|19800101|M|||123 STREET^APT 4B^CITY^ST^12345-6789||555-555-5555||S|
19
- PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var Ti=require("node:fs"),Oi=require("node:os"),xi=require("node:path");var $i=new g("set"),Ni=new g("remove"),ki=new g("list"),Li=new g("describe"),ve=new g("profile");y(ve,$i);y(ve,Ni);y(ve,ki);y(ve,Li);$i.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)=>{ot(e,t)});Ni.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new K(e).setObject("options",void 0),console.log(`${e} profile removed`)});ki.description("List all profiles saved").action(async()=>{let e=(0,xi.resolve)((0,Oi.homedir)(),".medplum"),t=(0,Ti.readdirSync)(e),r=[];t.forEach(n=>{let s=n.split(".")[0],i=new K(s).getObject("options");i&&r.push({profileName:s,profile:i})}),console.log(r)});Li.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=In(e);console.log(t)});var Mi=require("commander");var Di=new g("list"),_i=new g("current"),Ui=new g("switch"),ji=new g("invite"),Ce=new g("project");y(Ce,Di);y(Ce,_i);y(Ce,Ui);y(Ce,ji);Di.description("List of current projects").action(async e=>{let t=await A(e);kp(t)});function kp(e){let r=e.getLogins().map(n=>`${n.project.display} (${n.project.reference})`).join(`
19
+ PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var Ki=require("node:fs"),Gi=require("node:os"),Vi=require("node:path");var Hi=new h("set"),Ji=new h("remove"),Xi=new h("list"),zi=new h("describe"),Te=new h("profile");y(Te,Hi);y(Te,Ji);y(Te,Xi);y(Te,zi);Hi.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{lt(e,t)});Ji.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new J(e).setObject("options",void 0),console.log(`${e} profile removed`)});Xi.description("List all profiles saved").action(async()=>{let e=(0,Vi.resolve)((0,Gi.homedir)(),".medplum"),t=(0,Ki.readdirSync)(e),r=[];t.forEach(n=>{let s=n.split(".")[0],i=new J(s).getObject("options");i&&r.push({profileName:s,profile:i})}),console.log(r)});zi.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=Fn(e);console.log(t)});var Yi=require("commander");var Qi=new h("list"),Zi=new h("current"),ea=new h("switch"),ta=new h("invite"),Oe=new h("project");y(Oe,Qi);y(Oe,Zi);y(Oe,ea);y(Oe,ta);Qi.description("List of current projects").action(async e=>{let t=await b(e);Jp(t)});function Jp(e){let r=e.getLogins().map(n=>`${n.project.display} (${n.project.reference})`).join(`
20
20
 
21
- `);console.log(r)}_i.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})`)});Ui.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await A(t);await Lp(r,e)});ji.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 Mi.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,n)=>{let s=await A(n),o=s.getActiveLogin();if(!o)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!o?.project?.reference)throw new Error("No current project to invite user to");let i=o.project.reference.split("/")[1],a={resourceType:n.role,firstName:e,lastName:t,email:r,sendEmail:!!n.sendEmail,admin:!!n.admin};await Mp(i,a,s)});async function Lp(e,t){let n=e.getLogins().find(s=>s.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}
22
- `)}async function Mp(e,t,r){await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var Fi=require("@medplum/core");var Ur=new g("delete"),jr=new g("get"),Fr=new g("patch"),Br=new g("post"),Wr=new g("put");Ur.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await A(t);Z(await r.delete(Xe(r,e)))});jr.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(Xe(r,e));t.asTransaction?Z((0,Fi.convertToTransactionBundle)(n)):Z(n)});Fr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await A(r);Z(await n.patch(Xe(n,e),Kr(t)))});Br.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let n=await A(r),s=r.preferAsync?{Prefer:"respond-async"}:void 0;Z(await n.post(Xe(n,e),Kr(t),void 0,{headers:s}))});Wr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await A(r);Z(await n.put(Xe(n,e),Kr(t)))});function Kr(e){if(e)try{return JSON.parse(e)}catch{return e}}function Xe(e,t){return["admin/","auth/","fhir/R4"].some(n=>t.startsWith(n))?t:e.fhirUrl(t).toString()}async function Wi(e){let t=new g("medplum").description("Command to access Medplum CLI").option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base URL, must be absolute").option("--token-url <tokenUrl>","FHIR server token URL, absolute or relative to base URL").option("--authorize-url <authorizeUrl>","FHIR server authorize URL, absolute or relative to base URL").option("--fhir-url, --fhir-url-path <fhirUrlPath>","FHIR server URL, absolute or relative to base URL").option("--scope <scope>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new ze.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"])).on("option:verbose",()=>{process.env.VERBOSE="1"});t.exitOverride(),t.version(Te.MEDPLUM_VERSION),t.configureHelp({showGlobalOptions:!0}),y(t,nr),y(t,sr),y(t,or),y(t,jr),y(t,Br),y(t,Fr),y(t,Wr),y(t,Ur),y(t,Ce),y(t,_t),y(t,Ge),y(t,se),y(t,xr),y(t,$r),y(t,Nr),y(t,ve),y(t,li()),y(t,jt);try{await t.parseAsync(e)}catch(r){Ki(r)}}function Ki(e){let t=1,r=!0;if(e instanceof ze.CommanderError&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){qr(e,!!process.env.VERBOSE);let n=e.cause;if(process.env.VERBOSE)if(Array.isArray(n))for(let s of n)qr(s,!0);else n instanceof Error&&qr(n,!0)}process.exit(t)}function qr(e,t=!1){if(t){console.error(e);return}e instanceof ze.CommanderError?process.stderr.write(`${(0,Te.normalizeErrorString)(e)}
23
- `):process.stderr.write(`Error: ${(0,Te.normalizeErrorString)(e)}
24
- `)}async function qi(){Bi.default.config({quiet:!0}),await Wi(process.argv)}qi().catch(e=>{console.error("Unhandled error:",(0,Te.normalizeErrorString)(e)),process.exit(1)});0&&(module.exports={handleError,main,run});
21
+ `);console.log(r)}Zi.description("Project you are currently on").action(async e=>{let r=(await b(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});ea.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await b(t);await Xp(r,e)});ta.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 Yi.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,n)=>{let s=await b(n),o=s.getActiveLogin();if(!o)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!o?.project?.reference)throw new Error("No current project to invite user to");let i=o.project.reference.split("/")[1],a={resourceType:n.role,firstName:e,lastName:t,email:r,sendEmail:!!n.sendEmail,admin:!!n.admin};await zp(i,a,s)});async function Xp(e,t){let n=e.getLogins().find(s=>s.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}
22
+ `)}async function zp(e,t,r){await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var ra=require("@medplum/core");var Kr=new h("delete"),Gr=new h("get"),Vr=new h("patch"),Hr=new h("post"),Jr=new h("put");Kr.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await b(t);ne(await r.delete(ze(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 b(t),n=await r.get(ze(r,e));t.asTransaction?ne((0,ra.convertToTransactionBundle)(n)):ne(n)});Vr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await b(r);ne(await n.patch(ze(n,e),Xr(t)))});Hr.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let n=await b(r),s=r.preferAsync?{Prefer:"respond-async"}:void 0;ne(await n.post(ze(n,e),Xr(t),void 0,{headers:s}))});Jr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await b(r);ne(await n.put(ze(n,e),Xr(t)))});function Xr(e){if(e)try{return JSON.parse(e)}catch{return e}}function ze(e,t){return["admin/","auth/","fhir/R4"].some(n=>t.startsWith(n))?t:e.fhirUrl(t).toString()}async function sa(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>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new Ye.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"])).on("option:verbose",()=>{process.env.VERBOSE="1"});t.exitOverride(),t.version(xe.MEDPLUM_VERSION),t.configureHelp({showGlobalOptions:!0}),y(t,lr),y(t,ur),y(t,pr),y(t,Gr),y(t,Hr),y(t,Vr),y(t,Jr),y(t,Kr),y(t,Oe),y(t,Bt),y(t,He),y(t,ae),y(t,Mr),y(t,Ur),y(t,_r),y(t,Te),y(t,vi()),y(t,qt);try{await t.parseAsync(e)}catch(r){oa(r)}}function oa(e){let t=1,r=!0;if(e instanceof Ye.CommanderError&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){zr(e,!!process.env.VERBOSE);let n=e.cause;if(process.env.VERBOSE)if(Array.isArray(n))for(let s of n)zr(s,!0);else n instanceof Error&&zr(n,!0)}process.exit(t)}function zr(e,t=!1){if(t){console.error(e);return}e instanceof Ye.CommanderError?process.stderr.write(`${(0,xe.normalizeErrorString)(e)}
23
+ `):process.stderr.write(`Error: ${(0,xe.normalizeErrorString)(e)}
24
+ `)}async function ia(){na.default.config({quiet:!0}),await sa(process.argv)}ia().catch(e=>{console.error("Unhandled error:",(0,xe.normalizeErrorString)(e)),process.exit(1)});0&&(module.exports={handleError,main,run});
25
25
  //# sourceMappingURL=index.cjs.map