@medplum/cli 3.1.6 → 3.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +9 -9
- package/dist/cjs/index.cjs.map +3 -3
- package/dist/esm/index.mjs +9 -9
- package/dist/esm/index.mjs.map +3 -3
- package/package.json +13 -12
package/dist/esm/index.mjs
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var wo=Object.create;var Ze=Object.defineProperty;var Eo=Object.getOwnPropertyDescriptor;var So=Object.getOwnPropertyNames;var Ao=Object.getPrototypeOf,bo=Object.prototype.hasOwnProperty;var Co=(e,t,r)=>t in e?Ze(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Mt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var vo=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Io=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of So(t))!bo.call(e,n)&&n!==r&&Ze(e,n,{get:()=>t[n],enumerable:!(o=Eo(t,n))||o.enumerable});return e};var Wt=(e,t,r)=>(r=e!=null?wo(Ao(e)):{},Io(t||!e||!e.__esModule?Ze(r,"default",{value:e,enumerable:!0}):r,e));var C=(e,t,r)=>Co(e,typeof t!="symbol"?t+"":t,r);var It=vo((u,br)=>{"use strict";u=br.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 Ae=256,Ke=Number.MAX_SAFE_INTEGER||9007199254740991,wt=16,ai=Ae-6,pe=u.re=[],g=u.safeRe=[],p=u.src=[],a=u.tokens={},Sr=0;function f(e){a[e]=Sr++}var St="[a-zA-Z0-9-]",Et=[["\\s",1],["\\d",Ae],[St,ai]];function Ce(e){for(var t=0;t<Et.length;t++){var r=Et[t][0],o=Et[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-]"+St+"*";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]=St+"+";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,"+wt+"})(?:\\.(\\d{1,"+wt+"}))?(?:\\.(\\d{1,"+wt+"}))?(?:$|[^\\d])";f("COERCERTL");pe[a.COERCERTL]=new RegExp(p[a.COERCE],"g");g[a.COERCERTL]=new RegExp(Ce(p[a.COERCE]),"g");f("LONETILDE");p[a.LONETILDE]="(?:~>?)";f("TILDETRIM");p[a.TILDETRIM]="(\\s*)"+p[a.LONETILDE]+"\\s+";pe[a.TILDETRIM]=new RegExp(p[a.TILDETRIM],"g");g[a.TILDETRIM]=new RegExp(Ce(p[a.TILDETRIM]),"g");var si="$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+";pe[a.CARETTRIM]=new RegExp(p[a.CARETTRIM],"g");g[a.CARETTRIM]=new RegExp(Ce(p[a.CARETTRIM]),"g");var ci="$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]+")";pe[a.COMPARATORTRIM]=new RegExp(p[a.COMPARATORTRIM],"g");g[a.COMPARATORTRIM]=new RegExp(Ce(p[a.COMPARATORTRIM]),"g");var pi="$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(B=0;B<Sr;B++)w(B,p[B]),pe[B]||(pe[B]=new RegExp(p[B]),g[B]=new RegExp(Ce(p[B])));var B;u.parse=oe;function oe(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof m)return e;if(typeof e!="string"||e.length>Ae)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=di;function di(e,t){var r=oe(e,t);return r?r.version:null}u.clean=li;function li(e,t){var r=oe(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>Ae)throw new TypeError("version is longer than "+Ae+" 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>Ke||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Ke||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Ke||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<Ke)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)),re(this.major,e.major)||re(this.minor,e.minor)||re(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 re(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 re(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=ui;function ui(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=mi;function mi(e,t){if(At(e,t))return null;var r=oe(e),o=oe(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=re;var wr=/^[0-9]+$/;function re(e,t){var r=wr.test(e),o=wr.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1}u.rcompareIdentifiers=fi;function fi(e,t){return re(t,e)}u.major=hi;function hi(e,t){return new m(e,t).major}u.minor=yi;function yi(e,t){return new m(e,t).minor}u.patch=gi;function gi(e,t){return new m(e,t).patch}u.compare=Y;function Y(e,t,r){return new m(e,r).compare(new m(t,r))}u.compareLoose=wi;function wi(e,t){return Y(e,t,!0)}u.compareBuild=Ei;function Ei(e,t,r){var o=new m(e,r),n=new m(t,r);return o.compare(n)||o.compareBuild(n)}u.rcompare=Si;function Si(e,t,r){return Y(t,e,r)}u.sort=Ai;function Ai(e,t){return e.sort(function(r,o){return u.compareBuild(r,o,t)})}u.rsort=bi;function bi(e,t){return e.sort(function(r,o){return u.compareBuild(o,r,t)})}u.gt=be;function be(e,t,r){return Y(e,t,r)>0}u.lt=Le;function Le(e,t,r){return Y(e,t,r)<0}u.eq=At;function At(e,t,r){return Y(e,t,r)===0}u.neq=Ar;function Ar(e,t,r){return Y(e,t,r)!==0}u.gte=bt;function bt(e,t,r){return Y(e,t,r)>=0}u.lte=Ct;function Ct(e,t,r){return Y(e,t,r)<=0}u.cmp=Me;function Me(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 At(e,r,o);case"!=":return Ar(e,r,o);case">":return be(e,r,o);case">=":return bt(e,r,o);case"<":return Le(e,r,o);case"<=":return Ct(e,r,o);default:throw new TypeError("Invalid operator: "+t)}}u.Comparator=U;function U(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof U){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof U))return new U(e,t);e=e.trim().split(/\s+/).join(" "),w("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===de?this.value="":this.value=this.operator+this.semver.version,w("comp",this)}var de={};U.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=de};U.prototype.toString=function(){return this.value};U.prototype.test=function(e){if(w("Comparator.test",e,this.options.loose),this.semver===de||e===de)return!0;if(typeof e=="string")try{e=new m(e,this.options)}catch{return!1}return Me(e,this.operator,this.semver,this.options)};U.prototype.intersects=function(e,t){if(!(e instanceof U))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),We(this.value,r,t));if(e.operator==="")return e.value===""?!0:(r=new I(this.value,t),We(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=Me(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),l=Me(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 U)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,_i),w("hyphen replace",e),e=e.replace(g[a.COMPARATORTRIM],pi),w("comparator trim",e,g[a.COMPARATORTRIM]),e=e.replace(g[a.TILDETRIM],si),e=e.replace(g[a.CARETTRIM],ci),e=e.split(/\s+/).join(" ");var o=t?g[a.COMPARATORLOOSE]:g[a.COMPARATOR],n=e.split(" ").map(function(i){return vi(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 U(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 Er(r,t)&&e.set.some(function(o){return Er(o,t)&&r.every(function(n){return o.every(function(i){return n.intersects(i,t)})})})})};function Er(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=Ci;function Ci(e,t){return new I(e,t).set.map(function(r){return r.map(function(o){return o.value}).join(" ").trim().split(" ")})}function vi(e,t){return w("comp",e,t),e=Ri(e,t),w("caret",e),e=Ii(e,t),w("tildes",e),e=xi(e,t),w("xrange",e),e=Ni(e,t),w("stars",e),e}function O(e){return!e||e.toLowerCase()==="x"||e==="*"}function Ii(e,t){return e.trim().split(/\s+/).map(function(r){return Pi(r,t)}).join(" ")}function Pi(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 Ri(e,t){return e.trim().split(/\s+/).map(function(r){return Ti(r,t)}).join(" ")}function Ti(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 xi(e,t){return w("replaceXRanges",e,t),e.split(/\s+/).map(function(r){return Oi(r,t)}).join(" ")}function Oi(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 Ni(e,t){return w("replaceStars",e,t),e.trim().replace(g[a.STAR],"")}function _i(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(Di(this.set[t],e,this.options))return!0;return!1};function Di(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!==de&&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=We;function We(e,t,r){try{t=new I(t,r)}catch{return!1}return t.test(e)}u.maxSatisfying=ki;function ki(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=Hi;function Hi(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=Ki;function Ki(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||be(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=Li;function Li(e,t){try{return new I(e,t).range||"*"}catch{return null}}u.ltr=Mi;function Mi(e,t,r){return vt(e,t,"<",r)}u.gtr=Wi;function Wi(e,t,r){return vt(e,t,">",r)}u.outside=vt;function vt(e,t,r,o){e=new m(e,o),t=new I(t,o);var n,i,s,d,l;switch(r){case">":n=be,i=Ct,s=Le,d=">",l=">=";break;case"<":n=Le,i=bt,s=be,d="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(We(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===de&&(k=new U(">=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=Ui;function Ui(e,t){var r=oe(e,t);return r&&r.prerelease.length?r.prerelease:null}u.intersects=Ji;function Ji(e,t,r){return e=new I(e,r),t=new I(t,r),e.intersects(t)}u.coerce=$i;function $i(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:oe(r[2]+"."+(r[3]||"0")+"."+(r[4]||"0"),t)}});import{MEDPLUM_VERSION as Ds,normalizeErrorString as Lt}from"@medplum/core";import{Command as ks,CommanderError as go}from"commander";import Hs from"dotenv";import{ContentType as He,getDisplayString as zn,MEDPLUM_CLI_CLIENT_ID as qn,normalizeErrorString as Yn}from"@medplum/core";import{exec as Zn}from"child_process";import{createServer as Qn}from"http";import{platform as ei}from"os";import{MedplumClient as No}from"@medplum/core";import{ClientStorage as Po}from"@medplum/core";import{existsSync as Ut,mkdirSync as Ro,readFileSync as To,writeFileSync as xo}from"fs";import{homedir as Oo}from"os";import{resolve as Jt}from"path";var $=class extends Po{constructor(t){super(),this.dirName=Jt(Oo(),".medplum"),this.fileName=Jt(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(Ut(this.fileName))return JSON.parse(To(this.fileName,"utf8"))}writeFile(t){Ut(this.dirName)||Ro(this.dirName),xo(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function S(e,t=!0){let r=e.profile??"default",o=new $(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:s,accessToken:d,tokenUrl:l,authorizeUrl:y,clientId:A,clientSecret:b}=_o(e,o),T=e.fetch??fetch,k=new No({fetch:T,baseUrl:i,tokenUrl:l,fhirUrlPath:s,authorizeUrl:y,storage:o,onUnauthenticated:Do,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 _o(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 Do(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{Command as ko,Option as Ho}from"commander";function h(e){return new ko(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 Ho("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}import{ContentType as pt,encodeBase64 as ar}from"@medplum/core";import{Buffer as Lo}from"buffer";var H=new TextEncoder,N=new TextDecoder,Qs=2**32;function J(...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 K=e=>Lo.from(e).toString("base64url");var ee=class extends Error{constructor(r){super(r);C(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 ee{constructor(){super(...arguments);C(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var L=class extends ee{constructor(){super(...arguments);C(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},Z=class extends ee{constructor(){super(...arguments);C(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var Ft,Bt,Qe=class extends(Bt=ee,Ft=Symbol.asyncIterator,Bt){constructor(){super(...arguments);C(this,Ft);C(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");C(this,"message","multiple matching keys found in the JSON Web Key Set")}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};import*as Gt from"util";var M=e=>Gt.types.isKeyObject(e);import*as jt from"crypto";import*as Vt from"util";var Wo=jt.webcrypto,Xt=Wo,_=e=>Vt.types.isCryptoKey(e);function V(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Re(e,t){return e.name===t}function tt(e){return parseInt(e.name.slice(4),10)}function Uo(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Jo(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 zt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Re(e.algorithm,"HMAC"))throw V("HMAC");let o=parseInt(t.slice(2),10);if(tt(e.algorithm.hash)!==o)throw V(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Re(e.algorithm,"RSASSA-PKCS1-v1_5"))throw V("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(tt(e.algorithm.hash)!==o)throw V(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Re(e.algorithm,"RSA-PSS"))throw V("RSA-PSS");let o=parseInt(t.slice(2),10);if(tt(e.algorithm.hash)!==o)throw V(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw V("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!Re(e.algorithm,"ECDSA"))throw V("ECDSA");let o=Uo(t);if(e.algorithm.namedCurve!==o)throw V(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Jo(e,r)}function qt(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 W=(e,...t)=>qt("Key must be ",e,...t);function rt(e,t,...r){return qt(`Key for the ${e} algorithm must be `,t,...r)}var ot=e=>M(e)||_(e),v=["KeyObject"];(globalThis.CryptoKey||Xt?.CryptoKey)&&v.push("CryptoKey");var jo=(...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},ie=jo;function Vo(e){return typeof e=="object"&&e!==null}function x(e){if(!Vo(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}import{diffieHellman as pp,generateKeyPair as Yo,KeyObject as dp}from"crypto";import{promisify as Zo}from"util";import{KeyObject as Xo}from"crypto";var zo=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")}},qo=(e,t)=>{let r;if(_(e))r=Xo.from(e);else if(M(e))r=e;else throw new TypeError(W(e,...v));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:zo(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},nt=qo;var Sp=Zo(Yo);import{promisify as tn}from"util";import{KeyObject as Rp,pbkdf2 as rn}from"crypto";var Mp=tn(rn);import{KeyObject as $p,publicEncrypt as Fp,constants as on,privateDecrypt as Bp}from"crypto";import{deprecate as nn}from"util";var Te=(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 Zp=nn(()=>on.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var an=(e,t)=>{if(!(t instanceof Uint8Array)){if(!ot(t))throw new TypeError(rt(e,t,...v,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${v.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},sn=(e,t,r)=>{if(!ot(t))throw new TypeError(rt(e,t,...v));if(t.type==="secret")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},cn=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?an(e,t):sn(e,t,r)},ge=cn;function fn(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 ae=fn;var En=Symbol();import*as ct from"crypto";import{promisify as Pn}from"util";function xe(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`)}}import{constants as rr}from"crypto";var Sn={padding:rr.RSA_PKCS1_PSS_PADDING,saltLength:rr.RSA_PSS_SALTLEN_DIGEST},An=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Oe(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 Te(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 Te(t,e),{key:t,...Sn};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=nt(t),o=An.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`)}}import*as _e from"crypto";import{promisify as Cn}from"util";function at(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`)}}import{KeyObject as or,createSecretKey as bn}from"crypto";function Ne(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(W(t,...v));return bn(t)}if(t instanceof or)return t;if(_(t))return zt(t,e,r),or.from(t);throw new TypeError(W(t,...v,"Uint8Array"))}var vn=Cn(_e.sign),In=async(e,t,r)=>{let o=Ne(e,t,"sign");if(e.startsWith("HS")){let n=_e.createHmac(at(e),o);return n.update(r),n.digest()}return vn(xe(e),r,Oe(e,o))},st=In;var Ju=Pn(ct.verify);var X=e=>Math.floor(e.getTime()/1e3);var Tn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,we=e=>{let t=Tn.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 se=class{constructor(t){C(this,"_payload");C(this,"_protectedHeader");C(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 L("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!ie(this._protectedHeader,this._unprotectedHeader))throw new L("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=ae(L,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),i=!0;if(n.has("b64")&&(i=this._protectedHeader.b64,typeof i!="boolean"))throw new L('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new L('JWS "alg" (Algorithm) Header Parameter missing or invalid');ge(s,t,"sign");let d=this._payload;i&&(d=H.encode(K(d)));let l;this._protectedHeader?l=H.encode(K(JSON.stringify(this._protectedHeader))):l=H.encode("");let y=J(l,H.encode("."),d),A=await st(s,t,y),b={signature:K(A),payload:""};return i&&(b.payload=N.decode(d)),this._unprotectedHeader&&(b.header=this._unprotectedHeader),this._protectedHeader&&(b.protected=N.decode(l)),b}};var Ee=class{constructor(t){C(this,"_flattened");this._flattened=new se(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 te(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var ce=class{constructor(t={}){C(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:te("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:te("setNotBefore",X(t))}:this._payload={...this._payload,nbf:X(new Date)+we(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:te("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:te("setExpirationTime",X(t))}:this._payload={...this._payload,exp:X(new Date)+we(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:X(new Date)}:t instanceof Date?this._payload={...this._payload,iat:te("setIssuedAt",X(t))}:typeof t=="string"?this._payload={...this._payload,iat:te("setIssuedAt",X(new Date)+we(t))}:this._payload={...this._payload,iat:te("setIssuedAt",t)},this}};var Se=class extends ce{constructor(){super(...arguments);C(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new Ee(H.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 Z("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var Hn;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Hn="jose/v5.3.0");import{createSecretKey as zf,generateKeyPair as Mn}from"crypto";import{promisify as Wn}from"util";var Qf=Wn(Mn);import{createHmac as Un,createPrivateKey as Jn,randomBytes as $n}from"crypto";import{existsSync as Fn,readFileSync as sr,writeFileSync as cr}from"fs";import{basename as pr,extname as Bn,resolve as dt}from"path";import{extract as Gn}from"tar";function z(e){console.log(JSON.stringify(e,null,2))}async function lt(e,t,r){let o=t.source,n=De(o);if(!n)return;console.log("Saving source code...");let i=await e.createAttachment(n,pr(o),Xn(o));console.log("Updating bot...");let s=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+s.meta?.versionId)}async function ut(e,t,r){let o=t.dist??t.source,n=De(o);if(!n)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:pr(o)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}async function mt(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 lt(e,A,y),await ut(e,A,y),console.log(`Success! Bot created: ${y.id}`),s&&jn(A)}function dr(e){let t=new RegExp("^"+Vn(e).replace(/\\\*/g,".*")+"$"),r=F()?.bots?.filter(o=>t.test(o.name));return r||[]}function q(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){cr(dt(e),JSON.stringify(t,void 0,2),"utf-8")}function F(e,t){let r=q(e,t),o=De(r);if(o)return JSON.parse(o)}function lr(e){let t=De(q(e,{server:!0}));if(t)return JSON.parse(t)}function De(e){let t=dt(e);return Fn(t)?sr(t,"utf8"):""}function jn(e){let t=F()??{};t.bots||(t.bots=[]),t.bots.push(e),cr("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Vn(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function ur(e){let o=0,n=0;return Gn({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 Xn(e){let t=Bn(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?pt.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?pt.TYPESCRIPT:pt.TEXT}function ke(e,t){let r=new $(e),o={name:e,...t};return r.setObject("options",o),o}function mr(e){return new $(e).getObject("options")}async function fr(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=ar(JSON.stringify(r)),s=ar(JSON.stringify(n)),d=`${i}.${s}`,l=Un("sha256",t.clientSecret).update(d).digest("base64url"),y=`${d}.${l}`;await e.startJwtBearerLogin(t.clientId,y,t.scope??"")}async function hr(e,t){let r=Jn(sr(dt(t.privateKeyPath))),o=await new Se({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti($n(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var yr=qn,gr="http://localhost:9615",ht=h("login"),yt=h("whoami"),gt=h("token");ht.action(async e=>{let t=e.profile??"default",r=ke(t,e),o=await S(e,!1);await ti(o,r)});yt.action(async e=>{let t=await S(e);ni(t)});gt.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 ii(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 fr(e,t);break;case"jwt-assertion":await hr(e,t);break}}async function ri(e){let t=Qn(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":He.TEXT}),o.end("OK");return}if(n.pathname==="/"&&i)try{let s=await e.processCode(i,{clientId:yr,redirectUri:gr});o.writeHead(200,{"Content-Type":He.TEXT}),o.end(`Signed in as ${zn(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":He.TEXT}),o.end(`Error: ${Yn(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":He.TEXT}),o.end("Not found")}).listen(9615)}async function oi(e){let t=ei(),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)}Zn(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 ii(e){await ri(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",yr),t.searchParams.set("redirect_uri",gr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await oi(t.toString())}import{Command as ts}from"commander";var Ir=Wt(It());import{CloudFormationClient as vr,DescribeStackResourcesCommand as Bi,DescribeStacksCommand as Gi,ListStacksCommand as ji}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as Vi,CreateInvalidationCommand as Xi}from"@aws-sdk/client-cloudfront";import{ECSClient as zi}from"@aws-sdk/client-ecs";import{S3Client as qi}from"@aws-sdk/client-s3";import{GetParameterCommand as Yi,PutParameterCommand as Zi,SSMClient as Qi}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as ea,STSClient as ta}from"@aws-sdk/client-sts";import{normalizeErrorString as ra}from"@medplum/core";import oa from"node-fetch";import{readdirSync as na}from"fs";import Fi from"readline";var Ue;function Je(){Ue=Fi.createInterface({input:process.stdin,output:process.stdout})}function $e(){Ue.close()}function c(e){Ue.write(e+`
|
|
2
|
+
var yo=Object.create;var Ze=Object.defineProperty;var go=Object.getOwnPropertyDescriptor;var wo=Object.getOwnPropertyNames;var Eo=Object.getPrototypeOf,So=Object.prototype.hasOwnProperty;var Ao=(e,t,r)=>t in e?Ze(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Mt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var bo=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Co=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of wo(t))!So.call(e,n)&&n!==r&&Ze(e,n,{get:()=>t[n],enumerable:!(o=go(t,n))||o.enumerable});return e};var Wt=(e,t,r)=>(r=e!=null?yo(Eo(e)):{},Co(t||!e||!e.__esModule?Ze(r,"default",{value:e,enumerable:!0}):r,e));var C=(e,t,r)=>Ao(e,typeof t!="symbol"?t+"":t,r);var It=bo((u,br)=>{"use strict";u=br.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 Ae=256,Ke=Number.MAX_SAFE_INTEGER||9007199254740991,wt=16,ni=Ae-6,pe=u.re=[],g=u.safeRe=[],p=u.src=[],a=u.tokens={},Sr=0;function f(e){a[e]=Sr++}var St="[a-zA-Z0-9-]",Et=[["\\s",1],["\\d",Ae],[St,ni]];function Ce(e){for(var t=0;t<Et.length;t++){var r=Et[t][0],o=Et[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-]"+St+"*";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]=St+"+";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,"+wt+"})(?:\\.(\\d{1,"+wt+"}))?(?:\\.(\\d{1,"+wt+"}))?(?:$|[^\\d])";f("COERCERTL");pe[a.COERCERTL]=new RegExp(p[a.COERCE],"g");g[a.COERCERTL]=new RegExp(Ce(p[a.COERCE]),"g");f("LONETILDE");p[a.LONETILDE]="(?:~>?)";f("TILDETRIM");p[a.TILDETRIM]="(\\s*)"+p[a.LONETILDE]+"\\s+";pe[a.TILDETRIM]=new RegExp(p[a.TILDETRIM],"g");g[a.TILDETRIM]=new RegExp(Ce(p[a.TILDETRIM]),"g");var ii="$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+";pe[a.CARETTRIM]=new RegExp(p[a.CARETTRIM],"g");g[a.CARETTRIM]=new RegExp(Ce(p[a.CARETTRIM]),"g");var ai="$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]+")";pe[a.COMPARATORTRIM]=new RegExp(p[a.COMPARATORTRIM],"g");g[a.COMPARATORTRIM]=new RegExp(Ce(p[a.COMPARATORTRIM]),"g");var si="$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(B=0;B<Sr;B++)w(B,p[B]),pe[B]||(pe[B]=new RegExp(p[B]),g[B]=new RegExp(Ce(p[B])));var B;u.parse=oe;function oe(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof m)return e;if(typeof e!="string"||e.length>Ae)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=ci;function ci(e,t){var r=oe(e,t);return r?r.version:null}u.clean=pi;function pi(e,t){var r=oe(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>Ae)throw new TypeError("version is longer than "+Ae+" 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>Ke||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Ke||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Ke||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<Ke)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)),re(this.major,e.major)||re(this.minor,e.minor)||re(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 re(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 re(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=di;function di(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=li;function li(e,t){if(At(e,t))return null;var r=oe(e),o=oe(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=re;var wr=/^[0-9]+$/;function re(e,t){var r=wr.test(e),o=wr.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1}u.rcompareIdentifiers=ui;function ui(e,t){return re(t,e)}u.major=mi;function mi(e,t){return new m(e,t).major}u.minor=fi;function fi(e,t){return new m(e,t).minor}u.patch=hi;function hi(e,t){return new m(e,t).patch}u.compare=Y;function Y(e,t,r){return new m(e,r).compare(new m(t,r))}u.compareLoose=yi;function yi(e,t){return Y(e,t,!0)}u.compareBuild=gi;function gi(e,t,r){var o=new m(e,r),n=new m(t,r);return o.compare(n)||o.compareBuild(n)}u.rcompare=wi;function wi(e,t,r){return Y(t,e,r)}u.sort=Ei;function Ei(e,t){return e.sort(function(r,o){return u.compareBuild(r,o,t)})}u.rsort=Si;function Si(e,t){return e.sort(function(r,o){return u.compareBuild(o,r,t)})}u.gt=be;function be(e,t,r){return Y(e,t,r)>0}u.lt=Le;function Le(e,t,r){return Y(e,t,r)<0}u.eq=At;function At(e,t,r){return Y(e,t,r)===0}u.neq=Ar;function Ar(e,t,r){return Y(e,t,r)!==0}u.gte=bt;function bt(e,t,r){return Y(e,t,r)>=0}u.lte=Ct;function Ct(e,t,r){return Y(e,t,r)<=0}u.cmp=Me;function Me(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 At(e,r,o);case"!=":return Ar(e,r,o);case">":return be(e,r,o);case">=":return bt(e,r,o);case"<":return Le(e,r,o);case"<=":return Ct(e,r,o);default:throw new TypeError("Invalid operator: "+t)}}u.Comparator=U;function U(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof U){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof U))return new U(e,t);e=e.trim().split(/\s+/).join(" "),w("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===de?this.value="":this.value=this.operator+this.semver.version,w("comp",this)}var de={};U.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=de};U.prototype.toString=function(){return this.value};U.prototype.test=function(e){if(w("Comparator.test",e,this.options.loose),this.semver===de||e===de)return!0;if(typeof e=="string")try{e=new m(e,this.options)}catch{return!1}return Me(e,this.operator,this.semver,this.options)};U.prototype.intersects=function(e,t){if(!(e instanceof U))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),We(this.value,r,t));if(e.operator==="")return e.value===""?!0:(r=new I(this.value,t),We(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=Me(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),l=Me(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 U)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,Oi),w("hyphen replace",e),e=e.replace(g[a.COMPARATORTRIM],si),w("comparator trim",e,g[a.COMPARATORTRIM]),e=e.replace(g[a.TILDETRIM],ii),e=e.replace(g[a.CARETTRIM],ai),e=e.split(/\s+/).join(" ");var o=t?g[a.COMPARATORLOOSE]:g[a.COMPARATOR],n=e.split(" ").map(function(i){return bi(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 U(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 Er(r,t)&&e.set.some(function(o){return Er(o,t)&&r.every(function(n){return o.every(function(i){return n.intersects(i,t)})})})})};function Er(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=Ai;function Ai(e,t){return new I(e,t).set.map(function(r){return r.map(function(o){return o.value}).join(" ").trim().split(" ")})}function bi(e,t){return w("comp",e,t),e=Ii(e,t),w("caret",e),e=Ci(e,t),w("tildes",e),e=Ri(e,t),w("xrange",e),e=xi(e,t),w("stars",e),e}function O(e){return!e||e.toLowerCase()==="x"||e==="*"}function Ci(e,t){return e.trim().split(/\s+/).map(function(r){return vi(r,t)}).join(" ")}function vi(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 Ii(e,t){return e.trim().split(/\s+/).map(function(r){return Pi(r,t)}).join(" ")}function Pi(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 Ri(e,t){return w("replaceXRanges",e,t),e.split(/\s+/).map(function(r){return Ti(r,t)}).join(" ")}function Ti(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 xi(e,t){return w("replaceStars",e,t),e.trim().replace(g[a.STAR],"")}function Oi(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(Ni(this.set[t],e,this.options))return!0;return!1};function Ni(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!==de&&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=We;function We(e,t,r){try{t=new I(t,r)}catch{return!1}return t.test(e)}u.maxSatisfying=_i;function _i(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=Di;function Di(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=ki;function ki(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||be(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=Hi;function Hi(e,t){try{return new I(e,t).range||"*"}catch{return null}}u.ltr=Ki;function Ki(e,t,r){return vt(e,t,"<",r)}u.gtr=Li;function Li(e,t,r){return vt(e,t,">",r)}u.outside=vt;function vt(e,t,r,o){e=new m(e,o),t=new I(t,o);var n,i,s,d,l;switch(r){case">":n=be,i=Ct,s=Le,d=">",l=">=";break;case"<":n=Le,i=bt,s=be,d="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(We(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===de&&(k=new U(">=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=Mi;function Mi(e,t){var r=oe(e,t);return r&&r.prerelease.length?r.prerelease:null}u.intersects=Wi;function Wi(e,t,r){return e=new I(e,r),t=new I(t,r),e.intersects(t)}u.coerce=Ui;function Ui(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:oe(r[2]+"."+(r[3]||"0")+"."+(r[4]||"0"),t)}});import{MEDPLUM_VERSION as _s,normalizeErrorString as Lt}from"@medplum/core";import{Command as Ds,CommanderError as ho}from"commander";import ks from"dotenv";import{ContentType as He,getDisplayString as Vn,MEDPLUM_CLI_CLIENT_ID as Xn,normalizeErrorString as zn}from"@medplum/core";import{exec as qn}from"child_process";import{createServer as Yn}from"http";import{platform as Zn}from"os";import{MedplumClient as xo}from"@medplum/core";import{ClientStorage as vo}from"@medplum/core";import{existsSync as Ut,mkdirSync as Io,readFileSync as Po,writeFileSync as Ro}from"fs";import{homedir as To}from"os";import{resolve as Jt}from"path";var $=class extends vo{constructor(t){super(),this.dirName=Jt(To(),".medplum"),this.fileName=Jt(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(Ut(this.fileName))return JSON.parse(Po(this.fileName,"utf8"))}writeFile(t){Ut(this.dirName)||Io(this.dirName),Ro(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function S(e,t=!0){let r=e.profile??"default",o=new $(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:s,accessToken:d,tokenUrl:l,authorizeUrl:y,clientId:A,clientSecret:b}=Oo(e,o),T=e.fetch??fetch,k=new xo({fetch:T,baseUrl:i,tokenUrl:l,fhirUrlPath:s,authorizeUrl:y,storage:o,onUnauthenticated:No,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 Oo(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 No(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{Command as _o,Option as Do}from"commander";function h(e){return new _o(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 Do("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}import{ContentType as pt,encodeBase64 as ar}from"@medplum/core";import{Buffer as Ho}from"buffer";var H=new TextEncoder,N=new TextDecoder,Zs=2**32;function J(...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 K=e=>Ho.from(e).toString("base64url");var ee=class extends Error{constructor(r){super(r);C(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 ee{constructor(){super(...arguments);C(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var L=class extends ee{constructor(){super(...arguments);C(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},Z=class extends ee{constructor(){super(...arguments);C(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var Ft,Bt,Qe=class extends(Bt=ee,Ft=Symbol.asyncIterator,Bt){constructor(){super(...arguments);C(this,Ft);C(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");C(this,"message","multiple matching keys found in the JSON Web Key Set")}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};import*as Gt from"util";var M=e=>Gt.types.isKeyObject(e);import*as jt from"crypto";import*as Vt from"util";var Lo=jt.webcrypto,Xt=Lo,_=e=>Vt.types.isCryptoKey(e);function V(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Re(e,t){return e.name===t}function tt(e){return parseInt(e.name.slice(4),10)}function Mo(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Wo(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 zt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Re(e.algorithm,"HMAC"))throw V("HMAC");let o=parseInt(t.slice(2),10);if(tt(e.algorithm.hash)!==o)throw V(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Re(e.algorithm,"RSASSA-PKCS1-v1_5"))throw V("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(tt(e.algorithm.hash)!==o)throw V(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Re(e.algorithm,"RSA-PSS"))throw V("RSA-PSS");let o=parseInt(t.slice(2),10);if(tt(e.algorithm.hash)!==o)throw V(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw V("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!Re(e.algorithm,"ECDSA"))throw V("ECDSA");let o=Mo(t);if(e.algorithm.namedCurve!==o)throw V(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Wo(e,r)}function qt(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 W=(e,...t)=>qt("Key must be ",e,...t);function rt(e,t,...r){return qt(`Key for the ${e} algorithm must be `,t,...r)}var ot=e=>M(e)||_(e),v=["KeyObject"];(globalThis.CryptoKey||Xt?.CryptoKey)&&v.push("CryptoKey");var Bo=(...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},ie=Bo;function Go(e){return typeof e=="object"&&e!==null}function x(e){if(!Go(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}import{diffieHellman as cp,generateKeyPair as zo,KeyObject as pp}from"crypto";import{promisify as qo}from"util";import{KeyObject as jo}from"crypto";var Vo=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")}},Xo=(e,t)=>{let r;if(_(e))r=jo.from(e);else if(M(e))r=e;else throw new TypeError(W(e,...v));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:Vo(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},nt=Xo;var Ep=qo(zo);import{promisify as Qo}from"util";import{KeyObject as Pp,pbkdf2 as en}from"crypto";var Lp=Qo(en);import{KeyObject as Jp,publicEncrypt as $p,constants as tn,privateDecrypt as Fp}from"crypto";import{deprecate as rn}from"util";var Te=(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 Yp=rn(()=>tn.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var on=(e,t)=>{if(!(t instanceof Uint8Array)){if(!ot(t))throw new TypeError(rt(e,t,...v,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${v.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},nn=(e,t,r)=>{if(!ot(t))throw new TypeError(rt(e,t,...v));if(t.type==="secret")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${v.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},an=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?on(e,t):nn(e,t,r)},ge=an;function un(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 ae=un;var gn=Symbol();import*as ct from"crypto";import{promisify as vn}from"util";function xe(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`)}}import{constants as rr}from"crypto";var wn={padding:rr.RSA_PKCS1_PSS_PADDING,saltLength:rr.RSA_PSS_SALTLEN_DIGEST},En=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Oe(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 Te(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 Te(t,e),{key:t,...wn};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=nt(t),o=En.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`)}}import*as _e from"crypto";import{promisify as An}from"util";function at(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`)}}import{KeyObject as or,createSecretKey as Sn}from"crypto";function Ne(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(W(t,...v));return Sn(t)}if(t instanceof or)return t;if(_(t))return zt(t,e,r),or.from(t);throw new TypeError(W(t,...v,"Uint8Array"))}var bn=An(_e.sign),Cn=async(e,t,r)=>{let o=Ne(e,t,"sign");if(e.startsWith("HS")){let n=_e.createHmac(at(e),o);return n.update(r),n.digest()}return bn(xe(e),r,Oe(e,o))},st=Cn;var Uu=vn(ct.verify);var X=e=>Math.floor(e.getTime()/1e3);var Pn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,we=e=>{let t=Pn.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 se=class{constructor(t){C(this,"_payload");C(this,"_protectedHeader");C(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 L("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!ie(this._protectedHeader,this._unprotectedHeader))throw new L("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=ae(L,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),i=!0;if(n.has("b64")&&(i=this._protectedHeader.b64,typeof i!="boolean"))throw new L('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new L('JWS "alg" (Algorithm) Header Parameter missing or invalid');ge(s,t,"sign");let d=this._payload;i&&(d=H.encode(K(d)));let l;this._protectedHeader?l=H.encode(K(JSON.stringify(this._protectedHeader))):l=H.encode("");let y=J(l,H.encode("."),d),A=await st(s,t,y),b={signature:K(A),payload:""};return i&&(b.payload=N.decode(d)),this._unprotectedHeader&&(b.header=this._unprotectedHeader),this._protectedHeader&&(b.protected=N.decode(l)),b}};var Ee=class{constructor(t){C(this,"_flattened");this._flattened=new se(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 te(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var ce=class{constructor(t={}){C(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:te("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:te("setNotBefore",X(t))}:this._payload={...this._payload,nbf:X(new Date)+we(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:te("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:te("setExpirationTime",X(t))}:this._payload={...this._payload,exp:X(new Date)+we(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:X(new Date)}:t instanceof Date?this._payload={...this._payload,iat:te("setIssuedAt",X(t))}:typeof t=="string"?this._payload={...this._payload,iat:te("setIssuedAt",X(new Date)+we(t))}:this._payload={...this._payload,iat:te("setIssuedAt",t)},this}};var Se=class extends ce{constructor(){super(...arguments);C(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new Ee(H.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 Z("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var Dn;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Dn="jose/v5.3.0");import{createSecretKey as Xf,generateKeyPair as Kn}from"crypto";import{promisify as Ln}from"util";var Zf=Ln(Kn);import{createHmac as Mn,createPrivateKey as Wn,randomBytes as Un}from"crypto";import{existsSync as Jn,readFileSync as sr,writeFileSync as cr}from"fs";import{basename as pr,extname as $n,resolve as dt}from"path";import{extract as Fn}from"tar";function z(e){console.log(JSON.stringify(e,null,2))}async function lt(e,t,r){let o=t.source,n=De(o);if(!n)return;console.log("Saving source code...");let i=await e.createAttachment(n,pr(o),jn(o));console.log("Updating bot...");let s=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+s.meta?.versionId)}async function ut(e,t,r){let o=t.dist??t.source,n=De(o);if(!n)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:pr(o)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}async function mt(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 lt(e,A,y),await ut(e,A,y),console.log(`Success! Bot created: ${y.id}`),s&&Bn(A)}function dr(e){let t=new RegExp("^"+Gn(e).replace(/\\\*/g,".*")+"$"),r=F()?.bots?.filter(o=>t.test(o.name));return r||[]}function q(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){cr(dt(e),JSON.stringify(t,void 0,2),"utf-8")}function F(e,t){let r=q(e,t),o=De(r);if(o)return JSON.parse(o)}function lr(e){let t=De(q(e,{server:!0}));if(t)return JSON.parse(t)}function De(e){let t=dt(e);return Jn(t)?sr(t,"utf8"):""}function Bn(e){let t=F()??{};t.bots||(t.bots=[]),t.bots.push(e),cr("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Gn(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function ur(e){let o=0,n=0;return Fn({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 jn(e){let t=$n(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?pt.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?pt.TYPESCRIPT:pt.TEXT}function ke(e,t){let r=new $(e),o={name:e,...t};return r.setObject("options",o),o}function mr(e){return new $(e).getObject("options")}async function fr(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=ar(JSON.stringify(r)),s=ar(JSON.stringify(n)),d=`${i}.${s}`,l=Mn("sha256",t.clientSecret).update(d).digest("base64url"),y=`${d}.${l}`;await e.startJwtBearerLogin(t.clientId,y,t.scope??"")}async function hr(e,t){let r=Wn(sr(dt(t.privateKeyPath))),o=await new Se({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Un(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var yr=Xn,gr="http://localhost:9615",ht=h("login"),yt=h("whoami"),gt=h("token");ht.action(async e=>{let t=e.profile??"default",r=ke(t,e),o=await S(e,!1);await Qn(o,r)});yt.action(async e=>{let t=await S(e);ri(t)});gt.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 Qn(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await oi(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 fr(e,t);break;case"jwt-assertion":await hr(e,t);break}}async function ei(e){let t=Yn(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":He.TEXT}),o.end("OK");return}if(n.pathname==="/"&&i)try{let s=await e.processCode(i,{clientId:yr,redirectUri:gr});o.writeHead(200,{"Content-Type":He.TEXT}),o.end(`Signed in as ${Vn(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":He.TEXT}),o.end(`Error: ${zn(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":He.TEXT}),o.end("Not found")}).listen(9615)}async function ti(e){let t=Zn(),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)}qn(r,(o,n,i)=>{if(o)throw o;if(i)throw new Error("Could not open browser: "+i)})}function ri(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 oi(e){await ei(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",yr),t.searchParams.set("redirect_uri",gr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await ti(t.toString())}import{Command as Qa}from"commander";var Ir=Wt(It());import{CloudFormationClient as vr,DescribeStackResourcesCommand as $i,DescribeStacksCommand as Fi,ListStacksCommand as Bi}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as Gi,CreateInvalidationCommand as ji}from"@aws-sdk/client-cloudfront";import{ECSClient as Vi}from"@aws-sdk/client-ecs";import{S3Client as Xi}from"@aws-sdk/client-s3";import{GetParameterCommand as zi,PutParameterCommand as qi,SSMClient as Yi}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as Zi,STSClient as Qi}from"@aws-sdk/client-sts";import{normalizeErrorString as ea}from"@medplum/core";import ta from"node-fetch";import{readdirSync as ra}from"fs";import Ji from"readline";var Ue;function Je(){Ue=Ji.createInterface({input:process.stdin,output:process.stdout})}function $e(){Ue.close()}function c(e){Ue.write(e+`
|
|
3
3
|
`)}function P(e){c(`
|
|
4
4
|
`+e+`
|
|
5
|
-
`)}function D(e,t=""){return new Promise(r=>{Ue.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Fe(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 le(e,t,r){return parseInt(await Fe(e,t.map(o=>o.toString()),r.toString()),10)}async function ne(e){return(await Fe(e,["y","n"])).toLowerCase()==="y"}async function ve(e){if(!await ne(e))throw c("Exiting..."),new Error("User cancelled")}var Be=new vr({}),ia=new Vi({region:"us-east-1"}),Fy=new zi({}),Ie=new qi({}),aa="medplum:environment";async function Pt(){return(await Be.send(new ji({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function ue(e){let t=await Pt();for(let r of t){let o=r.StackName,n=await Rt(o);if(n?.tag===e)return n}}async function Rt(e){let t={};if(await Cr(Be,e,t),await Be.config.region()!=="us-east-1")try{await Cr(new vr({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Cr(e,t,r){let o=new Gi({StackName:t}),i=(await e.send(o))?.Stacks?.[0],s=i?.Tags?.find(l=>l.Key===aa);if(!s)return;let d=await e.send(new Bi({StackName:t}));if(d.StackResources){e===Be&&(r.stack=i,r.tag=s.Value);for(let l of d.StackResources)sa(l,r)}}function sa(e,t){e.ResourceType==="AWS::ECS::Cluster"?t.ecsCluster=e:e.ResourceType==="AWS::ECS::Service"?t.ecsService=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("FrontEndAppBucket")?t.appBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("FrontEndAppDistribution")?t.appDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?t.appOriginAccessIdentity=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("StorageStorageBucket")?t.storageBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("StorageStorageDistribution")?t.storageDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(t.storageOriginAccessIdentity=e)}function Ge(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${ca(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 ca(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function je(e){let t=await ia.send(new Xi({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Ve(e){let o=(await(await oa("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)=>Ir.compare(i,n)),e?o.slice(0,o.indexOf(e)):o}async function Xe(e,t,r){let o=new Qi({region:e});for(let[n,i]of Object.entries(r)){let s=t+n,d=i.toString(),l=await pa(o,s);l!==void 0&&l!==d&&(c(`Parameter "${s}" exists with different value.`),await ve(`Do you want to overwrite "${s}"?`)),await da(o,s,d)}}async function pa(e,t){let r=new Yi({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function da(e,t,r){let o=new Zi({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function Q(e,t){if(console.log(`Config not found: ${e} (${q(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=na(".",{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 me(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new ta,r=new ea({}),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",ra(t))}}async function Pr(e){let t=await ue(e);if(!t)throw await me(e),new Error(`Stack not found: ${e}`);Ge(t)}import{ACMClient as xr,ListCertificatesCommand as la,RequestCertificateCommand as ua}from"@aws-sdk/client-acm";import{CloudFrontClient as ma,CreatePublicKeyCommand as fa}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as ha,STSClient as ya}from"@aws-sdk/client-sts";import{normalizeErrorString as ga}from"@medplum/core";import{generateKeyPairSync as wa,randomUUID as Rr}from"crypto";import{existsSync as Ea}from"fs";var Sa=e=>`${e}DomainName`,Or=e=>`${e}SslCertArn`;async function Nr(){let e={apiPort:8103,region:"us-east-1"};Je(),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 Aa(e.region);t||(c("It appears that you do not have AWS credentials configured."),c("AWS credentials are not strictly required, but will enable some additional features."),c("If you intend to use AWS credentials, please configure them now."),await ve("Do you want to continue without AWS credentials?")),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`);Ea(r)&&(c("Config file already exists."),await ve("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 le("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 ne("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 le("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 le("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 le("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 le("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 Ve())[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 Ia(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 ba(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 Ca(e,d,y,A);e[Or(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 ne("Do you want to store these values in AWS Parameter Store?"))await Xe(e.region,`/medplum/${e.name}/`,l);else{let y=q(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(""),$e()}async function Aa(e){try{let t=new ya({region:e}),r=new ha({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function ba(e){let t=await Tr(e);if(e!=="us-east-1"){let r=await Tr("us-east-1");t.push(...r)}return t}async function Tr(e){try{let t=new xr({region:e}),r=new la({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Ca(e,t,r,o){let n=e[Sa(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 ne("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${Or(o)}" setting.`),"TODO";let s=await va(r,n);return c("Certificate ARN: "+s),s}async function va(e,t){try{let r=await Fe("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new xr({region:e}),n=new ua({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 Ia(e,t){let r=Rr(),o=wa("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new ma({region:e}).send(new fa({PublicKeyConfig:{Name:t,CallerReference:Rr(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",ga(n));return}}async function _r(){let e=await Pt();for(let t of e){let r=t.StackName,o=await Rt(r);o&&(Ge(o),console.log(""))}}import{PutObjectCommand as Pa}from"@aws-sdk/client-s3";import{ContentType as G}from"@medplum/core";import Ra from"fast-glob";import Dr from"node-fetch";import{createReadStream as Ta,mkdtempSync as xa,readdirSync as Oa,readFileSync as Na,rmSync as _a,writeFileSync as Da}from"fs";import{tmpdir as ka}from"os";import{join as ze,sep as Ha}from"path";import{pipeline as Ka}from"stream/promises";async function kr(e,t){let r=F(e,t);if(!r)throw Q(e,t),new Error(`Config not found: ${e}`);let o=await ue(e);if(!o)throw await me(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 Ma("@medplum/app",i);Hr(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 Ua(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await je(o.appDistribution.PhysicalResourceId),console.log("Done")}async function La(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Dr(r)).json()}async function Ma(e,t){let o=(await La(e,t)).dist.tarball,n=xa(ze(ka(),"tarball-"));try{let i=await Dr(o),s=ur(n);return await Ka(i.body,s),ze(n,"package","dist")}catch(i){throw _a(n,{recursive:!0,force:!0}),i}}function Hr(e,t){for(let r of Oa(e,{withFileTypes:!0})){let o=ze(e,r.name);r.isDirectory()?Hr(o,t):r.isFile()&&o.endsWith(".js")&&Wa(o,t)}}function Wa(e,t){let r=Na(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);Da(e,r)}async function Ua(e,t,r){let o=[["assets/**/*.css",G.CSS,!0],["assets/**/*.css.map",G.JSON,!0],["assets/**/*.js",G.JAVASCRIPT,!0],["assets/**/*.js.map",G.JSON,!0],["assets/**/*.txt",G.TEXT,!0],["assets/**/*.ico",G.FAVICON,!0],["img/**/*.png",G.PNG,!0],["img/**/*.svg",G.SVG,!0],["robots.txt",G.TEXT,!0],["index.html",G.HTML,!1]];for(let n of o)await Ja({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Ja(e){let t=Ra.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await $a(ze(e.rootDir,r),e)}async function $a(e,t){let r=Ta(e),o=e.substring(t.rootDir.length+1).split(Ha).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await Ie.send(new Pa(n))}import{GetBucketPolicyCommand as Fa,PutBucketPolicyCommand as Ba}from"@aws-sdk/client-s3";async function Lr(e,t){if(!F(e,t))throw Q(e,t),new Error(`Config not found: ${e}`);let o=await ue(e);if(!o)throw await me(e),new Error(`Stack not found: ${e}`);await Kr("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Kr("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Kr(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 Ga(i);if(Va(d,i,s))throw new Error(`${e} bucket already has policy statement`);Xa(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 ja(i,d),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await je(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Ga(e){let t=await Ie.send(new Fa({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function ja(e,t){await Ie.send(new Ba({Bucket:e,Policy:JSON.stringify(t)}))}function Va(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 Xa(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 Mr(e,t){try{Je();let r=F(e,t);if(!r)throw Q(e,t),new Error(`Config not found: ${e}`);let o=lr(e)??{};za(r,o),Ya(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)),await ne("Do you want to store these values in AWS Parameter Store?")&&await Xe(r.region,`/medplum/${r.name}/`,o)}finally{$e()}}function za(e,t){qe(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),qe(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),qe(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),qe(e.storageDomainName&&`https://${e.storageDomainName}/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function qe(e,t,r){if(qa(e,t))throw new Error(r)}function qa(e,t){return e!==void 0&&t!==void 0&&e!==t}function Ya(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 fe=Wt(It());import{spawnSync as Za}from"child_process";async function Ur(e,t){let r=await S(t),o=F(e,t);if(!o)throw console.log(`Configuration file ${q(e)} not found`),Q(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),i=o.serverImage.slice(0,n),s=await Qa(r,o),d=await Wr(s);for(;d;){if(t.toVersion&&fe.gt(d,t.toVersion)){console.log(`Skipping update to v${d}`);break}console.log(`Performing update to v${d}`),o.serverImage=`${i}:${d}`,es(e,o),await r.startAsyncRequest("/admin/super/migrate"),d=await Wr(d)}}async function Qa(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 Wr(e,t){let r=await Ve(e),o=r[0];return r.filter(n=>n===o||n===t||fe.gte(n,fe.inc(e,"minor"))).pop()}function es(e,t){let r=q(e);R(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=Za(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 Jr(){let e=new ts("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Nr),e.command("list").description("List Medplum AWS CloudFormation stacks").action(_r),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Pr),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.").action(Mr),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(Ur)),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(kr),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(Lr),e}import{Command as rs}from"commander";var $r=h("save"),Fr=h("deploy"),Br=h("create"),Gr=new rs("bot").addCommand($r).addCommand(Fr).addCommand(Br),Tt=h("save-bot"),xt=h("deploy-bot"),Ot=h("create-bot");$r.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await Ye(r,e)});Fr.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await Ye(r,e,!0)});Br.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 mt(i,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function Ye(e,t,r=!1){let o=dr(t),n=[],i=[],s=0,d=0;for(let l of o)try{let y=await e.readResource("Bot",l.id);await lt(e,l,y),s++,r&&(await ut(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 D(e,t=""){return new Promise(r=>{Ue.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Fe(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 le(e,t,r){return parseInt(await Fe(e,t.map(o=>o.toString()),r.toString()),10)}async function ne(e){return(await Fe(e,["y","n"])).toLowerCase()==="y"}async function ve(e){if(!await ne(e))throw c("Exiting..."),new Error("User cancelled")}var Be=new vr({}),oa=new Gi({region:"us-east-1"}),$y=new Vi({}),Ie=new Xi({}),na="medplum:environment";async function Pt(){return(await Be.send(new Bi({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function ue(e){let t=await Pt();for(let r of t){let o=r.StackName,n=await Rt(o);if(n?.tag===e)return n}}async function Rt(e){let t={};if(await Cr(Be,e,t),await Be.config.region()!=="us-east-1")try{await Cr(new vr({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Cr(e,t,r){let o=new Fi({StackName:t}),i=(await e.send(o))?.Stacks?.[0],s=i?.Tags?.find(l=>l.Key===na);if(!s)return;let d=await e.send(new $i({StackName:t}));if(d.StackResources){e===Be&&(r.stack=i,r.tag=s.Value);for(let l of d.StackResources)ia(l,r)}}function ia(e,t){e.ResourceType==="AWS::ECS::Cluster"?t.ecsCluster=e:e.ResourceType==="AWS::ECS::Service"?t.ecsService=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("FrontEndAppBucket")?t.appBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("FrontEndAppDistribution")?t.appDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?t.appOriginAccessIdentity=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("StorageStorageBucket")?t.storageBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("StorageStorageDistribution")?t.storageDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(t.storageOriginAccessIdentity=e)}function Ge(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${aa(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 aa(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function je(e){let t=await oa.send(new ji({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Ve(e){let o=(await(await ta("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)=>Ir.compare(i,n)),e?o.slice(0,o.indexOf(e)):o}async function Xe(e,t,r){let o=new Yi({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 ve(`Do you want to overwrite "${s}"?`)),await ca(o,s,d)}}async function sa(e,t){let r=new zi({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function ca(e,t,r){let o=new qi({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function Q(e,t){if(console.log(`Config not found: ${e} (${q(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=ra(".",{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 me(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new Qi,r=new Zi({}),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",ea(t))}}async function Pr(e){let t=await ue(e);if(!t)throw await me(e),new Error(`Stack not found: ${e}`);Ge(t)}import{ACMClient as xr,ListCertificatesCommand as pa,RequestCertificateCommand as da}from"@aws-sdk/client-acm";import{CloudFrontClient as la,CreatePublicKeyCommand as ua}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as ma,STSClient as fa}from"@aws-sdk/client-sts";import{normalizeErrorString as ha}from"@medplum/core";import{generateKeyPairSync as ya,randomUUID as Rr}from"crypto";import{existsSync as ga}from"fs";var wa=e=>`${e}DomainName`,Or=e=>`${e}SslCertArn`;async function Nr(){let e={apiPort:8103,region:"us-east-1"};Je(),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 Ea(e.region);t||(c("It appears that you do not have AWS credentials configured."),c("AWS credentials are not strictly required, but will enable some additional features."),c("If you intend to use AWS credentials, please configure them now."),await ve("Do you want to continue without AWS credentials?")),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`);ga(r)&&(c("Config file already exists."),await ve("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 le("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 ne("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 le("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 le("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 le("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 le("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 Ve())[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 Ca(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 Sa(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 Aa(e,d,y,A);e[Or(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 ne("Do you want to store these values in AWS Parameter Store?"))await Xe(e.region,`/medplum/${e.name}/`,l);else{let y=q(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(""),$e()}async function Ea(e){try{let t=new fa({region:e}),r=new ma({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Sa(e){let t=await Tr(e);if(e!=="us-east-1"){let r=await Tr("us-east-1");t.push(...r)}return t}async function Tr(e){try{let t=new xr({region:e}),r=new pa({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Aa(e,t,r,o){let n=e[wa(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 ne("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${Or(o)}" setting.`),"TODO";let s=await ba(r,n);return c("Certificate ARN: "+s),s}async function ba(e,t){try{let r=await Fe("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new xr({region:e}),n=new da({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 Ca(e,t){let r=Rr(),o=ya("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new la({region:e}).send(new ua({PublicKeyConfig:{Name:t,CallerReference:Rr(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",ha(n));return}}async function _r(){let e=await Pt();for(let t of e){let r=t.StackName,o=await Rt(r);o&&(Ge(o),console.log(""))}}import{PutObjectCommand as va}from"@aws-sdk/client-s3";import{ContentType as G}from"@medplum/core";import Ia from"fast-glob";import Dr from"node-fetch";import{createReadStream as Pa,mkdtempSync as Ra,readdirSync as Ta,readFileSync as xa,rmSync as Oa,writeFileSync as Na}from"fs";import{tmpdir as _a}from"os";import{join as ze,sep as Da}from"path";import{pipeline as ka}from"stream/promises";async function kr(e,t){let r=F(e,t);if(!r)throw Q(e,t),new Error(`Config not found: ${e}`);let o=await ue(e);if(!o)throw await me(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 Ka("@medplum/app",i);Hr(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 Ma(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await je(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Ha(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Dr(r)).json()}async function Ka(e,t){let o=(await Ha(e,t)).dist.tarball,n=Ra(ze(_a(),"tarball-"));try{let i=await Dr(o),s=ur(n);return await ka(i.body,s),ze(n,"package","dist")}catch(i){throw Oa(n,{recursive:!0,force:!0}),i}}function Hr(e,t){for(let r of Ta(e,{withFileTypes:!0})){let o=ze(e,r.name);r.isDirectory()?Hr(o,t):r.isFile()&&o.endsWith(".js")&&La(o,t)}}function La(e,t){let r=xa(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);Na(e,r)}async function Ma(e,t,r){let o=[["assets/**/*.css",G.CSS,!0],["assets/**/*.css.map",G.JSON,!0],["assets/**/*.js",G.JAVASCRIPT,!0],["assets/**/*.js.map",G.JSON,!0],["assets/**/*.txt",G.TEXT,!0],["assets/**/*.ico",G.FAVICON,!0],["img/**/*.png",G.PNG,!0],["img/**/*.svg",G.SVG,!0],["robots.txt",G.TEXT,!0],["index.html",G.HTML,!1]];for(let n of o)await Wa({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Wa(e){let t=Ia.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Ua(ze(e.rootDir,r),e)}async function Ua(e,t){let r=Pa(e),o=e.substring(t.rootDir.length+1).split(Da).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await Ie.send(new va(n))}import{GetBucketPolicyCommand as Ja,PutBucketPolicyCommand as $a}from"@aws-sdk/client-s3";async function Lr(e,t){if(!F(e,t))throw Q(e,t),new Error(`Config not found: ${e}`);let o=await ue(e);if(!o)throw await me(e),new Error(`Stack not found: ${e}`);await Kr("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Kr("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Kr(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 Fa(i);if(Ga(d,i,s))throw new Error(`${e} bucket already has policy statement`);ja(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 Ba(i,d),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await je(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Fa(e){let t=await Ie.send(new Ja({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Ba(e,t){await Ie.send(new $a({Bucket:e,Policy:JSON.stringify(t)}))}function Ga(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 ja(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 Mr(e,t){try{Je();let r=F(e,t);if(!r)throw Q(e,t),new Error(`Config not found: ${e}`);let o=lr(e)??{};Va(r,o),za(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)),await ne("Do you want to store these values in AWS Parameter Store?")&&await Xe(r.region,`/medplum/${r.name}/`,o)}finally{$e()}}function Va(e,t){qe(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),qe(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),qe(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),qe(e.storageDomainName&&`https://${e.storageDomainName}/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function qe(e,t,r){if(Xa(e,t))throw new Error(r)}function Xa(e,t){return e!==void 0&&t!==void 0&&e!==t}function za(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 fe=Wt(It());import{spawnSync as qa}from"child_process";async function Ur(e,t){let r=await S(t),o=F(e,t);if(!o)throw console.log(`Configuration file ${q(e)} not found`),Q(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),i=o.serverImage.slice(0,n),s=await Ya(r,o),d=await Wr(s);for(;d;){if(t.toVersion&&fe.gt(d,t.toVersion)){console.log(`Skipping update to v${d}`);break}console.log(`Performing update to v${d}`),o.serverImage=`${i}:${d}`,Za(e,o),await r.startAsyncRequest("/admin/super/migrate"),d=await Wr(d)}}async function Ya(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 Wr(e,t){let r=await Ve(e),o=r[0];return r.filter(n=>n===o||n===t||fe.gte(n,fe.inc(e,"minor"))).pop()}function Za(e,t){let r=q(e);R(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=qa(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 Jr(){let e=new Qa("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Nr),e.command("list").description("List Medplum AWS CloudFormation stacks").action(_r),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Pr),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.").action(Mr),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(Ur)),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(kr),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(Lr),e}import{Command as es}from"commander";var $r=h("save"),Fr=h("deploy"),Br=h("create"),Gr=new es("bot").addCommand($r).addCommand(Fr).addCommand(Br),Tt=h("save-bot"),xt=h("deploy-bot"),Ot=h("create-bot");$r.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await Ye(r,e)});Fr.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await Ye(r,e,!0)});Br.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 mt(i,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function Ye(e,t,r=!1){let o=dr(t),n=[],i=[],s=0,d=0;for(let l of o)try{let y=await e.readResource("Bot",l.id);await lt(e,l,y),s++,r&&(await ut(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:
|
|
6
6
|
|
|
7
7
|
${i.join(`
|
|
8
|
-
`)}`,{cause:n})}Tt.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await Ye(r,e)});xt.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await Ye(r,e,!0)});Ot.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let i=await S(n);await mt(i,e,t,r,o)});import{Command as
|
|
9
|
-
`))}finally{n.close()}}),
|
|
10
|
-
`)),
|
|
8
|
+
`)}`,{cause:n})}Tt.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await Ye(r,e)});xt.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await Ye(r,e,!0)});Ot.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let i=await S(n);await mt(i,e,t,r,o)});import{Command as ts}from"commander";import{createReadStream as rs,writeFile as os}from"fs";import{resolve as Vr}from"path";import{createInterface as ns}from"readline";var Xr=h("export"),zr=h("import"),qr=new ts("bulk").addCommand(Xr).addCommand(zr);Xr.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=Vr(n??"",b);os(`${T}`,await A.text(),()=>{console.log(`${T} is created`)})})});zr.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=Vr(n??process.cwd(),e),s=await S(t);await is(i,parseInt(r,10),s,o)});async function is(e,t,r,o){let n=[],i=rs(e),s=ns({input:i});for await(let d of s){let l=as(d,o);n.push({resource:l,request:{method:"POST",url:l.resourceType}}),n.length%t===0&&(await jr(n,r),n=[])}n.length>0&&await jr(n,r)}async function jr(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{z(o.response)})}function as(e,t){let r=JSON.parse(e);return t?ss(r):r}function ss(e){return e.resourceType==="ExplanationOfBenefit"?cs(e):e}function cs(e){return e.provider||(e.provider=ft()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=ft())}),e}import{formatHl7DateTime as hs,Hl7Message as ys}from"@medplum/core";import{connect as ps}from"net";import{Hl7Message as ds}from"@medplum/core";import{decode as ls,encode as us}from"iconv-lite";import fs from"net";var Zr=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var ms=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},Yr=class extends Event{constructor(e){super("error"),this.error=e}},Qr=class extends Zr{constructor(e,t="utf-8"){super(),this.socket=e,this.encoding=t,this.chunks=[],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=ls(n,this.encoding),s=ds.parse(i);this.dispatchEvent(new ms(this,s)),this.resetBuffer()}}catch(o){this.dispatchEvent(new Yr(o))}}),e.on("error",r=>{this.resetBuffer(),this.dispatchEvent(new Yr(r))})}send(e){let t=e.toString(),r=us(t,this.encoding),o=Buffer.alloc(r.length+3);o.writeInt8(11,0),r.copy(o,1),o.writeInt8(28,r.length+1),o.writeInt8(13,r.length+2),this.socket.write(o)}async sendAndWait(e){let t=new Promise(r=>{function o(n){n.target.removeEventListener("message",o),r(n.message)}this.addEventListener("message",o)});return this.send(e),t}close(){this.socket.end(),this.socket.destroy()}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}},eo=class extends Zr{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding}connect(){return this.connection?Promise.resolve(this.connection):new Promise((e,t)=>{let r=ps({host:this.host,port:this.port},()=>{this.connection=new Qr(r,this.encoding),r.off("error",t),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)}},to=class{constructor(e){this.handler=e}start(e,t){let r=fs.createServer(o=>{let n=new Qr(o,t);this.handler(n)});r.listen(e),this.server=r}async stop(){return new Promise((e,t)=>{this.server&&(this.server.close(r=>{if(r){t(r);return}e()}),this.server=void 0)})}};import{Command as gs}from"commander";import{readFileSync as ws}from"fs";var Es=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=As():o.file&&(r=ws(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new eo({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await n.sendAndWait(ys.parse(r));console.log(i.toString().replaceAll("\r",`
|
|
9
|
+
`))}finally{n.close()}}),Ss=h("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{new to(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)}),ro=new gs("hl7").addCommand(Es).addCommand(Ss);function As(){let e=hs(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|`}import{Command as
|
|
13
|
+
PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}import{Command as bs}from"commander";import{readdirSync as Cs}from"fs";import{homedir as vs}from"os";import{resolve as Is}from"path";var oo=h("set"),no=h("remove"),io=h("list"),ao=h("describe"),so=new bs("profile").addCommand(oo).addCommand(no).addCommand(io).addCommand(ao);oo.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)=>{ke(e,t)});no.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new $(e).setObject("options",void 0),console.log(`${e} profile removed`)});io.description("List all profiles saved").action(async()=>{let e=Is(vs(),".medplum"),t=Cs(e),r=[];t.forEach(o=>{let n=o.split(".")[0],s=new $(n).getObject("options");s&&r.push({profileName:n,profile:s})}),console.log(r)});ao.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=mr(e);console.log(t)});import{Command as Ps,Option as Rs}from"commander";var co=h("list"),po=h("current"),lo=h("switch"),uo=h("invite"),mo=new Ps("project").addCommand(co).addCommand(po).addCommand(lo).addCommand(uo);co.description("List of current projects").action(async e=>{let t=await S(e);Ts(t)});function Ts(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
|
|
14
14
|
|
|
15
|
-
`);console.log(r)}
|
|
16
|
-
`)}async function
|
|
15
|
+
`);console.log(r)}po.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})`)});lo.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await S(t);await xs(r,e)});uo.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 Rs("-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 Os(s,d,n)});async function xs(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 Os(e,t,r){await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}import{convertToTransactionBundle as Ns}from"@medplum/core";var Nt=h("delete"),_t=h("get"),Dt=h("patch"),kt=h("post"),Ht=h("put");Nt.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await S(t);z(await r.delete(Pe(r,e)))});_t.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(Pe(r,e));t.asTransaction?z(Ns(o)):z(o)});Dt.arguments("<url> <body>").action(async(e,t,r)=>{let o=await S(r);z(await o.patch(Pe(o,e),Kt(t)))});kt.arguments("<url> <body>").action(async(e,t,r)=>{let o=await S(r);z(await o.post(Pe(o,e),Kt(t)))});Ht.arguments("<url> <body>").action(async(e,t,r)=>{let o=await S(r);z(await o.put(Pe(o,e),Kt(t)))});function Kt(e){if(e)try{return JSON.parse(e)}catch{return e}}function Pe(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function Hs(e){let t=new Ds("medplum").description("Command to access Medplum CLI");t.exitOverride(),t.version(_s),t.addCommand(ht),t.addCommand(yt),t.addCommand(gt),t.addCommand(_t),t.addCommand(kt),t.addCommand(Dt),t.addCommand(Ht),t.addCommand(Nt),t.addCommand(mo),t.addCommand(qr),t.addCommand(Gr),t.addCommand(Tt),t.addCommand(xt),t.addCommand(Ot),t.addCommand(so),t.addCommand(Jr()),t.addCommand(ro);try{await t.parseAsync(e)}catch(r){Ks(r)}}function Ks(e){fo(e);let t=e.cause;if(Array.isArray(t))for(let o of t)fo(o);let r=1;e instanceof ho&&(r=e.exitCode),process.exit(r)}function fo(e){e instanceof ho&&process.stderr.write(`${Lt(e)}
|
|
17
17
|
`),process.stderr.write(`Error: ${Lt(e)}
|
|
18
|
-
`)}async function
|
|
18
|
+
`)}async function Ls(){ks.config(),await Hs(process.argv)}Mt.main===module&&Ls().catch(e=>{console.error("Unhandled error:",Lt(e)),process.exit(1)});export{Ks as handleError,Hs as main,Ls as run};
|
|
19
19
|
//# sourceMappingURL=index.mjs.map
|