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