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