@medplum/cli 3.1.11 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Cn=Object.create;var Te=Object.defineProperty;var In=Object.getOwnPropertyDescriptor;var Pn=Object.getOwnPropertyNames;var Rn=Object.getPrototypeOf,Tn=Object.prototype.hasOwnProperty;var xn=(e,t,r)=>t in e?Te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var On=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Nn=(e,t)=>{for(var r in t)Te(e,r,{get:t[r],enumerable:!0})},fr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Pn(t))!Tn.call(e,n)&&n!==r&&Te(e,n,{get:()=>t[n],enumerable:!(o=In(t,n))||o.enumerable});return e};var H=(e,t,r)=>(r=e!=null?Cn(Rn(e)):{},fr(t||!e||!e.__esModule?Te(r,"default",{value:e,enumerable:!0}):r,e)),_n=e=>fr(Te({},"__esModule",{value:!0}),e);var v=(e,t,r)=>xn(e,typeof t!="symbol"?t+"":t,r);var er=On((u,no)=>{"use strict";u=no.exports=m;var w;typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?w=function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:w=function(){};u.SEMVER_SPEC_VERSION="2.0.0";var Le=256,tt=Number.MAX_SAFE_INTEGER||9007199254740991,Vt=16,Di=Le-6,Se=u.re=[],g=u.safeRe=[],p=u.src=[],a=u.tokens={},ro=0;function f(e){a[e]=ro++}var zt="[a-zA-Z0-9-]",Xt=[["\\s",1],["\\d",Le],[zt,Di]];function We(e){for(var t=0;t<Xt.length;t++){var r=Xt[t][0],o=Xt[t][1];e=e.split(r+"*").join(r+"{0,"+o+"}").split(r+"+").join(r+"{1,"+o+"}")}return e}f("NUMERICIDENTIFIER");p[a.NUMERICIDENTIFIER]="0|[1-9]\\d*";f("NUMERICIDENTIFIERLOOSE");p[a.NUMERICIDENTIFIERLOOSE]="\\d+";f("NONNUMERICIDENTIFIER");p[a.NONNUMERICIDENTIFIER]="\\d*[a-zA-Z-]"+zt+"*";f("MAINVERSION");p[a.MAINVERSION]="("+p[a.NUMERICIDENTIFIER]+")\\.("+p[a.NUMERICIDENTIFIER]+")\\.("+p[a.NUMERICIDENTIFIER]+")";f("MAINVERSIONLOOSE");p[a.MAINVERSIONLOOSE]="("+p[a.NUMERICIDENTIFIERLOOSE]+")\\.("+p[a.NUMERICIDENTIFIERLOOSE]+")\\.("+p[a.NUMERICIDENTIFIERLOOSE]+")";f("PRERELEASEIDENTIFIER");p[a.PRERELEASEIDENTIFIER]="(?:"+p[a.NUMERICIDENTIFIER]+"|"+p[a.NONNUMERICIDENTIFIER]+")";f("PRERELEASEIDENTIFIERLOOSE");p[a.PRERELEASEIDENTIFIERLOOSE]="(?:"+p[a.NUMERICIDENTIFIERLOOSE]+"|"+p[a.NONNUMERICIDENTIFIER]+")";f("PRERELEASE");p[a.PRERELEASE]="(?:-("+p[a.PRERELEASEIDENTIFIER]+"(?:\\."+p[a.PRERELEASEIDENTIFIER]+")*))";f("PRERELEASELOOSE");p[a.PRERELEASELOOSE]="(?:-?("+p[a.PRERELEASEIDENTIFIERLOOSE]+"(?:\\."+p[a.PRERELEASEIDENTIFIERLOOSE]+")*))";f("BUILDIDENTIFIER");p[a.BUILDIDENTIFIER]=zt+"+";f("BUILD");p[a.BUILD]="(?:\\+("+p[a.BUILDIDENTIFIER]+"(?:\\."+p[a.BUILDIDENTIFIER]+")*))";f("FULL");f("FULLPLAIN");p[a.FULLPLAIN]="v?"+p[a.MAINVERSION]+p[a.PRERELEASE]+"?"+p[a.BUILD]+"?";p[a.FULL]="^"+p[a.FULLPLAIN]+"$";f("LOOSEPLAIN");p[a.LOOSEPLAIN]="[v=\\s]*"+p[a.MAINVERSIONLOOSE]+p[a.PRERELEASELOOSE]+"?"+p[a.BUILD]+"?";f("LOOSE");p[a.LOOSE]="^"+p[a.LOOSEPLAIN]+"$";f("GTLT");p[a.GTLT]="((?:<|>)?=?)";f("XRANGEIDENTIFIERLOOSE");p[a.XRANGEIDENTIFIERLOOSE]=p[a.NUMERICIDENTIFIERLOOSE]+"|x|X|\\*";f("XRANGEIDENTIFIER");p[a.XRANGEIDENTIFIER]=p[a.NUMERICIDENTIFIER]+"|x|X|\\*";f("XRANGEPLAIN");p[a.XRANGEPLAIN]="[v=\\s]*("+p[a.XRANGEIDENTIFIER]+")(?:\\.("+p[a.XRANGEIDENTIFIER]+")(?:\\.("+p[a.XRANGEIDENTIFIER]+")(?:"+p[a.PRERELEASE]+")?"+p[a.BUILD]+"?)?)?";f("XRANGEPLAINLOOSE");p[a.XRANGEPLAINLOOSE]="[v=\\s]*("+p[a.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+p[a.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+p[a.XRANGEIDENTIFIERLOOSE]+")(?:"+p[a.PRERELEASELOOSE]+")?"+p[a.BUILD]+"?)?)?";f("XRANGE");p[a.XRANGE]="^"+p[a.GTLT]+"\\s*"+p[a.XRANGEPLAIN]+"$";f("XRANGELOOSE");p[a.XRANGELOOSE]="^"+p[a.GTLT]+"\\s*"+p[a.XRANGEPLAINLOOSE]+"$";f("COERCE");p[a.COERCE]="(^|[^\\d])(\\d{1,"+Vt+"})(?:\\.(\\d{1,"+Vt+"}))?(?:\\.(\\d{1,"+Vt+"}))?(?:$|[^\\d])";f("COERCERTL");Se[a.COERCERTL]=new RegExp(p[a.COERCE],"g");g[a.COERCERTL]=new RegExp(We(p[a.COERCE]),"g");f("LONETILDE");p[a.LONETILDE]="(?:~>?)";f("TILDETRIM");p[a.TILDETRIM]="(\\s*)"+p[a.LONETILDE]+"\\s+";Se[a.TILDETRIM]=new RegExp(p[a.TILDETRIM],"g");g[a.TILDETRIM]=new RegExp(We(p[a.TILDETRIM]),"g");var ki="$1~";f("TILDE");p[a.TILDE]="^"+p[a.LONETILDE]+p[a.XRANGEPLAIN]+"$";f("TILDELOOSE");p[a.TILDELOOSE]="^"+p[a.LONETILDE]+p[a.XRANGEPLAINLOOSE]+"$";f("LONECARET");p[a.LONECARET]="(?:\\^)";f("CARETTRIM");p[a.CARETTRIM]="(\\s*)"+p[a.LONECARET]+"\\s+";Se[a.CARETTRIM]=new RegExp(p[a.CARETTRIM],"g");g[a.CARETTRIM]=new RegExp(We(p[a.CARETTRIM]),"g");var Hi="$1^";f("CARET");p[a.CARET]="^"+p[a.LONECARET]+p[a.XRANGEPLAIN]+"$";f("CARETLOOSE");p[a.CARETLOOSE]="^"+p[a.LONECARET]+p[a.XRANGEPLAINLOOSE]+"$";f("COMPARATORLOOSE");p[a.COMPARATORLOOSE]="^"+p[a.GTLT]+"\\s*("+p[a.LOOSEPLAIN]+")$|^$";f("COMPARATOR");p[a.COMPARATOR]="^"+p[a.GTLT]+"\\s*("+p[a.FULLPLAIN]+")$|^$";f("COMPARATORTRIM");p[a.COMPARATORTRIM]="(\\s*)"+p[a.GTLT]+"\\s*("+p[a.LOOSEPLAIN]+"|"+p[a.XRANGEPLAIN]+")";Se[a.COMPARATORTRIM]=new RegExp(p[a.COMPARATORTRIM],"g");g[a.COMPARATORTRIM]=new RegExp(We(p[a.COMPARATORTRIM]),"g");var Ki="$1$2$3";f("HYPHENRANGE");p[a.HYPHENRANGE]="^\\s*("+p[a.XRANGEPLAIN]+")\\s+-\\s+("+p[a.XRANGEPLAIN]+")\\s*$";f("HYPHENRANGELOOSE");p[a.HYPHENRANGELOOSE]="^\\s*("+p[a.XRANGEPLAINLOOSE]+")\\s+-\\s+("+p[a.XRANGEPLAINLOOSE]+")\\s*$";f("STAR");p[a.STAR]="(<|>)?=?\\s*\\*";for(X=0;X<ro;X++)w(X,p[X]),Se[X]||(Se[X]=new RegExp(p[X]),g[X]=new RegExp(We(p[X])));var X;u.parse=le;function le(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof m)return e;if(typeof e!="string"||e.length>Le)return null;var r=t.loose?g[a.LOOSE]:g[a.FULL];if(!r.test(e))return null;try{return new m(e,t)}catch{return null}}u.valid=Li;function Li(e,t){var r=le(e,t);return r?r.version:null}u.clean=Mi;function Mi(e,t){var r=le(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null}u.SemVer=m;function m(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof m){if(e.loose===t.loose)return e;e=e.version}else if(typeof e!="string")throw new TypeError("Invalid Version: "+e);if(e.length>Le)throw new TypeError("version is longer than "+Le+" characters");if(!(this instanceof m))return new m(e,t);w("SemVer",e,t),this.options=t,this.loose=!!t.loose;var r=e.trim().match(t.loose?g[a.LOOSE]:g[a.FULL]);if(!r)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>tt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>tt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>tt||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(function(o){if(/^[0-9]+$/.test(o)){var n=+o;if(n>=0&&n<tt)return n}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}m.prototype.format=function(){return this.version=this.major+"."+this.minor+"."+this.patch,this.prerelease.length&&(this.version+="-"+this.prerelease.join(".")),this.version};m.prototype.toString=function(){return this.version};m.prototype.compare=function(e){return w("SemVer.compare",this.version,this.options,e),e instanceof m||(e=new m(e,this.options)),this.compareMain(e)||this.comparePre(e)};m.prototype.compareMain=function(e){return e instanceof m||(e=new m(e,this.options)),de(this.major,e.major)||de(this.minor,e.minor)||de(this.patch,e.patch)};m.prototype.comparePre=function(e){if(e instanceof m||(e=new m(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;var t=0;do{var r=this.prerelease[t],o=e.prerelease[t];if(w("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return de(r,o)}while(++t)};m.prototype.compareBuild=function(e){e instanceof m||(e=new m(e,this.options));var t=0;do{var r=this.build[t],o=e.build[t];if(w("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return de(r,o)}while(++t)};m.prototype.inc=function(e,t){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t),this.inc("pre",t);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t),this.inc("pre",t);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":if(this.prerelease.length===0)this.prerelease=[0];else{for(var r=this.prerelease.length;--r>=0;)typeof this.prerelease[r]=="number"&&(this.prerelease[r]++,r=-2);r===-1&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this};u.inc=Wi;function Wi(e,t,r,o){typeof r=="string"&&(o=r,r=void 0);try{return new m(e,r).inc(t,o).version}catch{return null}}u.diff=Ui;function Ui(e,t){if(qt(e,t))return null;var r=le(e),o=le(t),n="";if(r.prerelease.length||o.prerelease.length){n="pre";var i="prerelease"}for(var s in r)if((s==="major"||s==="minor"||s==="patch")&&r[s]!==o[s])return n+s;return i}u.compareIdentifiers=de;var eo=/^[0-9]+$/;function de(e,t){var r=eo.test(e),o=eo.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1}u.rcompareIdentifiers=Ji;function Ji(e,t){return de(t,e)}u.major=$i;function $i(e,t){return new m(e,t).major}u.minor=Fi;function Fi(e,t){return new m(e,t).minor}u.patch=Bi;function Bi(e,t){return new m(e,t).patch}u.compare=re;function re(e,t,r){return new m(e,r).compare(new m(t,r))}u.compareLoose=Gi;function Gi(e,t){return re(e,t,!0)}u.compareBuild=ji;function ji(e,t,r){var o=new m(e,r),n=new m(t,r);return o.compare(n)||o.compareBuild(n)}u.rcompare=Vi;function Vi(e,t,r){return re(t,e,r)}u.sort=Xi;function Xi(e,t){return e.sort(function(r,o){return u.compareBuild(r,o,t)})}u.rsort=zi;function zi(e,t){return e.sort(function(r,o){return u.compareBuild(o,r,t)})}u.gt=Me;function Me(e,t,r){return re(e,t,r)>0}u.lt=rt;function rt(e,t,r){return re(e,t,r)<0}u.eq=qt;function qt(e,t,r){return re(e,t,r)===0}u.neq=oo;function oo(e,t,r){return re(e,t,r)!==0}u.gte=Yt;function Yt(e,t,r){return re(e,t,r)>=0}u.lte=Zt;function Zt(e,t,r){return re(e,t,r)<=0}u.cmp=ot;function ot(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 qt(e,r,o);case"!=":return oo(e,r,o);case">":return Me(e,r,o);case">=":return Yt(e,r,o);case"<":return rt(e,r,o);case"<=":return Zt(e,r,o);default:throw new TypeError("Invalid operator: "+t)}}u.Comparator=J;function J(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof J){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof J))return new J(e,t);e=e.trim().split(/\s+/).join(" "),w("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Ae?this.value="":this.value=this.operator+this.semver.version,w("comp",this)}var Ae={};J.prototype.parse=function(e){var t=this.options.loose?g[a.COMPARATORLOOSE]:g[a.COMPARATOR],r=e.match(t);if(!r)throw new TypeError("Invalid comparator: "+e);this.operator=r[1]!==void 0?r[1]:"",this.operator==="="&&(this.operator=""),r[2]?this.semver=new m(r[2],this.options.loose):this.semver=Ae};J.prototype.toString=function(){return this.value};J.prototype.test=function(e){if(w("Comparator.test",e,this.options.loose),this.semver===Ae||e===Ae)return!0;if(typeof e=="string")try{e=new m(e,this.options)}catch{return!1}return ot(e,this.operator,this.semver,this.options)};J.prototype.intersects=function(e,t){if(!(e instanceof J))throw new TypeError("a Comparator is required");(!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1});var r;if(this.operator==="")return this.value===""?!0:(r=new I(e.value,t),nt(this.value,r,t));if(e.operator==="")return e.value===""?!0:(r=new I(this.value,t),nt(e.semver,r,t));var o=(this.operator===">="||this.operator===">")&&(e.operator===">="||e.operator===">"),n=(this.operator==="<="||this.operator==="<")&&(e.operator==="<="||e.operator==="<"),i=this.semver.version===e.semver.version,s=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<="),d=ot(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),l=ot(this.semver,">",e.semver,t)&&(this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">");return o||n||i&&s||d||l};u.Range=I;function I(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof I)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new I(e.raw,t);if(e instanceof J)return new I(e.value,t);if(!(this instanceof I))return new I(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().split(/\s+/).join(" "),this.set=this.raw.split("||").map(function(r){return this.parseRange(r.trim())},this).filter(function(r){return r.length}),!this.set.length)throw new TypeError("Invalid SemVer Range: "+this.raw);this.format()}I.prototype.format=function(){return this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim(),this.range};I.prototype.toString=function(){return this.range};I.prototype.parseRange=function(e){var t=this.options.loose,r=t?g[a.HYPHENRANGELOOSE]:g[a.HYPHENRANGE];e=e.replace(r,ia),w("hyphen replace",e),e=e.replace(g[a.COMPARATORTRIM],Ki),w("comparator trim",e,g[a.COMPARATORTRIM]),e=e.replace(g[a.TILDETRIM],ki),e=e.replace(g[a.CARETTRIM],Hi),e=e.split(/\s+/).join(" ");var o=t?g[a.COMPARATORLOOSE]:g[a.COMPARATOR],n=e.split(" ").map(function(i){return Yi(i,this.options)},this).join(" ").split(/\s+/);return this.options.loose&&(n=n.filter(function(i){return!!i.match(o)})),n=n.map(function(i){return new J(i,this.options)},this),n};I.prototype.intersects=function(e,t){if(!(e instanceof I))throw new TypeError("a Range is required");return this.set.some(function(r){return to(r,t)&&e.set.some(function(o){return to(o,t)&&r.every(function(n){return o.every(function(i){return n.intersects(i,t)})})})})};function to(e,t){for(var r=!0,o=e.slice(),n=o.pop();r&&o.length;)r=o.every(function(i){return n.intersects(i,t)}),n=o.pop();return r}u.toComparators=qi;function qi(e,t){return new I(e,t).set.map(function(r){return r.map(function(o){return o.value}).join(" ").trim().split(" ")})}function Yi(e,t){return w("comp",e,t),e=ea(e,t),w("caret",e),e=Zi(e,t),w("tildes",e),e=ra(e,t),w("xrange",e),e=na(e,t),w("stars",e),e}function O(e){return!e||e.toLowerCase()==="x"||e==="*"}function Zi(e,t){return e.trim().split(/\s+/).map(function(r){return Qi(r,t)}).join(" ")}function Qi(e,t){var r=t.loose?g[a.TILDELOOSE]:g[a.TILDE];return e.replace(r,function(o,n,i,s,d){w("tilde",e,o,n,i,s,d);var l;return O(n)?l="":O(i)?l=">="+n+".0.0 <"+(+n+1)+".0.0":O(s)?l=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":d?(w("replaceTilde pr",d),l=">="+n+"."+i+"."+s+"-"+d+" <"+n+"."+(+i+1)+".0"):l=">="+n+"."+i+"."+s+" <"+n+"."+(+i+1)+".0",w("tilde return",l),l})}function ea(e,t){return e.trim().split(/\s+/).map(function(r){return ta(r,t)}).join(" ")}function ta(e,t){w("caret",e,t);var r=t.loose?g[a.CARETLOOSE]:g[a.CARET];return e.replace(r,function(o,n,i,s,d){w("caret",e,o,n,i,s,d);var l;return O(n)?l="":O(i)?l=">="+n+".0.0 <"+(+n+1)+".0.0":O(s)?n==="0"?l=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":l=">="+n+"."+i+".0 <"+(+n+1)+".0.0":d?(w("replaceCaret pr",d),n==="0"?i==="0"?l=">="+n+"."+i+"."+s+"-"+d+" <"+n+"."+i+"."+(+s+1):l=">="+n+"."+i+"."+s+"-"+d+" <"+n+"."+(+i+1)+".0":l=">="+n+"."+i+"."+s+"-"+d+" <"+(+n+1)+".0.0"):(w("no pr"),n==="0"?i==="0"?l=">="+n+"."+i+"."+s+" <"+n+"."+i+"."+(+s+1):l=">="+n+"."+i+"."+s+" <"+n+"."+(+i+1)+".0":l=">="+n+"."+i+"."+s+" <"+(+n+1)+".0.0"),w("caret return",l),l})}function ra(e,t){return w("replaceXRanges",e,t),e.split(/\s+/).map(function(r){return oa(r,t)}).join(" ")}function oa(e,t){e=e.trim();var r=t.loose?g[a.XRANGELOOSE]:g[a.XRANGE];return e.replace(r,function(o,n,i,s,d,l){w("xRange",e,o,n,i,s,d,l);var y=O(i),A=y||O(s),b=A||O(d),T=b;return n==="="&&T&&(n=""),l=t.includePrerelease?"-0":"",y?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&T?(A&&(s=0),d=0,n===">"?(n=">=",A?(i=+i+1,s=0,d=0):(s=+s+1,d=0)):n==="<="&&(n="<",A?i=+i+1:s=+s+1),o=n+i+"."+s+"."+d+l):A?o=">="+i+".0.0"+l+" <"+(+i+1)+".0.0"+l:b&&(o=">="+i+"."+s+".0"+l+" <"+i+"."+(+s+1)+".0"+l),w("xRange return",o),o})}function na(e,t){return w("replaceStars",e,t),e.trim().replace(g[a.STAR],"")}function ia(e,t,r,o,n,i,s,d,l,y,A,b,T){return O(r)?t="":O(o)?t=">="+r+".0.0":O(n)?t=">="+r+"."+o+".0":t=">="+t,O(l)?d="":O(y)?d="<"+(+l+1)+".0.0":O(A)?d="<"+l+"."+(+y+1)+".0":b?d="<="+l+"."+y+"."+A+"-"+b:d="<="+d,(t+" "+d).trim()}I.prototype.test=function(e){if(!e)return!1;if(typeof e=="string")try{e=new m(e,this.options)}catch{return!1}for(var t=0;t<this.set.length;t++)if(aa(this.set[t],e,this.options))return!0;return!1};function aa(e,t,r){for(var o=0;o<e.length;o++)if(!e[o].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(o=0;o<e.length;o++)if(w(e[o].semver),e[o].semver!==Ae&&e[o].semver.prerelease.length>0){var n=e[o].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}u.satisfies=nt;function nt(e,t,r){try{t=new I(t,r)}catch{return!1}return t.test(e)}u.maxSatisfying=sa;function sa(e,t,r){var o=null,n=null;try{var i=new I(t,r)}catch{return null}return e.forEach(function(s){i.test(s)&&(!o||n.compare(s)===-1)&&(o=s,n=new m(o,r))}),o}u.minSatisfying=ca;function ca(e,t,r){var o=null,n=null;try{var i=new I(t,r)}catch{return null}return e.forEach(function(s){i.test(s)&&(!o||n.compare(s)===1)&&(o=s,n=new m(o,r))}),o}u.minVersion=pa;function pa(e,t){e=new I(e,t);var r=new m("0.0.0");if(e.test(r)||(r=new m("0.0.0-0"),e.test(r)))return r;r=null;for(var o=0;o<e.set.length;++o){var n=e.set[o];n.forEach(function(i){var s=new m(i.semver.version);switch(i.operator){case">":s.prerelease.length===0?s.patch++:s.prerelease.push(0),s.raw=s.format();case"":case">=":(!r||Me(r,s))&&(r=s);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+i.operator)}})}return r&&e.test(r)?r:null}u.validRange=da;function da(e,t){try{return new I(e,t).range||"*"}catch{return null}}u.ltr=la;function la(e,t,r){return Qt(e,t,"<",r)}u.gtr=ua;function ua(e,t,r){return Qt(e,t,">",r)}u.outside=Qt;function Qt(e,t,r,o){e=new m(e,o),t=new I(t,o);var n,i,s,d,l;switch(r){case">":n=Me,i=Zt,s=rt,d=">",l=">=";break;case"<":n=rt,i=Yt,s=Me,d="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(nt(e,t,o))return!1;for(var y=0;y<t.set.length;++y){var A=t.set[y],b=null,T=null;if(A.forEach(function(k){k.semver===Ae&&(k=new J(">=0.0.0")),b=b||k,T=T||k,n(k.semver,b.semver,o)?b=k:s(k.semver,T.semver,o)&&(T=k)}),b.operator===d||b.operator===l||(!T.operator||T.operator===d)&&i(e,T.semver))return!1;if(T.operator===l&&s(e,T.semver))return!1}return!0}u.prerelease=ma;function ma(e,t){var r=le(e,t);return r&&r.prerelease.length?r.prerelease:null}u.intersects=fa;function fa(e,t,r){return e=new I(e,r),t=new I(t,r),e.intersects(t)}u.coerce=ha;function ha(e,t){if(e instanceof m)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};var r=null;if(!t.rtl)r=e.match(g[a.COERCE]);else{for(var o;(o=g[a.COERCERTL].exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||o.index+o[0].length!==r.index+r[0].length)&&(r=o),g[a.COERCERTL].lastIndex=o.index+o[1].length+o[2].length;g[a.COERCERTL].lastIndex=-1}return r===null?null:le(r[2]+"."+(r[3]||"0")+"."+(r[4]||"0"),t)}});var es={};Nn(es,{handleError:()=>bn,main:()=>An,run:()=>vn});module.exports=_n(es);var Re=require("@medplum/core"),Be=require("commander"),Sn=H(require("dotenv"));var B=require("@medplum/core"),zr=require("child_process"),qr=require("http"),Yr=require("os");var gr=require("@medplum/core");var hr=require("@medplum/core"),z=require("fs"),yr=require("os"),Pt=require("path"),j=class extends hr.ClientStorage{constructor(t){super(),this.dirName=(0,Pt.resolve)((0,yr.homedir)(),".medplum"),this.fileName=(0,Pt.resolve)(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((0,z.existsSync)(this.fileName))return JSON.parse((0,z.readFileSync)(this.fileName,"utf8"))}writeFile(t){(0,z.existsSync)(this.dirName)||(0,z.mkdirSync)(this.dirName),(0,z.writeFileSync)(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function S(e,t=!0){let r=e.profile??"default",o=new j(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:s,accessToken:d,tokenUrl:l,authorizeUrl:y,clientId:A,clientSecret:b}=Dn(e,o),T=e.fetch??fetch,k=new gr.MedplumClient({fetch:T,baseUrl:i,tokenUrl:l,fhirUrlPath:s,authorizeUrl:y,storage:o,onUnauthenticated:kn,verbose:e.verbose});return t&&(d?k.setAccessToken(d):A&&b&&(k.setBasicAuth(A,b),n?.authType!=="basic"&&await k.startClientLogin(A,b))),k}function Dn(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,i=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,s=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,d=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,l=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,y=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:i,tokenUrl:s,authorizeUrl:d,clientId:l,clientSecret:y}}function kn(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var Ge=require("commander");function h(e){return new Ge.Command(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 Ge.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}var pe=require("@medplum/core");var wr=require("buffer");var K=new TextEncoder,N=new TextDecoder,ps=2**32;function F(...e){let t=e.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}var L=e=>wr.Buffer.from(e).toString("base64url");var se=class extends Error{constructor(r){super(r);v(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}static get code(){return"ERR_JOSE_GENERIC"}};var E=class extends se{constructor(){super(...arguments);v(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var M=class extends se{constructor(){super(...arguments);v(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},ne=class extends se{constructor(){super(...arguments);v(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var Sr,Ar,Rt=class extends(Ar=se,Sr=Symbol.asyncIterator,Ar){constructor(){super(...arguments);v(this,Sr);v(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");v(this,"message","multiple matching keys found in the JSON Web Key Set")}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};var br=H(require("util"),1),W=e=>br.types.isKeyObject(e);var vr=H(require("crypto"),1),Cr=H(require("util"),1),Ln=vr.webcrypto,Ir=Ln,_=e=>Cr.types.isCryptoKey(e);function Y(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function je(e,t){return e.name===t}function xt(e){return parseInt(e.name.slice(4),10)}function Mn(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Wn(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 Pr(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!je(e.algorithm,"HMAC"))throw Y("HMAC");let o=parseInt(t.slice(2),10);if(xt(e.algorithm.hash)!==o)throw Y(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!je(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Y("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(xt(e.algorithm.hash)!==o)throw Y(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!je(e.algorithm,"RSA-PSS"))throw Y("RSA-PSS");let o=parseInt(t.slice(2),10);if(xt(e.algorithm.hash)!==o)throw Y(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw Y("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!je(e.algorithm,"ECDSA"))throw Y("ECDSA");let o=Mn(t);if(e.algorithm.namedCurve!==o)throw Y(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Wn(e,r)}function Rr(e,t,...r){if(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 U=(e,...t)=>Rr("Key must be ",e,...t);function Ot(e,t,...r){return Rr(`Key for the ${e} algorithm must be `,t,...r)}var Nt=e=>W(e)||_(e),C=["KeyObject"];(globalThis.CryptoKey||Ir?.CryptoKey)&&C.push("CryptoKey");var Bn=(...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 i of n){if(r.has(i))return!1;r.add(i)}}return!0},he=Bn;function Gn(e){return typeof e=="object"&&e!==null}function x(e){if(!Gn(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var Ve=require("crypto"),Or=require("util");var xr=require("crypto");var jn=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 E("Unsupported key curve for this operation")}},Vn=(e,t)=>{let r;if(_(e))r=xr.KeyObject.from(e);else if(W(e))r=e;else throw new TypeError(U(e,...C));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:jn(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},_t=Vn;var Cc=(0,Or.promisify)(Ve.generateKeyPair);var _r=require("util"),Dt=require("crypto");var Wc=(0,_r.promisify)(Dt.pbkdf2);var Oe=require("crypto"),Dr=require("util");var Xe=(e,t)=>{let{modulusLength:r}=e.asymmetricKeyDetails;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};var Xc=(0,Dr.deprecate)(()=>Oe.constants.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var qn=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Nt(t))throw new TypeError(Ot(e,t,...C,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${C.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Yn=(e,t,r)=>{if(!Nt(t))throw new TypeError(Ot(e,t,...C));if(t.type==="secret")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},Zn=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?qn(e,t):Yn(e,t,r)},_e=Zn;function ni(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(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let s of o.crit){if(!i.has(s))throw new E(`Extension Header Parameter "${s}" is not recognized`);if(n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i.get(s)&&o[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(o.crit)}var ye=ni;var pi=Symbol();var Mt=H(require("crypto"),1),Mr=require("util");function ze(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 E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Ht=require("crypto");var di={padding:Ht.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ht.constants.RSA_PSS_SALTLEN_DIGEST},li=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function qe(e,t){switch(e){case"EdDSA":if(!["ed25519","ed448"].includes(t.asymmetricKeyType))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");return t;case"RS256":case"RS384":case"RS512":if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return Xe(t,e),t;case"PS256":case"PS384":case"PS512":if(t.asymmetricKeyType==="rsa-pss"){let{hashAlgorithm:r,mgf1HashAlgorithm:o,saltLength:n}=t.asymmetricKeyDetails,i=parseInt(e.slice(-3),10);if(r!==void 0&&(r!==`sha${i}`||o!==r))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(n!==void 0&&n>i>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");return Xe(t,e),{key:t,...di};case"ES256":case"ES256K":case"ES384":case"ES512":{if(t.asymmetricKeyType!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let r=_t(t),o=li.get(e);if(r!==o)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${o}, got ${r}`);return{dsaEncoding:"ieee-p1363",key:t}}default:throw new E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Ze=H(require("crypto"),1),Lr=require("util");function Kt(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var De=require("crypto");function Ye(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(U(t,...C));return(0,De.createSecretKey)(t)}if(t instanceof De.KeyObject)return t;if(_(t))return Pr(t,e,r),De.KeyObject.from(t);throw new TypeError(U(t,...C,"Uint8Array"))}var ui=(0,Lr.promisify)(Ze.sign),mi=async(e,t,r)=>{let o=Ye(e,t,"sign");if(e.startsWith("HS")){let n=Ze.createHmac(Kt(e),o);return n.update(r),n.digest()}return ui(ze(e),r,qe(e,o))},Lt=mi;var Dl=(0,Mr.promisify)(Mt.verify);var Z=e=>Math.floor(e.getTime()/1e3);var hi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ke=e=>{let t=hi.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 ge=class{constructor(t){v(this,"_payload");v(this,"_protectedHeader");v(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 M("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!he(this._protectedHeader,this._unprotectedHeader))throw new M("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=ye(M,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),i=!0;if(n.has("b64")&&(i=this._protectedHeader.b64,typeof i!="boolean"))throw new M('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new M('JWS "alg" (Algorithm) Header Parameter missing or invalid');_e(s,t,"sign");let d=this._payload;i&&(d=K.encode(L(d)));let l;this._protectedHeader?l=K.encode(L(JSON.stringify(this._protectedHeader))):l=K.encode("");let y=F(l,K.encode("."),d),A=await Lt(s,t,y),b={signature:L(A),payload:""};return i&&(b.payload=N.decode(d)),this._unprotectedHeader&&(b.header=this._unprotectedHeader),this._protectedHeader&&(b.protected=N.decode(l)),b}};var He=class{constructor(t){v(this,"_flattened");this._flattened=new ge(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 ce(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var we=class{constructor(t={}){v(this,"_payload");if(!x(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:ce("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:ce("setNotBefore",Z(t))}:this._payload={...this._payload,nbf:Z(new Date)+ke(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:ce("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:ce("setExpirationTime",Z(t))}:this._payload={...this._payload,exp:Z(new Date)+ke(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Z(new Date)}:t instanceof Date?this._payload={...this._payload,iat:ce("setIssuedAt",Z(t))}:typeof t=="string"?this._payload={...this._payload,iat:ce("setIssuedAt",Z(new Date)+ke(t))}:this._payload={...this._payload,iat:ce("setIssuedAt",t)},this}};var Ke=class extends we{constructor(){super(...arguments);v(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new He(K.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 ne("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var bi;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(bi="jose/v5.4.1");var Wt=require("crypto"),Jr=require("util");var Jm=(0,Jr.promisify)(Wt.generateKeyPair);var Ee=require("crypto"),ie=require("fs"),Q=require("path"),$r=require("tar");function ee(e){console.log(JSON.stringify(e,null,2))}async function Ut(e,t,r){let o=t.source,n=Qe(o);if(!n)return;console.log("Saving source code...");let i=await e.createAttachment(n,(0,Q.basename)(o),Ri(o));console.log("Updating bot...");let s=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+s.meta?.versionId)}async function Jt(e,t,r){let o=t.dist??t.source,n=Qe(o);if(!n)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,Q.basename)(o)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}async function $t(e,t,r,o,n,i,s){let d={name:t,description:"",runtimeVersion:i},l=await e.post("admin/projects/"+r+"/bot",d),y=await e.readResource("Bot",l.id),A={name:t,id:l.id,source:o,dist:n};await Ut(e,A,y),await Jt(e,A,y),console.log(`Success! Bot created: ${y.id}`),s&&Ii(A)}function Fr(e){let t=new RegExp("^"+Pi(e).replace(/\\\*/g,".*")+"$"),r=V()?.bots?.filter(o=>t.test(o.name));return r||[]}function te(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 R(e,t){(0,ie.writeFileSync)((0,Q.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function V(e,t){let r=te(e,t),o=Qe(r);if(o)return JSON.parse(o)}function Br(e){let t=Qe(te(e,{server:!0}));if(t)return JSON.parse(t)}function Qe(e){let t=(0,Q.resolve)(e);return(0,ie.existsSync)(t)?(0,ie.readFileSync)(t,"utf8"):""}function Ii(e){let t=V()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ie.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Pi(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Gr(e){let o=0,n=0;return(0,$r.extract)({cwd:e,filter:(i,s)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=s.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Ft(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function Ri(e){let t=(0,Q.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?pe.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?pe.ContentType.TYPESCRIPT:pe.ContentType.TEXT}function et(e,t){let r=new j(e),o={name:e,...t};return r.setObject("options",o),o}function jr(e){return new j(e).getObject("options")}async function Vr(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},i=(0,pe.encodeBase64)(JSON.stringify(r)),s=(0,pe.encodeBase64)(JSON.stringify(n)),d=`${i}.${s}`,l=(0,Ee.createHmac)("sha256",t.clientSecret).update(d).digest("base64url"),y=`${d}.${l}`;await e.startJwtBearerLogin(t.clientId,y,t.scope??"")}async function Xr(e,t){let r=(0,Ee.createPrivateKey)((0,ie.readFileSync)((0,Q.resolve)(t.privateKeyPath))),o=await new Ke({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,Ee.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var Zr=B.MEDPLUM_CLI_CLIENT_ID,Qr="http://localhost:9615",Bt=h("login"),Gt=h("whoami"),jt=h("token");Bt.action(async e=>{let t=e.profile??"default",r=et(t,e),o=await S(e,!1);await Ti(o,r)});Gt.action(async e=>{let t=await S(e);Ni(t)});jt.action(async e=>{let t=await S(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 Ti(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 Vr(e,t);break;case"jwt-assertion":await Xr(e,t);break}}async function xi(e){let t=(0,qr.createServer)(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),i=n.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":B.ContentType.TEXT}),o.end("OK");return}if(n.pathname==="/"&&i)try{let s=await e.processCode(i,{clientId:Zr,redirectUri:Qr});o.writeHead(200,{"Content-Type":B.ContentType.TEXT}),o.end(`Signed in as ${(0,B.getDisplayString)(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":B.ContentType.TEXT}),o.end(`Error: ${(0,B.normalizeErrorString)(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":B.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function Oi(e){let t=(0,Yr.platform)(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}(0,zr.exec)(r,(o,n,i)=>{if(o)throw o;if(i)throw new Error("Could not open browser: "+i)})}function Ni(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 xi(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Zr),t.searchParams.set("redirect_uri",Qr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Oi(t.toString())}var Do=require("commander");var oe=require("@aws-sdk/client-cloudformation"),dt=require("@aws-sdk/client-cloudfront"),so=require("@aws-sdk/client-ecs"),co=require("@aws-sdk/client-s3"),ve=require("@aws-sdk/client-ssm"),lt=require("@aws-sdk/client-sts"),po=require("@medplum/core"),lo=H(require("node-fetch")),uo=require("fs"),mo=H(er());var io=H(require("readline")),it;function at(){it=io.default.createInterface({input:process.stdin,output:process.stdout})}function st(){it.close()}function c(e){it.write(e+`
3
- `)}function P(e){c(`
2
+ "use strict";var po=Object.create;var q=Object.defineProperty;var fo=Object.getOwnPropertyDescriptor;var go=Object.getOwnPropertyNames;var yo=Object.getPrototypeOf,ho=Object.prototype.hasOwnProperty;var wo=(e,t)=>{for(var o in t)q(e,o,{get:t[o],enumerable:!0})},je=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of go(t))!ho.call(e,i)&&i!==o&&q(e,i,{get:()=>t[i],enumerable:!(n=fo(t,i))||n.enumerable});return e};var x=(e,t,o)=>(o=e!=null?po(yo(e)):{},je(t||!e||!e.__esModule?q(o,"default",{value:e,enumerable:!0}):o,e)),So=e=>je(q({},"__esModule",{value:!0}),e);var fn={};wo(fn,{handleError:()=>mo,main:()=>lo,run:()=>uo});module.exports=So(fn);var W=require("@medplum/core"),J=require("commander"),co=x(require("dotenv"));var w=require("@medplum/core"),Ze=require("child_process"),Qe=require("http"),et=require("os");var _e=require("@medplum/core");var We=require("@medplum/core"),v=require("fs"),Ke=require("os"),Se=require("path"),C=class extends We.ClientStorage{constructor(t){super(),this.dirName=(0,Se.resolve)((0,Ke.homedir)(),".medplum"),this.fileName=(0,Se.resolve)(this.dirName,t+".json")}clear(){this.writeFile({})}getString(t){return this.readFile()?.[t]}setString(t,o){let n=this.readFile()??{};o?n[t]=o:delete n[t],this.writeFile(n)}getObject(t){let o=this.getString(t);return o?JSON.parse(o):void 0}setObject(t,o){this.setString(t,o?JSON.stringify(o):void 0)}readFile(){if((0,v.existsSync)(this.fileName))return JSON.parse((0,v.readFileSync)(this.fileName,"utf8"))}writeFile(t){(0,v.existsSync)(this.dirName)||(0,v.mkdirSync)(this.dirName),(0,v.writeFileSync)(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function d(e,t=!0){let o=e.profile??"default",n=new C(o),i=n.getObject("options");if(o!=="default"&&!i)throw new Error(`Profile "${o}" does not exist`);let{baseUrl:a,fhirUrlPath:s,accessToken:c,tokenUrl:m,authorizeUrl:p,clientId:y,clientSecret:T}=Co(e,n),z=e.fetch??fetch,G=new _e.MedplumClient({fetch:z,baseUrl:a,tokenUrl:m,fhirUrlPath:s,authorizeUrl:p,storage:n,onUnauthenticated:bo,verbose:e.verbose});return t&&(c?G.setAccessToken(c):y&&T&&(G.setBasicAuth(y,T),i?.authType!=="basic"&&await G.startClientLogin(y,T))),G}function Co(e,t){let o=t.getObject("options"),n=e.baseUrl??o?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",i=e.fhirUrlPath??o?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,a=e.accessToken??o?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,s=e.tokenUrl??o?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??o?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,m=e.clientId??o?.clientId??process.env.MEDPLUM_CLIENT_ID,p=e.clientSecret??o?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:n,fhirUrlPath:i,accessToken:a,tokenUrl:s,authorizeUrl:c,clientId:m,clientSecret:p}}function bo(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var X=require("commander");function l(e){return new X.Command(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 X.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}var D=require("@medplum/core"),Ve=require("jose"),U=require("crypto"),E=require("fs"),P=require("path"),He=require("tar");function k(e){console.log(JSON.stringify(e,null,2))}async function Ce(e,t,o){let n=t.source,i=Y(n);if(!i)return;console.log("Saving source code...");let a=await e.createAttachment(i,(0,P.basename)(n),ko(n));console.log("Updating bot...");let s=await e.updateResource({...o,sourceCode:a});console.log("Success! New bot version: "+s.meta?.versionId)}async function be(e,t,o){let n=t.dist??t.source,i=Y(n);if(!i)return;console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",o.id,"$deploy"),{code:i,filename:(0,P.basename)(n)});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}async function ve(e,t,o,n,i,a,s){let c={name:t,description:"",runtimeVersion:a},m=await e.post("admin/projects/"+o+"/bot",c),p=await e.readResource("Bot",m.id),y={name:t,id:m.id,source:n,dist:i};await Ce(e,y,p),await be(e,y,p),console.log(`Success! Bot created: ${p.id}`),s&&vo(y)}function Je(e){let t=new RegExp("^"+Po(e).replace(/\\\*/g,".*")+"$"),o=b()?.bots?.filter(n=>t.test(n.name));return o||[]}function A(e,t){if(t?.file)return t.file;let o=["medplum"];return e&&o.push(e),o.push("config"),t?.server&&o.push("server"),o.push("json"),o.join(".")}function f(e,t){(0,E.writeFileSync)((0,P.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function b(e,t){let o=A(e,t),n=Y(o);if(n)return JSON.parse(n)}function ze(e){let t=Y(A(e,{server:!0}));if(t)return JSON.parse(t)}function Y(e){let t=(0,P.resolve)(e);return(0,E.existsSync)(t)?(0,E.readFileSync)(t,"utf8"):""}function vo(e){let t=b()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,E.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Po(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Ge(e){let n=0,i=0;return(0,He.extract)({cwd:e,filter:(a,s)=>{if(n++,n>100)throw new Error("Tar extractor reached max number of files");if(i+=s.size,i>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Pe(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function ko(e){let t=(0,P.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?D.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?D.ContentType.TYPESCRIPT:D.ContentType.TEXT}function Z(e,t){let o=new C(e),n={name:e,...t};return o.setObject("options",n),n}function qe(e){return new C(e).getObject("options")}async function Xe(e,t){let o={typ:"JWT",alg:"HS256"},n=Math.floor(Date.now()/1e3),i={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:n,iat:n,exp:n+604800},a=(0,D.encodeBase64)(JSON.stringify(o)),s=(0,D.encodeBase64)(JSON.stringify(i)),c=`${a}.${s}`,m=(0,U.createHmac)("sha256",t.clientSecret).update(c).digest("base64url"),p=`${c}.${m}`;await e.startJwtBearerLogin(t.clientId,p,t.scope??"")}async function Ye(e,t){let o=(0,U.createPrivateKey)((0,E.readFileSync)((0,P.resolve)(t.privateKeyPath))),n=await new Ve.SignJWT({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,U.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(o);await e.startJwtAssertionLogin(n)}var tt=w.MEDPLUM_CLI_CLIENT_ID,ot="http://localhost:9615",ke=l("login"),Ae=l("whoami"),Ie=l("token");ke.action(async e=>{let t=e.profile??"default",o=Z(t,e),n=await d(e,!1);await Ao(n,o)});Ae.action(async e=>{let t=await d(e);Mo(t)});Ie.action(async e=>{let t=await d(e);await t.getProfileAsync();let o=t.getAccessToken();if(!o)throw new Error("Not logged in");console.log("Access token:"),console.log(),console.log(o)});async function Ao(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await To(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 Xe(e,t);break;case"jwt-assertion":await Ye(e,t);break}}async function Io(e){let t=(0,Qe.createServer)(async(o,n)=>{let i=new URL(o.url,"http://localhost:9615"),a=i.searchParams.get("code");if(o.method==="OPTIONS"){n.writeHead(200,{Allow:"GET, POST","Content-Type":w.ContentType.TEXT}),n.end("OK");return}if(i.pathname==="/"&&a)try{let s=await e.processCode(a,{clientId:tt,redirectUri:ot});n.writeHead(200,{"Content-Type":w.ContentType.TEXT}),n.end(`Signed in as ${(0,w.getDisplayString)(s)}. You may close this window.`)}catch(s){n.writeHead(400,{"Content-Type":w.ContentType.TEXT}),n.end(`Error: ${(0,w.normalizeErrorString)(s)}`)}finally{t.close()}else n.writeHead(404,{"Content-Type":w.ContentType.TEXT}),n.end("Not found")}).listen(9615)}async function Eo(e){let t=(0,et.platform)(),o;switch(t){case"openbsd":case"linux":o=`xdg-open '${e}'`;break;case"darwin":o=`open '${e}'`;break;case"win32":o=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}(0,Ze.exec)(o,(n,i,a)=>{if(n)throw n;if(a)throw new Error("Could not open browser: "+a)})}function Mo(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 To(e){await Io(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",tt),t.searchParams.set("redirect_uri",ot),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Eo(t.toString())}var xt=require("commander");var I=require("@aws-sdk/client-cloudformation"),re=require("@aws-sdk/client-cloudfront"),it=require("@aws-sdk/client-ecs"),at=require("@aws-sdk/client-s3"),B=require("@aws-sdk/client-ssm"),ie=require("@aws-sdk/client-sts"),st=require("@medplum/core"),ct=x(require("node-fetch")),lt=require("fs"),mt=x(require("semver"));var nt=x(require("readline")),Q;function ee(){Q=nt.default.createInterface({input:process.stdin,output:process.stdout})}function te(){Q.close()}function r(e){Q.write(e+`
3
+ `)}function u(e){r(`
4
4
  `+e+`
5
- `)}function D(e,t=""){return new Promise(r=>{it.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function ct(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await D(o)||r;if(t.includes(n))return n;c("Please choose one of the following options: "+t.join(", "))}}async function be(e,t,r){return parseInt(await ct(e,t.map(o=>o.toString()),r.toString()),10)}async function ue(e){return(await ct(e,["y","n"])).toLowerCase()==="y"}async function Ue(e){if(!await ue(e))throw c("Exiting..."),new Error("User cancelled")}var pt=new oe.CloudFormationClient({}),ya=new dt.CloudFrontClient({region:"us-east-1"}),mh=new so.ECSClient({}),Je=new co.S3Client({}),ga="medplum:environment";async function tr(){return(await pt.send(new oe.ListStacksCommand({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function Ce(e){let t=await tr();for(let r of t){let o=r.StackName,n=await rr(o);if(n?.tag===e)return n}}async function rr(e){let t={};if(await ao(pt,e,t),await pt.config.region()!=="us-east-1")try{await ao(new oe.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function ao(e,t,r){let o=new oe.DescribeStacksCommand({StackName:t}),i=(await e.send(o))?.Stacks?.[0],s=i?.Tags?.find(l=>l.Key===ga);if(!s)return;let d=await e.send(new oe.DescribeStackResourcesCommand({StackName:t}));if(d.StackResources){e===pt&&(r.stack=i,r.tag=s.Value);for(let l of d.StackResources)wa(l,r)}}function wa(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 ut(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: ${Ea(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 Ea(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function mt(e){let t=await ya.send(new dt.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function ft(e){let o=(await(await(0,lo.default)("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,i)=>mo.compare(i,n)),e?o.slice(0,o.indexOf(e)):o}async function ht(e,t,r){let o=new ve.SSMClient({region:e});for(let[n,i]of Object.entries(r)){let s=t+n,d=i.toString(),l=await Sa(o,s);l!==void 0&&l!==d&&(c(`Parameter "${s}" exists with different value.`),await Ue(`Do you want to overwrite "${s}"?`)),await Aa(o,s,d)}}async function Sa(e,t){let r=new ve.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Aa(e,t,r){let o=new ve.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function ae(e,t){if(console.log(`Config not found: ${e} (${te(e,t)})`),t){let o=Object.entries(t);if(o.length>0){console.log("Additional options:");for(let[n,i]of o)console.log(` ${n}: ${i}`)}}console.log();let r=(0,uo.readdirSync)(".",{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(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new lt.STSClient,r=new lt.GetCallerIdentityCommand({}),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",(0,po.normalizeErrorString)(t))}}async function fo(e){let t=await Ce(e);if(!t)throw await Ie(e),new Error(`Stack not found: ${e}`);ut(t)}var me=require("@aws-sdk/client-acm"),yt=require("@aws-sdk/client-cloudfront"),gt=require("@aws-sdk/client-sts"),yo=require("@medplum/core"),$e=require("crypto"),go=require("fs");var ba=e=>`${e}DomainName`,wo=e=>`${e}SslCertArn`;async function Eo(){let e={apiPort:8103,region:"us-east-1"};at(),P("MEDPLUM"),c("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),c(""),c("Most Medplum infrastructure is deployed using the AWS CDK."),c("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),c("This tool will help you create those resources."),c(""),c("Upon completion, this tool will:"),c(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),c(" 2. Optionally generate an AWS CloudFront signing key"),c(" 3. Optionally request SSL certificates from AWS Certificate Manager"),c(" 4. Optionally write server config settings to AWS Parameter Store"),c(""),c("The Medplum infra config file is an input to the Medplum CDK."),c("The Medplum CDK will create and manage the necessary AWS resources."),c(""),c("We will ask a series of questions to generate your infra config file."),c("Some questions have predefined options in [square brackets]."),c("Some questions have default values in (parentheses), which you can accept by pressing Enter."),c("Press Ctrl+C at any time to exit.");let t=await va(e.region);t||(c("It appears that you do not have AWS credentials configured."),c("AWS credentials are not strictly required, but will enable some additional features."),c("If you intend to use AWS credentials, please configure them now."),await Ue("Do you want to continue without AWS credentials?")),P("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await D("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),P("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await D("What is the config file name?",`medplum.${e.name}.config.json`);(0,go.existsSync)(r)&&(c("Config file already exists."),await Ue("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),R(r,e),P("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await D("Enter your AWS region:","us-east-1"),R(r,e),P("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await D("What is your AWS account number?",t),R(r,e),P("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await D("Enter your CloudFormation stack name?",o),R(r,e),P("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await D("Enter your base domain name:");R(r,e),P("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let n=await D("Enter your support email address:");P("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await D("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,R(r,e),P("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await D("Enter your web application domain name:","app."+e.domainName),R(r,e),P("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await D("Enter your storage domain name:","storage."+e.domainName),R(r,e),P("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await D("Enter your storage bucket name:",e.storageDomainName),R(r,e),P("MAX AVAILABILITY ZONES"),c("Medplum API servers can be deployed in multiple availability zones."),c("This provides redundancy and high availability."),c("However, it also increases the cost of the deployment."),c("If you want to use all availability zones, choose a large number such as 99."),c("If you want to restrict the number, for example to manage EIP limits,"),c("then choose a small number such as 2 or 3."),e.maxAzs=await be("Enter the maximum number of availability zones:",[2,3,99],2),P("DATABASE INSTANCES"),c("Medplum uses a relational database to store data."),c("Medplum can create a new RDS database as part of the CloudFormation stack,"),c("or can set up your own database and enter the database name, username, and password."),await ue("Do you want to create a new RDS database as part of the CloudFormation stack?")?(c("Medplum will create a new RDS database as part of the CloudFormation stack."),c(""),c("If you need high availability, you can choose multiple instances."),c("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await be("Enter the number of database instances:",[1,2],1)):(c("Medplum will not create a new RDS database."),c("Please create a new RDS database and enter the database name, username, and password."),c('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),R(r,e),P("SERVER INSTANCES"),c("Medplum uses AWS Fargate to run the API servers."),c("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),c("Fargate will automatically scale the number of servers up and down."),c("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await be("Enter the number of server instances:",[1,2,3,4,6,8],1),R(r,e),P("SERVER MEMORY"),c("You can choose the amount of memory for each server instance."),c("The default is 512 MB, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await be("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),R(r,e),P("SERVER CPU"),c("You can choose the amount of CPU for each server instance."),c("CPU is expressed as an integer using AWS CPU units"),c("The default is 256, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await be("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),R(r,e),P("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let i=(await ft())[0]??"latest";e.serverImage=await D("Enter the server image:",`medplum/medplum-server:${i}`),R(r,e),P("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let s=await Ra(e.region,e.stackName+"SigningKey");s?(e.signingKeyId=s.keyId,e.storagePublicKey=s.publicKey,R(r,e)):(c("Unable to generate signing key."),c("Please manually create a signing key and enter the key ID and public key in the config file."),c('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),P("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let d=await Ca(e.region);c("Found "+d.length+" certificate(s).");for(let{region:y,certName:A}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let b=await Ia(e,d,y,A);e[wo(A)]=b,R(r,e)}P("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${e.name}" path.`);let l={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(s&&(l.signingKeyId=s.keyId,l.signingKey=s.privateKey,l.signingKeyPassphrase=s.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await ue("Do you want to store these values in AWS Parameter Store?"))await ht(e.region,`/medplum/${e.name}/`,l);else{let y=te(e.name,{server:!0});R(y,l),c("Skipping AWS Parameter Store."),c(`Writing values to local config file: ${y}`),c("Please add these values to AWS Parameter Store manually.")}P("DONE!"),c("Medplum configuration complete."),c("You can now proceed to deploying the Medplum infrastructure with CDK."),c("Run:"),c(""),c(` npx cdk bootstrap -c config=${r}`),c(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?c(` npx cdk deploy -c config=${r}`):c(` npx cdk deploy -c config=${r} --all`),c(""),c("See Medplum documentation for more information:"),c(""),c(" https://www.medplum.com/docs/self-hosting/install-on-aws"),c(""),st()}async function va(e){try{let t=new gt.STSClient({region:e}),r=new gt.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Ca(e){let t=await ho(e);if(e!=="us-east-1"){let r=await ho("us-east-1");t.push(...r)}return t}async function ho(e){try{let t=new me.ACMClient({region:e}),r=new me.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Ia(e,t,r,o){let n=e[ba(o)],i=t.find(d=>d.CertificateArn?.includes(r)&&d.DomainName===n);if(i)return c(`Found existing certificate for "${n}" in "${r}.`),i.CertificateArn;if(c(`No existing certificate found for "${n}" in "${r}.`),!await ue("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${wo(o)}" setting.`),"TODO";let s=await Pa(r,n);return c("Certificate ARN: "+s),s}async function Pa(e,t){try{let r=await ct("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new me.ACMClient({region:e}),n=new me.RequestCertificateCommand({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 Ra(e,t){let r=(0,$e.randomUUID)(),o=(0,$e.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new yt.CloudFrontClient({region:e}).send(new yt.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,$e.randomUUID)(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",(0,yo.normalizeErrorString)(n));return}}async function So(){let e=await tr();for(let t of e){let r=t.StackName,o=await rr(r);o&&(ut(o),console.log(""))}}var Ao=require("@aws-sdk/client-s3"),G=require("@medplum/core"),bo=H(require("fast-glob")),or=H(require("node-fetch")),$=require("fs"),vo=require("os"),fe=require("path"),Co=require("stream/promises");async function Io(e,t){let r=V(e,t);if(!r)throw ae(e,t),new Error(`Config not found: ${e}`);let o=await Ce(e);if(!o)throw await Ie(e),new Error(`Stack not found: ${e}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${e}`);let i=t?.toVersion??"latest",s=await xa("@medplum/app",i);Po(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 Na(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await mt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Ta(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,or.default)(r)).json()}async function xa(e,t){let o=(await Ta(e,t)).dist.tarball,n=(0,$.mkdtempSync)((0,fe.join)((0,vo.tmpdir)(),"tarball-"));try{let i=await(0,or.default)(o),s=Gr(n);return await(0,Co.pipeline)(i.body,s),(0,fe.join)(n,"package","dist")}catch(i){throw(0,$.rmSync)(n,{recursive:!0,force:!0}),i}}function Po(e,t){for(let r of(0,$.readdirSync)(e,{withFileTypes:!0})){let o=(0,fe.join)(e,r.name);r.isDirectory()?Po(o,t):r.isFile()&&o.endsWith(".js")&&Oa(o,t)}}function Oa(e,t){let r=(0,$.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,$.writeFileSync)(e,r)}async function Na(e,t,r){let o=[["assets/**/*.css",G.ContentType.CSS,!0],["assets/**/*.css.map",G.ContentType.JSON,!0],["assets/**/*.js",G.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",G.ContentType.JSON,!0],["assets/**/*.txt",G.ContentType.TEXT,!0],["assets/**/*.ico",G.ContentType.FAVICON,!0],["img/**/*.png",G.ContentType.PNG,!0],["img/**/*.svg",G.ContentType.SVG,!0],["robots.txt",G.ContentType.TEXT,!0],["index.html",G.ContentType.HTML,!1]];for(let n of o)await _a({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function _a(e){let t=bo.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Da((0,fe.join)(e.rootDir,r),e)}async function Da(e,t){let r=(0,$.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(fe.sep).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 Je.send(new Ao.PutObjectCommand(n))}var wt=require("@aws-sdk/client-s3");async function To(e,t){if(!V(e,t))throw ae(e,t),new Error(`Config not found: ${e}`);let o=await Ce(e);if(!o)throw await Ie(e),new Error(`Stack not found: ${e}`);await Ro("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Ro("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Ro(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 i=t.PhysicalResourceId,s=o.PhysicalResourceId,d=await ka(i);if(Ka(d,i,s))throw new Error(`${e} bucket already has policy statement`);La(d,i,s),console.log(`${e} bucket policy:`),console.log(JSON.stringify(d,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Ha(i,d),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await mt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function ka(e){let t=await Je.send(new wt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Ha(e,t){await Je.send(new wt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Ka(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 La(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 xo(e,t){try{at();let r=V(e,t);if(!r)throw ae(e,t),new Error(`Config not found: ${e}`);let o=Br(e)??{};Ma(r,o),Ua(r,o),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${r.name}" path.`),c(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),(t.yes||await ue("Do you want to store these values in AWS Parameter Store?"))&&await ht(r.region,`/medplum/${r.name}/`,o)}finally{st()}}function Ma(e,t){Et(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Et(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Et(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Et(e.storageDomainName&&`https://${e.storageDomainName}/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Et(e,t,r){if(Wa(e,t))throw new Error(r)}function Wa(e,t){return e!==void 0&&t!==void 0&&e!==t}function Ua(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 No=require("child_process"),Pe=H(er());async function _o(e,t){let r=await S(t),o=V(e,t);if(!o)throw console.log(`Configuration file ${te(e)} not found`),ae(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),i=o.serverImage.slice(0,n),s=await Ja(r,o),d=await Oo(s);for(;d;){if(t.toVersion&&Pe.gt(d,t.toVersion)){console.log(`Skipping update to v${d}`);break}console.log(`Performing update to v${d}`),o.serverImage=`${i}:${d}`,$a(e,o),await r.startAsyncRequest("/admin/super/migrate"),d=await Oo(d)}}async function Ja(e,t){let r=t.serverImage.lastIndexOf(":"),o=t.serverImage.slice(r+1);if(o==="latest"){o=(await e.get("/healthcheck")).version;let i=o.indexOf("-");i>-1&&(o=o.slice(0,i))}return o}async function Oo(e,t){let r=await ft(e),o=r[0];return r.filter(n=>n===o||n===t||Pe.gte(n,Pe.inc(e,"minor"))).pop()}function $a(e,t){let r=te(e);R(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,No.spawnSync)(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 ko(){let e=new Do.Command("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Eo),e.command("list").description("List Medplum AWS CloudFormation stacks").action(So),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(fo),e.command("update-config").alias("deploy-config").description("Update the AWS Parameter Store config values").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.").option("--yes","Automatically confirm the update").action(xo),e.addCommand(h("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(_o)),e.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Io),e.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(To),e}var Ho=require("commander");var Ko=h("save"),Lo=h("deploy"),Mo=h("create"),Wo=new Ho.Command("bot").addCommand(Ko).addCommand(Lo).addCommand(Mo),nr=h("save-bot"),ir=h("deploy-bot"),ar=h("create-bot");Ko.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await St(r,e)});Lo.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await St(r,e,!0)});Mo.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(e,t,r,o,n)=>{let i=await S(n);await $t(i,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function St(e,t,r=!1){let o=Fr(t),n=[],i=[],s=0,d=0;for(let l of o)try{let y=await e.readResource("Bot",l.id);await Ut(e,l,y),s++,r&&(await Jt(e,l,y),d++)}catch(y){n.push(y),i.push(`${l.name} [${l.id}]`)}if(console.log(`Number of bots saved: ${s}`),console.log(`Number of bots deployed: ${d}`),console.log(`Number of errors: ${n.length}`),n.length)throw new Error(`${n.length} bot(s) had failures. Bots with failures:
5
+ `)}function g(e,t=""){return new Promise(o=>{Q.question(e+(t?" ("+t+")":"")+" ",n=>{o(n||t.toString())})})}async function oe(e,t,o=""){let n=e+" ["+t.map(i=>i===o?"("+i+")":i).join("|")+"]";for(;;){let i=await g(n)||o;if(t.includes(i))return i;r("Please choose one of the following options: "+t.join(", "))}}async function $(e,t,o){return parseInt(await oe(e,t.map(n=>n.toString()),o.toString()),10)}async function N(e){return(await oe(e,["y","n"])).toLowerCase()==="y"}async function K(e){if(!await N(e))throw r("Exiting..."),new Error("User cancelled")}var ne=new I.CloudFormationClient({}),xo=new re.CloudFrontClient({region:"us-east-1"}),$n=new it.ECSClient({}),_=new at.S3Client({}),Do="medplum:environment";async function Ee(){return(await ne.send(new I.ListStacksCommand({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function F(e){let t=await Ee();for(let o of t){let n=o.StackName,i=await Me(n);if(i?.tag===e)return i}}async function Me(e){let t={};if(await rt(ne,e,t),await ne.config.region()!=="us-east-1")try{await rt(new I.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function rt(e,t,o){let n=new I.DescribeStacksCommand({StackName:t}),a=(await e.send(n))?.Stacks?.[0],s=a?.Tags?.find(m=>m.Key===Do);if(!s)return;let c=await e.send(new I.DescribeStackResourcesCommand({StackName:t}));if(c.StackResources){e===ne&&(o.stack=a,o.tag=s.Value);for(let m of c.StackResources)No(m,o)}}function No(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 ae(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: ${Ro(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 Ro(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function se(e){let t=await xo.send(new re.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function ce(e){let n=(await(await(0,ct.default)("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(i=>i.tag_name.startsWith("v")?i.tag_name.slice(1):i.tag_name);return n.sort((i,a)=>mt.compare(a,i)),e?n.slice(0,n.indexOf(e)):n}async function le(e,t,o){let n=new B.SSMClient({region:e});for(let[i,a]of Object.entries(o)){let s=t+i,c=a.toString(),m=await Oo(n,s);m!==void 0&&m!==c&&(r(`Parameter "${s}" exists with different value.`),await K(`Do you want to overwrite "${s}"?`)),await Uo(n,s,c)}}async function Oo(e,t){let o=new B.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(o)).Parameter?.Value}catch(n){if(n.name==="ParameterNotFound")return;throw n}}async function Uo(e,t,o){let n=new B.PutParameterCommand({Name:t,Value:o,Type:"SecureString",Overwrite:!0});await e.send(n)}function M(e,t){if(console.log(`Config not found: ${e} (${A(e,t)})`),t){let n=Object.entries(t);if(n.length>0){console.log("Additional options:");for(let[i,a]of n)console.log(` ${i}: ${a}`)}}console.log();let o=(0,lt.readdirSync)(".",{withFileTypes:!0});if(o=o.filter(n=>n.isFile()&&n.name.startsWith("medplum.")&&n.name.endsWith(".json")).map(n=>n.name),o.length===0)console.log("No configs found");else{console.log("Available configs:");for(let n of o)console.log(` ${n.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${n})`)}}async function L(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new ie.STSClient,o=new ie.GetCallerIdentityCommand({}),n=await t.send(o),i=await t.config.region();console.log("AWS Region: ",i),console.log("AWS Account ID: ",n.Account),console.log("AWS Account ARN: ",n.Arn),console.log("AWS User ID: ",n.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",(0,st.normalizeErrorString)(t))}}async function dt(e){let t=await F(e);if(!t)throw await L(e),new Error(`Stack not found: ${e}`);ae(t)}var R=require("@aws-sdk/client-acm"),me=require("@aws-sdk/client-cloudfront"),de=require("@aws-sdk/client-sts"),pt=require("@medplum/core"),V=require("crypto"),ft=require("fs");var $o=e=>`${e}DomainName`,gt=e=>`${e}SslCertArn`;async function yt(){let e={apiPort:8103,region:"us-east-1"};ee(),u("MEDPLUM"),r("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),r(""),r("Most Medplum infrastructure is deployed using the AWS CDK."),r("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),r("This tool will help you create those resources."),r(""),r("Upon completion, this tool will:"),r(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),r(" 2. Optionally generate an AWS CloudFront signing key"),r(" 3. Optionally request SSL certificates from AWS Certificate Manager"),r(" 4. Optionally write server config settings to AWS Parameter Store"),r(""),r("The Medplum infra config file is an input to the Medplum CDK."),r("The Medplum CDK will create and manage the necessary AWS resources."),r(""),r("We will ask a series of questions to generate your infra config file."),r("Some questions have predefined options in [square brackets]."),r("Some questions have default values in (parentheses), which you can accept by pressing Enter."),r("Press Ctrl+C at any time to exit.");let t=await Bo(e.region);t||(r("It appears that you do not have AWS credentials configured."),r("AWS credentials are not strictly required, but will enable some additional features."),r("If you intend to use AWS credentials, please configure them now."),await K("Do you want to continue without AWS credentials?")),u("ENVIRONMENT NAME"),r('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),r("The environment name is used in multiple places:"),r(" 1. As part of config file names (i.e., medplum.demo.config.json)"),r(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),r(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await g("What is your environment name?","demo"),r('Using environment name "'+e.name+'"...'),u("CONFIG FILE"),r("Medplum Infrastructure will create a config file in the current directory.");let o=await g("What is the config file name?",`medplum.${e.name}.config.json`);(0,ft.existsSync)(o)&&(r("Config file already exists."),await K("Do you want to overwrite the config file?")),r('Using config file "'+o+'"...'),f(o,e),u("AWS REGION"),r("Most Medplum resources will be created in a single AWS region."),e.region=await g("Enter your AWS region:","us-east-1"),f(o,e),u("AWS ACCOUNT NUMBER"),r("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&r("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await g("What is your AWS account number?",t),f(o,e),u("STACK NAME"),r("Medplum will create a CloudFormation stack to manage AWS resources."),r("AWS CloudFormation stack names ");let n="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await g("Enter your CloudFormation stack name?",n),f(o,e),u("BASE DOMAIN NAME"),r("Please enter the base domain name for your Medplum deployment."),r(""),r("Medplum deploys multiple subdomains for various services."),r(""),r('For example, "api." for the REST API and "app." for the web application.'),r("The base domain name is the common suffix for all subdomains."),r(""),r('For example, if your base domain name is "example.com",'),r('then the REST API will be "api.example.com".'),r(""),r('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),r(""),r("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await g("Enter your base domain name:");f(o,e),u("SUPPORT EMAIL"),r("Medplum sends transactional emails to users."),r("For example, emails to new users or for password reset."),r("Medplum will use the support email address to send these emails."),r("Note that you must verify the support email address in SES.");let i=await g("Enter your support email address:");u("API DOMAIN NAME"),r("Medplum deploys a REST API for the backend services."),e.apiDomainName=await g("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,f(o,e),u("APP DOMAIN NAME"),r("Medplum deploys a web application for the user interface."),e.appDomainName=await g("Enter your web application domain name:","app."+e.domainName),f(o,e),u("STORAGE DOMAIN NAME"),r("Medplum deploys a storage service for file uploads."),e.storageDomainName=await g("Enter your storage domain name:","storage."+e.domainName),f(o,e),u("STORAGE BUCKET"),r("Medplum uses an S3 bucket to store binary content such as file uploads."),r("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await g("Enter your storage bucket name:",e.storageDomainName),f(o,e),u("MAX AVAILABILITY ZONES"),r("Medplum API servers can be deployed in multiple availability zones."),r("This provides redundancy and high availability."),r("However, it also increases the cost of the deployment."),r("If you want to use all availability zones, choose a large number such as 99."),r("If you want to restrict the number, for example to manage EIP limits,"),r("then choose a small number such as 2 or 3."),e.maxAzs=await $("Enter the maximum number of availability zones:",[2,3,99],2),u("DATABASE INSTANCES"),r("Medplum uses a relational database to store data."),r("Medplum can create a new RDS database as part of the CloudFormation stack,"),r("or can set up your own database and enter the database name, username, and password."),await N("Do you want to create a new RDS database as part of the CloudFormation stack?")?(r("Medplum will create a new RDS database as part of the CloudFormation stack."),r(""),r("If you need high availability, you can choose multiple instances."),r("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await $("Enter the number of database instances:",[1,2],1)):(r("Medplum will not create a new RDS database."),r("Please create a new RDS database and enter the database name, username, and password."),r('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),f(o,e),u("SERVER INSTANCES"),r("Medplum uses AWS Fargate to run the API servers."),r("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),r("Fargate will automatically scale the number of servers up and down."),r("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await $("Enter the number of server instances:",[1,2,3,4,6,8],1),f(o,e),u("SERVER MEMORY"),r("You can choose the amount of memory for each server instance."),r("The default is 512 MB, which is sufficient for getting started."),r("Note that only certain CPU units are compatible with memory units."),r('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await $("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),f(o,e),u("SERVER CPU"),r("You can choose the amount of CPU for each server instance."),r("CPU is expressed as an integer using AWS CPU units"),r("The default is 256, which is sufficient for getting started."),r("Note that only certain CPU units are compatible with memory units."),r('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await $("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),f(o,e),u("SERVER IMAGE"),r("Medplum uses Docker images for the API servers."),r("You can choose the image to use for the servers."),r("Docker images can be loaded from either Docker Hub or AWS ECR."),r("The default is the latest Medplum release.");let a=(await ce())[0]??"latest";e.serverImage=await g("Enter the server image:",`medplum/medplum-server:${a}`),f(o,e),u("SIGNING KEY"),r("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let s=await Wo(e.region,e.stackName+"SigningKey");s?(e.signingKeyId=s.keyId,e.storagePublicKey=s.publicKey,f(o,e)):(r("Unable to generate signing key."),r("Please manually create a signing key and enter the key ID and public key in the config file."),r('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),u("SSL CERTIFICATES"),r("Medplum will now check for existing SSL certificates for the subdomains.");let c=await Fo(e.region);r("Found "+c.length+" certificate(s).");for(let{region:p,certName:y}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){r("");let T=await Lo(e,c,p,y);e[gt(y)]=T,f(o,e)}u("AWS PARAMETER STORE"),r("Medplum uses AWS Parameter Store to store sensitive configuration values."),r("These values will be encrypted at rest."),r(`The values will be stored in the "/medplum/${e.name}" path.`);let m={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:i};if(s&&(m.signingKeyId=s.keyId,m.signingKey=s.privateKey,m.signingKeyPassphrase=s.passphrase),r(JSON.stringify({...m,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await N("Do you want to store these values in AWS Parameter Store?"))await le(e.region,`/medplum/${e.name}/`,m);else{let p=A(e.name,{server:!0});f(p,m),r("Skipping AWS Parameter Store."),r(`Writing values to local config file: ${p}`),r("Please add these values to AWS Parameter Store manually.")}u("DONE!"),r("Medplum configuration complete."),r("You can now proceed to deploying the Medplum infrastructure with CDK."),r("Run:"),r(""),r(` npx cdk bootstrap -c config=${o}`),r(` npx cdk synth -c config=${o}`),e.region==="us-east-1"?r(` npx cdk deploy -c config=${o}`):r(` npx cdk deploy -c config=${o} --all`),r(""),r("See Medplum documentation for more information:"),r(""),r(" https://www.medplum.com/docs/self-hosting/install-on-aws"),r(""),te()}async function Bo(e){try{let t=new de.STSClient({region:e}),o=new de.GetCallerIdentityCommand({});return(await t.send(o)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Fo(e){let t=await ut(e);if(e!=="us-east-1"){let o=await ut("us-east-1");t.push(...o)}return t}async function ut(e){try{let t=new R.ACMClient({region:e}),o=new R.ListCertificatesCommand({MaxItems:1e3});return(await t.send(o)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Lo(e,t,o,n){let i=e[$o(n)],a=t.find(c=>c.CertificateArn?.includes(o)&&c.DomainName===i);if(a)return r(`Found existing certificate for "${i}" in "${o}.`),a.CertificateArn;if(r(`No existing certificate found for "${i}" in "${o}.`),!await N("Do you want to request a new certificate?"))return r(`Please add your certificate ARN to the config file in the "${gt(n)}" setting.`),"TODO";let s=await jo(o,i);return r("Certificate ARN: "+s),s}async function jo(e,t){try{let o=await oe("Validate certificate using DNS or email validation?",["dns","email"],"dns"),n=new R.ACMClient({region:e}),i=new R.RequestCertificateCommand({DomainName:t,ValidationMethod:o.toUpperCase()});return(await n.send(i)).CertificateArn}catch(o){return console.log("Error: Unable to request certificate",o.message),"TODO"}}async function Wo(e,t){let o=(0,V.randomUUID)(),n=(0,V.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:o}});try{return{keyId:(await new me.CloudFrontClient({region:e}).send(new me.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,V.randomUUID)(),EncodedKey:n.publicKey}}))).PublicKey?.Id,publicKey:n.publicKey,privateKey:n.privateKey,passphrase:o}}catch(i){console.log("Error: Unable to create signing key: ",(0,pt.normalizeErrorString)(i));return}}async function ht(){let e=await Ee();for(let t of e){let o=t.StackName,n=await Me(o);n&&(ae(n),console.log(""))}}var wt=require("@aws-sdk/client-s3"),S=require("@medplum/core"),St=x(require("fast-glob")),Te=x(require("node-fetch")),h=require("fs"),Ct=require("os"),O=require("path"),bt=require("stream/promises");async function vt(e,t){let o=b(e,t);if(!o)throw M(e,t),new Error(`Config not found: ${e}`);let n=await F(e);if(!n)throw await L(e),new Error(`Stack not found: ${e}`);let i=n.appBucket;if(!i)throw new Error(`App bucket not found for stack ${e}`);let a=t?.toVersion??"latest",s=await _o("@medplum/app",a);Pt(s,{MEDPLUM_BASE_URL:o.baseUrl,MEDPLUM_CLIENT_ID:o.clientId??"",GOOGLE_CLIENT_ID:o.googleClientId??"",RECAPTCHA_SITE_KEY:o.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:o.registerEnabled?"true":"false"}),await Ho(s,i.PhysicalResourceId,t),n.appDistribution?.PhysicalResourceId&&!t.dryrun&&await se(n.appDistribution.PhysicalResourceId),console.log("Done")}async function Ko(e,t){let o=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Te.default)(o)).json()}async function _o(e,t){let n=(await Ko(e,t)).dist.tarball,i=(0,h.mkdtempSync)((0,O.join)((0,Ct.tmpdir)(),"tarball-"));try{let a=await(0,Te.default)(n),s=Ge(i);return await(0,bt.pipeline)(a.body,s),(0,O.join)(i,"package","dist")}catch(a){throw(0,h.rmSync)(i,{recursive:!0,force:!0}),a}}function Pt(e,t){for(let o of(0,h.readdirSync)(e,{withFileTypes:!0})){let n=(0,O.join)(e,o.name);o.isDirectory()?Pt(n,t):o.isFile()&&n.endsWith(".js")&&Vo(n,t)}}function Vo(e,t){let o=(0,h.readFileSync)(e,"utf-8");for(let[n,i]of Object.entries(t))o=o.replaceAll(`__${n}__`,i);(0,h.writeFileSync)(e,o)}async function Ho(e,t,o){let n=[["assets/**/*.css",S.ContentType.CSS,!0],["assets/**/*.css.map",S.ContentType.JSON,!0],["assets/**/*.js",S.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",S.ContentType.JSON,!0],["assets/**/*.txt",S.ContentType.TEXT,!0],["assets/**/*.ico",S.ContentType.FAVICON,!0],["img/**/*.png",S.ContentType.PNG,!0],["img/**/*.svg",S.ContentType.SVG,!0],["robots.txt",S.ContentType.TEXT,!0],["index.html",S.ContentType.HTML,!1]];for(let i of n)await Jo({rootDir:e,bucketName:t,fileNamePattern:i[0],contentType:i[1],cached:i[2],dryrun:o.dryrun})}async function Jo(e){let t=St.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let o of t)await zo((0,O.join)(e.rootDir,o),e)}async function zo(e,t){let o=(0,h.createReadStream)(e),n=e.substring(t.rootDir.length+1).split(O.sep).join("/"),i={Bucket:t.bucketName,Key:n,Body:o,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${n} to ${t.bucketName}...`),t.dryrun||await _.send(new wt.PutObjectCommand(i))}var ue=require("@aws-sdk/client-s3");async function At(e,t){if(!b(e,t))throw M(e,t),new Error(`Config not found: ${e}`);let n=await F(e);if(!n)throw await L(e),new Error(`Stack not found: ${e}`);await kt("App",n.appBucket,n.appDistribution,n.appOriginAccessIdentity,t),await kt("Storage",n.storageBucket,n.storageDistribution,n.storageOriginAccessIdentity,t),console.log("Done")}async function kt(e,t,o,n,i){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!o?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!n?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let a=t.PhysicalResourceId,s=n.PhysicalResourceId,c=await Go(a);if(Xo(c,a,s))throw new Error(`${e} bucket already has policy statement`);Yo(c,a,s),console.log(`${e} bucket policy:`),console.log(JSON.stringify(c,void 0,2)),i.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await qo(a,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await se(o.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Go(e){let t=await _.send(new ue.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function qo(e,t){await _.send(new ue.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Xo(e,t,o){return!!e?.Statement?.some(n=>n?.Effect==="Allow"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${o}`&&Array.isArray(n?.Action)&&n?.Action?.includes("s3:GetObject*")&&n?.Action?.includes("s3:GetBucket*")&&n?.Action?.includes("s3:List*")&&Array.isArray(n?.Resource)&&n?.Resource?.includes(`arn:aws:s3:::${t}`)&&n?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Yo(e,t,o){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 ${o}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}async function It(e,t){try{ee();let o=b(e,t);if(!o)throw M(e,t),new Error(`Config not found: ${e}`);let n=ze(e)??{};Zo(o,n),en(o,n),r("Medplum uses AWS Parameter Store to store sensitive configuration values."),r("These values will be encrypted at rest."),r(`The values will be stored in the "/medplum/${o.name}" path.`),r(JSON.stringify({...n,signingKey:"****",signingKeyPassphrase:"****"},null,2)),(t.yes||await N("Do you want to store these values in AWS Parameter Store?"))&&await le(o.region,`/medplum/${o.name}/`,n)}finally{te()}}function Zo(e,t){pe(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),pe(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),pe(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),pe(e.storageDomainName&&`https://${e.storageDomainName}/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function pe(e,t,o){if(Qo(e,t))throw new Error(o)}function Qo(e,t){return e!==void 0&&t!==void 0&&e!==t}function en(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 Mt=require("child_process"),j=x(require("semver"));async function Tt(e,t){let o=await d(t),n=b(e,t);if(!n)throw console.log(`Configuration file ${A(e)} not found`),M(e,t),new Error(`Config not found: ${e}`);let i=n.serverImage.lastIndexOf(":"),a=n.serverImage.slice(0,i),s=await tn(o,n),c=await Et(s);for(;c;){if(t.toVersion&&j.gt(c,t.toVersion)){console.log(`Skipping update to v${c}`);break}console.log(`Performing update to v${c}`),n.serverImage=`${a}:${c}`,on(e,n),await o.startAsyncRequest("/admin/super/migrate"),c=await Et(c)}}async function tn(e,t){let o=t.serverImage.lastIndexOf(":"),n=t.serverImage.slice(o+1);if(n==="latest"){n=(await e.get("/healthcheck")).version;let a=n.indexOf("-");a>-1&&(n=n.slice(0,a))}return n}async function Et(e,t){let o=await ce(e),n=o[0];return o.filter(i=>i===n||i===t||j.gte(i,j.inc(e,"minor"))).pop()}function on(e,t){let o=A(e);f(o,t);let n=`npx cdk deploy -c config=${o}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+n);let i=(0,Mt.spawnSync)(n,{stdio:"inherit"});if(i.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${i.status}): ${i.stderr}`);console.log(i.stdout)}function Dt(){let e=new xt.Command("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(yt),e.command("list").description("List Medplum AWS CloudFormation stacks").action(ht),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(dt),e.command("update-config").alias("deploy-config").description("Update the AWS Parameter Store config values").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.").option("--yes","Automatically confirm the update").action(It),e.addCommand(l("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(Tt)),e.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(vt),e.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(At),e}var Nt=require("commander");var Rt=l("save"),Ot=l("deploy"),Ut=l("create"),$t=new Nt.Command("bot").addCommand(Rt).addCommand(Ot).addCommand(Ut),xe=l("save-bot"),De=l("deploy-bot"),Ne=l("create-bot");Rt.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let o=await d(t);await fe(o,e)});Ot.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let o=await d(t);await fe(o,e,!0)});Ut.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(e,t,o,n,i)=>{let a=await d(i);await ve(a,e,t,o,n,i.runtimeVersion,!!i.writeConfig)});async function fe(e,t,o=!1){let n=Je(t),i=[],a=[],s=0,c=0;for(let m of n)try{let p=await e.readResource("Bot",m.id);await Ce(e,m,p),s++,o&&(await be(e,m,p),c++)}catch(p){i.push(p),a.push(`${m.name} [${m.id}]`)}if(console.log(`Number of bots saved: ${s}`),console.log(`Number of bots deployed: ${c}`),console.log(`Number of errors: ${i.length}`),i.length)throw new Error(`${i.length} bot(s) had failures. Bots with failures:
6
6
 
7
- ${i.join(`
8
- `)}`,{cause:n})}nr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await St(r,e)});ir.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await St(r,e,!0)});ar.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let i=await S(n);await $t(i,e,t,r,o)});var Jo=require("commander"),At=require("fs"),sr=require("path"),$o=require("readline");var Fo=h("export"),Bo=h("import"),Go=new Jo.Command("bulk").addCommand(Fo).addCommand(Bo);Fo.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,i=await S(e);(await i.bulkExport(t,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:d,url:l})=>{let y=new URL(l),A=await i.download(l),b=`${d}_${y.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",T=(0,sr.resolve)(n??"",b);(0,At.writeFile)(`${T}`,await A.text(),()=>{console.log(`${T} is created`)})})});Bo.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,i=(0,sr.resolve)(n??process.cwd(),e),s=await S(t);await Fa(i,parseInt(r,10),s,o)});async function Fa(e,t,r,o){let n=[],i=(0,At.createReadStream)(e),s=(0,$o.createInterface)({input:i});for await(let d of s){let l=Ba(d,o);n.push({resource:l,request:{method:"POST",url:l.resourceType}}),n.length%t===0&&(await Uo(n,r),n=[])}n.length>0&&await Uo(n,r)}async function Uo(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{ee(o.response)})}function Ba(e,t){let r=JSON.parse(e);return t?Ga(r):r}function Ga(e){return e.resourceType==="ExplanationOfBenefit"?ja(e):e}function ja(e){return e.provider||(e.provider=Ft()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Ft())}),e}var Ct=require("@medplum/core");var Vo=require("net"),Xo=require("@medplum/core"),vt=require("iconv-lite"),Zo=H(require("net"),1),jo=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var Va=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},bt=class extends Event{constructor(e){super("error"),this.error=e}},zo=class extends Event{constructor(){super("close")}},qo=class extends jo{constructor(e,t="utf-8"){super(),this.socket=e,this.encoding=t,this.chunks=[],this.messageQueue=[],e.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),i=(0,vt.decode)(n,this.encoding),s=Xo.Hl7Message.parse(i);this.dispatchEvent(new Va(this,s)),this.resetBuffer()}}catch(o){this.dispatchEvent(new bt(o))}}),e.on("error",r=>{this.resetBuffer(),this.dispatchEvent(new bt(r))}),e.on("end",()=>{this.close()}),this.addEventListener("message",r=>{let o=this.messageQueue.shift();if(!o){this.dispatchEvent(new bt(new Error(`Received a message when no pending messages were in the queue. Message: ${r.message}`)));return}o.resolve?.(r.message)})}sendImpl(e,t){this.messageQueue.push(t);let r=e.toString(),o=(0,vt.encode)(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(e){this.sendImpl(e,{message:e})}async sendAndWait(e){return new Promise((t,r)=>{let o={message:e,resolve:t,reject:r};this.sendImpl(e,o)})}close(){this.socket.end(),this.socket.destroy(),this.dispatchEvent(new zo)}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}},Yo=class extends jo{constructor(e){super(),this.options=e,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((e,t)=>{let r=(0,Vo.connect)({host:this.host,port:this.port,keepAlive:this.keepAlive},()=>{let o;this.connection=o=new qo(r,this.encoding),r.off("error",t),o.addEventListener("close",()=>this.dispatchEvent(new zo)),o.addEventListener("error",n=>this.dispatchEvent(new bt(n.error))),e(this.connection)});r.on("error",t)})}async send(e){return(await this.connect()).send(e)}async sendAndWait(e){return(await this.connect()).sendAndWait(e)}close(){this.connection&&(this.connection.close(),delete this.connection)}},Qo=class{constructor(e){this.handler=e}start(e,t){let r=Zo.default.createServer(o=>{let n=new qo(o,t);this.handler(n)});r.listen(e),this.server=r}async stop(){return new Promise((e,t)=>{if(!this.server){t(new Error("Stop was called but there is no server running"));return}this.server.close(r=>{if(r){t(r);return}e()}),this.server=void 0})}};var en=require("commander"),tn=require("fs");var Xa=h("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,o)=>{if(o.generateExample?r=qa():o.file&&(r=(0,tn.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new Yo({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await n.sendAndWait(Ct.Hl7Message.parse(r));console.log(i.toString().replaceAll("\r",`
9
- `))}finally{n.close()}}),za=h("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{new Qo(o=>{o.addEventListener("message",({message:n})=>{console.log(n.toString().replaceAll("\r",`
10
- `)),o.send(n.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),rn=new en.Command("hl7").addCommand(Xa).addCommand(za);function qa(){let e=(0,Ct.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
7
+ ${a.join(`
8
+ `)}`,{cause:i})}xe.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let o=await d(t);await fe(o,e)});De.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let o=await d(t);await fe(o,e,!0)});Ne.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,o,n,i)=>{let a=await d(i);await ve(a,e,t,o,n)});var Ft=require("commander"),ge=require("fs"),Re=require("path"),Lt=require("readline");var jt=l("export"),Wt=l("import"),Kt=new Ft.Command("bulk").addCommand(jt).addCommand(Wt);jt.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:o,since:n,targetDirectory:i}=e,a=await d(e);(await a.bulkExport(t,o,n,{pollStatusOnAccepted:!0})).output?.forEach(async({type:c,url:m})=>{let p=new URL(m),y=await a.download(m),T=`${c}_${p.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",z=(0,Re.resolve)(i??"",T);(0,ge.writeFile)(`${z}`,await y.text(),()=>{console.log(`${z} is created`)})})});Wt.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:o,addExtensionsForMissingValues:n,targetDirectory:i}=t,a=(0,Re.resolve)(i??process.cwd(),e),s=await d(t);await nn(a,parseInt(o,10),s,n)});async function nn(e,t,o,n){let i=[],a=(0,ge.createReadStream)(e),s=(0,Lt.createInterface)({input:a});for await(let c of s){let m=rn(c,n);i.push({resource:m,request:{method:"POST",url:m.resourceType}}),i.length%t===0&&(await Bt(i,o),i=[])}i.length>0&&await Bt(i,o)}async function Bt(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(n=>{k(n.response)})}function rn(e,t){let o=JSON.parse(e);return t?an(o):o}function an(e){return e.resourceType==="ExplanationOfBenefit"?sn(e):e}function sn(e){return e.provider||(e.provider=Pe()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Pe())}),e}var ye=require("@medplum/core"),he=require("@medplum/hl7"),_t=require("commander"),Vt=require("fs");var cn=l("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,o,n)=>{if(n.generateExample?o=mn():n.file&&(o=(0,Vt.readFileSync)(n.file,"utf8")),!o)throw new Error("Missing HL7 message body");let i=new he.Hl7Client({host:e,port:Number.parseInt(t,10),encoding:n.encoding});try{let a=await i.sendAndWait(ye.Hl7Message.parse(o));console.log(a.toString().replaceAll("\r",`
9
+ `))}finally{i.close()}}),ln=l("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{new he.Hl7Server(n=>{n.addEventListener("message",({message:i})=>{console.log(i.toString().replaceAll("\r",`
10
+ `)),n.send(i.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),Ht=new _t.Command("hl7").addCommand(cn).addCommand(ln);function mn(){let e=(0,ye.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
11
11
  EVN|A01|${e}||
12
12
  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|
13
- PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var on=require("commander"),nn=require("fs"),an=require("os"),sn=require("path");var cn=h("set"),pn=h("remove"),dn=h("list"),ln=h("describe"),un=new on.Command("profile").addCommand(cn).addCommand(pn).addCommand(dn).addCommand(ln);cn.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{et(e,t)});pn.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new j(e).setObject("options",void 0),console.log(`${e} profile removed`)});dn.description("List all profiles saved").action(async()=>{let e=(0,sn.resolve)((0,an.homedir)(),".medplum"),t=(0,nn.readdirSync)(e),r=[];t.forEach(o=>{let n=o.split(".")[0],s=new j(n).getObject("options");s&&r.push({profileName:n,profile:s})}),console.log(r)});ln.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=jr(e);console.log(t)});var It=require("commander");var mn=h("list"),fn=h("current"),hn=h("switch"),yn=h("invite"),gn=new It.Command("project").addCommand(mn).addCommand(fn).addCommand(hn).addCommand(yn);mn.description("List of current projects").action(async e=>{let t=await S(e);Ya(t)});function Ya(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
13
+ PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var Jt=require("commander"),zt=require("fs"),Gt=require("os"),qt=require("path");var Xt=l("set"),Yt=l("remove"),Zt=l("list"),Qt=l("describe"),eo=new Jt.Command("profile").addCommand(Xt).addCommand(Yt).addCommand(Zt).addCommand(Qt);Xt.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{Z(e,t)});Yt.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new C(e).setObject("options",void 0),console.log(`${e} profile removed`)});Zt.description("List all profiles saved").action(async()=>{let e=(0,qt.resolve)((0,Gt.homedir)(),".medplum"),t=(0,zt.readdirSync)(e),o=[];t.forEach(n=>{let i=n.split(".")[0],s=new C(i).getObject("options");s&&o.push({profileName:i,profile:s})}),console.log(o)});Qt.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=qe(e);console.log(t)});var we=require("commander");var to=l("list"),oo=l("current"),no=l("switch"),ro=l("invite"),io=new we.Command("project").addCommand(to).addCommand(oo).addCommand(no).addCommand(ro);to.description("List of current projects").action(async e=>{let t=await d(e);dn(t)});function dn(e){let o=e.getLogins().map(n=>`${n.project.display} (${n.project.reference})`).join(`
14
14
 
15
- `);console.log(r)}fn.description("Project you are currently on").action(async e=>{let r=(await S(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});hn.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await S(t);await Za(r,e)});yn.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 It.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await S(o),i=n.getActiveLogin();if(!i)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!i?.project?.reference)throw new Error("No current project to invite user to");let s=i.project.reference.split("/")[1],d={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await Qa(s,d,n)});async function Za(e,t){let o=e.getLogins().find(n=>n.project.reference?.includes(t));if(!o)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(o),console.log(`Switched to project ${t}
16
- `)}async function Qa(e,t,r){await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var wn=require("@medplum/core");var cr=h("delete"),pr=h("get"),dr=h("patch"),lr=h("post"),ur=h("put");cr.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await S(t);ee(await r.delete(Fe(r,e)))});pr.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await S(t),o=await r.get(Fe(r,e));t.asTransaction?ee((0,wn.convertToTransactionBundle)(o)):ee(o)});dr.arguments("<url> <body>").action(async(e,t,r)=>{let o=await S(r);ee(await o.patch(Fe(o,e),mr(t)))});lr.arguments("<url> <body>").action(async(e,t,r)=>{let o=await S(r);ee(await o.post(Fe(o,e),mr(t)))});ur.arguments("<url> <body>").action(async(e,t,r)=>{let o=await S(r);ee(await o.put(Fe(o,e),mr(t)))});function mr(e){if(e)try{return JSON.parse(e)}catch{return e}}function Fe(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function An(e){let t=new Be.Command("medplum").description("Command to access Medplum CLI");t.exitOverride(),t.version(Re.MEDPLUM_VERSION),t.addCommand(Bt),t.addCommand(Gt),t.addCommand(jt),t.addCommand(pr),t.addCommand(lr),t.addCommand(dr),t.addCommand(ur),t.addCommand(cr),t.addCommand(gn),t.addCommand(Go),t.addCommand(Wo),t.addCommand(nr),t.addCommand(ir),t.addCommand(ar),t.addCommand(un),t.addCommand(ko()),t.addCommand(rn);try{await t.parseAsync(e)}catch(r){bn(r)}}function bn(e){En(e);let t=e.cause;if(Array.isArray(t))for(let o of t)En(o);let r=1;e instanceof Be.CommanderError&&(r=e.exitCode),process.exit(r)}function En(e){e instanceof Be.CommanderError&&process.stderr.write(`${(0,Re.normalizeErrorString)(e)}
17
- `),process.stderr.write(`Error: ${(0,Re.normalizeErrorString)(e)}
18
- `)}async function vn(){Sn.default.config(),await An(process.argv)}require.main===module&&vn().catch(e=>{console.error("Unhandled error:",(0,Re.normalizeErrorString)(e)),process.exit(1)});0&&(module.exports={handleError,main,run});
15
+ `);console.log(o)}oo.description("Project you are currently on").action(async e=>{let o=(await d(e)).getActiveLogin();if(!o)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${o.project.display} (${o.project.reference})`)});no.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let o=await d(t);await un(o,e)});ro.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 we.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,o,n)=>{let i=await d(n),a=i.getActiveLogin();if(!a)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!a?.project?.reference)throw new Error("No current project to invite user to");let s=a.project.reference.split("/")[1],c={resourceType:n.role,firstName:e,lastName:t,email:o,sendEmail:!!n.sendEmail,admin:!!n.admin};await pn(s,c,i)});async function un(e,t){let n=e.getLogins().find(i=>i.project.reference?.includes(t));if(!n)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(n),console.log(`Switched to project ${t}
16
+ `)}async function pn(e,t,o){await o.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var ao=require("@medplum/core");var Oe=l("delete"),Ue=l("get"),$e=l("patch"),Be=l("post"),Fe=l("put");Oe.argument("<url>","Resource/$id").action(async(e,t)=>{let o=await d(t);k(await o.delete(H(o,e)))});Ue.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let o=await d(t),n=await o.get(H(o,e));t.asTransaction?k((0,ao.convertToTransactionBundle)(n)):k(n)});$e.arguments("<url> <body>").action(async(e,t,o)=>{let n=await d(o);k(await n.patch(H(n,e),Le(t)))});Be.arguments("<url> <body>").action(async(e,t,o)=>{let n=await d(o);k(await n.post(H(n,e),Le(t)))});Fe.arguments("<url> <body>").action(async(e,t,o)=>{let n=await d(o);k(await n.put(H(n,e),Le(t)))});function Le(e){if(e)try{return JSON.parse(e)}catch{return e}}function H(e,t){return["admin/","auth/","fhir/R4"].some(n=>t.startsWith(n))?t:e.fhirUrl(t).toString()}async function lo(e){let t=new J.Command("medplum").description("Command to access Medplum CLI");t.exitOverride(),t.version(W.MEDPLUM_VERSION),t.addCommand(ke),t.addCommand(Ae),t.addCommand(Ie),t.addCommand(Ue),t.addCommand(Be),t.addCommand($e),t.addCommand(Fe),t.addCommand(Oe),t.addCommand(io),t.addCommand(Kt),t.addCommand($t),t.addCommand(xe),t.addCommand(De),t.addCommand(Ne),t.addCommand(eo),t.addCommand(Dt()),t.addCommand(Ht);try{await t.parseAsync(e)}catch(o){mo(o)}}function mo(e){so(e);let t=e.cause;if(Array.isArray(t))for(let n of t)so(n);let o=1;e instanceof J.CommanderError&&(o=e.exitCode),process.exit(o)}function so(e){e instanceof J.CommanderError&&process.stderr.write(`${(0,W.normalizeErrorString)(e)}
17
+ `),process.stderr.write(`Error: ${(0,W.normalizeErrorString)(e)}
18
+ `)}async function uo(){co.default.config(),await lo(process.argv)}require.main===module&&uo().catch(e=>{console.error("Unhandled error:",(0,W.normalizeErrorString)(e)),process.exit(1)});0&&(module.exports={handleError,main,run});
19
19
  //# sourceMappingURL=index.cjs.map