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