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