@medplum/cli 5.1.6 → 5.1.7

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