@medplum/cli 5.1.6 → 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 +14 -14
- package/dist/cjs/index.cjs.map +3 -3
- package/dist/esm/index.mjs +14 -14
- package/dist/esm/index.mjs.map +3 -3
- package/package.json +14 -14
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Di=Object.create;var Ce=Object.defineProperty;var _i=Object.getOwnPropertyDescriptor;var Ui=Object.getOwnPropertyNames;var ji=Object.getPrototypeOf,Fi=Object.prototype.hasOwnProperty;var Bi=(e,t,r)=>t in e?Ce(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),Wi=(e,t)=>{for(var r in t)Ce(e,r,{get:t[r],enumerable:!0})},Kr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ui(t))!Fi.call(e,n)&&n!==r&&Ce(e,n,{get:()=>t[n],enumerable:!(o=_i(t,n))||o.enumerable});return e};var k=(e,t,r)=>(r=e!=null?Di(ji(e)):{},Kr(t||!e||!e.__esModule?Ce(r,"default",{value:e,enumerable:!0}):r,e)),Ki=e=>Kr(Ce({},"__esModule",{value:!0}),e);var P=(e,t,r)=>Bi(e,typeof t!="symbol"?t+"":t,r);var Me=w((Jd,Uo)=>{"use strict";var Ca="2.0.0",Ta=Number.MAX_SAFE_INTEGER||9007199254740991,Oa=16,xa=250,$a=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Uo.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Oa,MAX_SAFE_BUILD_LENGTH:xa,MAX_SAFE_INTEGER:Ta,RELEASE_TYPES:$a,SEMVER_SPEC_VERSION:Ca,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var De=w((Xd,jo)=>{"use strict";var Na=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};jo.exports=Na});var we=w((G,Fo)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:ar,MAX_SAFE_BUILD_LENGTH:ka,MAX_LENGTH:La}=Me(),Ma=De();G=Fo.exports={};var Da=G.re=[],_a=G.safeRe=[],p=G.src=[],Ua=G.safeSrc=[],d=G.t={},ja=0,cr="[a-zA-Z0-9-]",Fa=[["\\s",1],["\\d",La],[cr,ka]],Ba=e=>{for(let[t,r]of Fa)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let o=Ba(t),n=ja++;Ma(e,n,t),d[e]=n,p[n]=t,Ua[n]=o,Da[n]=new RegExp(t,r?"g":void 0),_a[n]=new RegExp(o,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${cr}*`);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",`${cr}+`);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,${ar}})(?:\\.(\\d{1,${ar}}))?(?:\\.(\\d{1,${ar}}))?`);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);G.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);G.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);G.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 it=w((zd,Bo)=>{"use strict";var Wa=Object.freeze({loose:!0}),Ka=Object.freeze({}),qa=e=>e?typeof e!="object"?Wa:e:Ka;Bo.exports=qa});var lr=w((Yd,qo)=>{"use strict";var Wo=/^[0-9]+$/,Ko=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=Wo.test(e),o=Wo.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1},Ha=(e,t)=>Ko(t,e);qo.exports={compareIdentifiers:Ko,rcompareIdentifiers:Ha}});var T=w((Qd,Go)=>{"use strict";var at=De(),{MAX_LENGTH:Ho,MAX_SAFE_INTEGER:ct}=Me(),{safeRe:lt,t:ut}=we(),Ga=it(),{compareIdentifiers:ur}=lr(),pr=class e{constructor(t,r){if(r=Ga(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>Ho)throw new TypeError(`version is longer than ${Ho} characters`);at("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let o=t.trim().match(r.loose?lt[ut.LOOSE]:lt[ut.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>ct||this.major<0)throw new TypeError("Invalid major version");if(this.minor>ct||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>ct||this.patch<0)throw new TypeError("Invalid patch version");o[4]?this.prerelease=o[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let s=+n;if(s>=0&&s<ct)return s}return n}):this.prerelease=[],this.build=o[5]?o[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(at("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if(typeof t=="string"&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let o=this.prerelease[r],n=t.prerelease[r];if(at("prerelease compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return ur(o,n)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let o=this.build[r],n=t.build[r];if(at("build compare",r,o,n),o===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;if(o===n)continue;return ur(o,n)}while(++r)}inc(t,r,o){if(t.startsWith("pre")){if(!r&&o===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let n=`-${r}`.match(this.options.loose?lt[ut.PRERELEASELOOSE]:lt[ut.PRERELEASE]);if(!n||n[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,o);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,o);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,o),this.inc("pre",r,o);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,o),this.inc("pre",r,o);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let n=Number(o)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(r===this.prerelease.join(".")&&o===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(r){let s=[r,n];o===!1&&(s=[r]),ur(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Go.exports=pr});var pe=w((Zd,Jo)=>{"use strict";var Vo=T(),Va=(e,t,r=!1)=>{if(e instanceof Vo)return e;try{return new Vo(e,t)}catch(o){if(!r)return null;throw o}};Jo.exports=Va});var zo=w((em,Xo)=>{"use strict";var Ja=pe(),Xa=(e,t)=>{let r=Ja(e,t);return r?r.version:null};Xo.exports=Xa});var Qo=w((tm,Yo)=>{"use strict";var za=pe(),Ya=(e,t)=>{let r=za(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Yo.exports=Ya});var tn=w((rm,en)=>{"use strict";var Zo=T(),Qa=(e,t,r,o,n)=>{typeof r=="string"&&(n=o,o=r,r=void 0);try{return new Zo(e instanceof Zo?e.version:e,r).inc(t,o,n).version}catch{return null}};en.exports=Qa});var nn=w((om,on)=>{"use strict";var rn=pe(),Za=(e,t)=>{let r=rn(e,null,!0),o=rn(t,null,!0),n=r.compare(o);if(n===0)return null;let s=n>0,i=s?r:o,a=s?o:r,l=!!i.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}let f=l?"pre":"";return r.major!==o.major?f+"major":r.minor!==o.minor?f+"minor":r.patch!==o.patch?f+"patch":"prerelease"};on.exports=Za});var an=w((nm,sn)=>{"use strict";var ec=T(),tc=(e,t)=>new ec(e,t).major;sn.exports=tc});var ln=w((sm,cn)=>{"use strict";var rc=T(),oc=(e,t)=>new rc(e,t).minor;cn.exports=oc});var pn=w((im,un)=>{"use strict";var nc=T(),sc=(e,t)=>new nc(e,t).patch;un.exports=sc});var mn=w((am,dn)=>{"use strict";var ic=pe(),ac=(e,t)=>{let r=ic(e,t);return r&&r.prerelease.length?r.prerelease:null};dn.exports=ac});var D=w((cm,hn)=>{"use strict";var fn=T(),cc=(e,t,r)=>new fn(e,r).compare(new fn(t,r));hn.exports=cc});var yn=w((lm,gn)=>{"use strict";var lc=D(),uc=(e,t,r)=>lc(t,e,r);gn.exports=uc});var En=w((um,wn)=>{"use strict";var pc=D(),dc=(e,t)=>pc(e,t,!0);wn.exports=dc});var pt=w((pm,Rn)=>{"use strict";var Sn=T(),mc=(e,t,r)=>{let o=new Sn(e,r),n=new Sn(t,r);return o.compare(n)||o.compareBuild(n)};Rn.exports=mc});var Pn=w((dm,An)=>{"use strict";var fc=pt(),hc=(e,t)=>e.sort((r,o)=>fc(r,o,t));An.exports=hc});var In=w((mm,vn)=>{"use strict";var gc=pt(),yc=(e,t)=>e.sort((r,o)=>gc(o,r,t));vn.exports=yc});var _e=w((fm,bn)=>{"use strict";var wc=D(),Ec=(e,t,r)=>wc(e,t,r)>0;bn.exports=Ec});var dt=w((hm,Cn)=>{"use strict";var Sc=D(),Rc=(e,t,r)=>Sc(e,t,r)<0;Cn.exports=Rc});var dr=w((gm,Tn)=>{"use strict";var Ac=D(),Pc=(e,t,r)=>Ac(e,t,r)===0;Tn.exports=Pc});var mr=w((ym,On)=>{"use strict";var vc=D(),Ic=(e,t,r)=>vc(e,t,r)!==0;On.exports=Ic});var mt=w((wm,xn)=>{"use strict";var bc=D(),Cc=(e,t,r)=>bc(e,t,r)>=0;xn.exports=Cc});var ft=w((Em,$n)=>{"use strict";var Tc=D(),Oc=(e,t,r)=>Tc(e,t,r)<=0;$n.exports=Oc});var fr=w((Sm,Nn)=>{"use strict";var xc=dr(),$c=mr(),Nc=_e(),kc=mt(),Lc=dt(),Mc=ft(),Dc=(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 xc(e,r,o);case"!=":return $c(e,r,o);case">":return Nc(e,r,o);case">=":return kc(e,r,o);case"<":return Lc(e,r,o);case"<=":return Mc(e,r,o);default:throw new TypeError(`Invalid operator: ${t}`)}};Nn.exports=Dc});var Ln=w((Rm,kn)=>{"use strict";var _c=T(),Uc=pe(),{safeRe:ht,t:gt}=we(),jc=(e,t)=>{if(e instanceof _c)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?ht[gt.COERCEFULL]:ht[gt.COERCE]);else{let l=t.includePrerelease?ht[gt.COERCERTLFULL]:ht[gt.COERCERTL],u;for(;(u=l.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let o=r[2],n=r[3]||"0",s=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Uc(`${o}.${n}.${s}${i}${a}`,t)};kn.exports=jc});var Dn=w((Am,Mn)=>{"use strict";var hr=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(t,r)}return this}};Mn.exports=hr});var _=w((Pm,Fn)=>{"use strict";var Fc=/\s+/g,gr=class e{constructor(t,r){if(r=Wc(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof yr)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(Fc," "),this.set=this.raw.split("||").map(o=>this.parseRange(o.trim())).filter(o=>o.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let o=this.set[0];if(this.set=this.set.filter(n=>!Un(n[0])),this.set.length===0)this.set=[o];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&Xc(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let r=this.set[t];for(let o=0;o<r.length;o++)o>0&&(this.formatted+=" "),this.formatted+=r[o].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let o=((this.options.includePrerelease&&Vc)|(this.options.loose&&Jc))+":"+t,n=_n.get(o);if(n)return n;let s=this.options.loose,i=s?x[O.HYPHENRANGELOOSE]:x[O.HYPHENRANGE];t=t.replace(i,sl(this.options.includePrerelease)),v("hyphen replace",t),t=t.replace(x[O.COMPARATORTRIM],qc),v("comparator trim",t),t=t.replace(x[O.TILDETRIM],Hc),v("tilde trim",t),t=t.replace(x[O.CARETTRIM],Gc),v("caret trim",t);let a=t.split(" ").map(m=>zc(m,this.options)).join(" ").split(/\s+/).map(m=>nl(m,this.options));s&&(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 yr(m,this.options));for(let m of u){if(Un(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let f=[...l.values()];return _n.set(o,f),f}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(o=>jn(o,r)&&t.set.some(n=>jn(n,r)&&o.every(s=>n.every(i=>s.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new Kc(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(il(this.set[r],t,this.options))return!0;return!1}};Fn.exports=gr;var Bc=Dn(),_n=new Bc,Wc=it(),yr=Ue(),v=De(),Kc=T(),{safeRe:x,t:O,comparatorTrimReplace:qc,tildeTrimReplace:Hc,caretTrimReplace:Gc}=we(),{FLAG_INCLUDE_PRERELEASE:Vc,FLAG_LOOSE:Jc}=Me(),Un=e=>e.value==="<0.0.0-0",Xc=e=>e.value==="",jn=(e,t)=>{let r=!0,o=e.slice(),n=o.pop();for(;r&&o.length;)r=o.every(s=>n.intersects(s,t)),n=o.pop();return r},zc=(e,t)=>(e=e.replace(x[O.BUILD],""),v("comp",e,t),e=Zc(e,t),v("caret",e),e=Yc(e,t),v("tildes",e),e=tl(e,t),v("xrange",e),e=ol(e,t),v("stars",e),e),$=e=>!e||e.toLowerCase()==="x"||e==="*",Yc=(e,t)=>e.trim().split(/\s+/).map(r=>Qc(r,t)).join(" "),Qc=(e,t)=>{let r=t.loose?x[O.TILDELOOSE]:x[O.TILDE];return e.replace(r,(o,n,s,i,a)=>{v("tilde",e,o,n,s,i,a);let l;return $(n)?l="":$(s)?l=`>=${n}.0.0 <${+n+1}.0.0-0`:$(i)?l=`>=${n}.${s}.0 <${n}.${+s+1}.0-0`:a?(v("replaceTilde pr",a),l=`>=${n}.${s}.${i}-${a} <${n}.${+s+1}.0-0`):l=`>=${n}.${s}.${i} <${n}.${+s+1}.0-0`,v("tilde return",l),l})},Zc=(e,t)=>e.trim().split(/\s+/).map(r=>el(r,t)).join(" "),el=(e,t)=>{v("caret",e,t);let r=t.loose?x[O.CARETLOOSE]:x[O.CARET],o=t.includePrerelease?"-0":"";return e.replace(r,(n,s,i,a,l)=>{v("caret",e,n,s,i,a,l);let u;return $(s)?u="":$(i)?u=`>=${s}.0.0${o} <${+s+1}.0.0-0`:$(a)?s==="0"?u=`>=${s}.${i}.0${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${o} <${+s+1}.0.0-0`:l?(v("replaceCaret pr",l),s==="0"?i==="0"?u=`>=${s}.${i}.${a}-${l} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a}-${l} <${+s+1}.0.0-0`):(v("no pr"),s==="0"?i==="0"?u=`>=${s}.${i}.${a}${o} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}${o} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a} <${+s+1}.0.0-0`),v("caret return",u),u})},tl=(e,t)=>(v("replaceXRanges",e,t),e.split(/\s+/).map(r=>rl(r,t)).join(" ")),rl=(e,t)=>{e=e.trim();let r=t.loose?x[O.XRANGELOOSE]:x[O.XRANGE];return e.replace(r,(o,n,s,i,a,l)=>{v("xRange",e,o,n,s,i,a,l);let u=$(s),f=u||$(i),m=f||$(a),S=m;return n==="="&&S&&(n=""),l=t.includePrerelease?"-0":"",u?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&S?(f&&(i=0),a=0,n===">"?(n=">=",f?(s=+s+1,i=0,a=0):(i=+i+1,a=0)):n==="<="&&(n="<",f?s=+s+1:i=+i+1),n==="<"&&(l="-0"),o=`${n+s}.${i}.${a}${l}`):f?o=`>=${s}.0.0${l} <${+s+1}.0.0-0`:m&&(o=`>=${s}.${i}.0${l} <${s}.${+i+1}.0-0`),v("xRange return",o),o})},ol=(e,t)=>(v("replaceStars",e,t),e.trim().replace(x[O.STAR],"")),nl=(e,t)=>(v("replaceGTE0",e,t),e.trim().replace(x[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),sl=e=>(t,r,o,n,s,i,a,l,u,f,m,S)=>($(o)?r="":$(n)?r=`>=${o}.0.0${e?"-0":""}`:$(s)?r=`>=${o}.${n}.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()),il=(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!==yr.ANY&&e[o].semver.prerelease.length>0){let n=e[o].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}});var Ue=w((vm,Gn)=>{"use strict";var je=Symbol("SemVer ANY"),Sr=class e{static get ANY(){return je}constructor(t,r){if(r=Bn(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Er("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===je?this.value="":this.value=this.operator+this.semver.version,Er("comp",this)}parse(t){let r=this.options.loose?Wn[Kn.COMPARATORLOOSE]:Wn[Kn.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 qn(o[2],this.options.loose):this.semver=je}toString(){return this.value}test(t){if(Er("Comparator.test",t,this.options.loose),this.semver===je||t===je)return!0;if(typeof t=="string")try{t=new qn(t,this.options)}catch{return!1}return wr(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 Hn(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Hn(this.value,r).test(t.semver):(r=Bn(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("=")||wr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||wr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Gn.exports=Sr;var Bn=it(),{safeRe:Wn,t:Kn}=we(),wr=fr(),Er=De(),qn=T(),Hn=_()});var Fe=w((Im,Vn)=>{"use strict";var al=_(),cl=(e,t,r)=>{try{t=new al(t,r)}catch{return!1}return t.test(e)};Vn.exports=cl});var Xn=w((bm,Jn)=>{"use strict";var ll=_(),ul=(e,t)=>new ll(e,t).set.map(r=>r.map(o=>o.value).join(" ").trim().split(" "));Jn.exports=ul});var Yn=w((Cm,zn)=>{"use strict";var pl=T(),dl=_(),ml=(e,t,r)=>{let o=null,n=null,s=null;try{s=new dl(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===-1)&&(o=i,n=new pl(o,r))}),o};zn.exports=ml});var Zn=w((Tm,Qn)=>{"use strict";var fl=T(),hl=_(),gl=(e,t,r)=>{let o=null,n=null,s=null;try{s=new hl(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!o||n.compare(i)===1)&&(o=i,n=new fl(o,r))}),o};Qn.exports=gl});var rs=w((Om,ts)=>{"use strict";var Rr=T(),yl=_(),es=_e(),wl=(e,t)=>{e=new yl(e,t);let r=new Rr("0.0.0");if(e.test(r)||(r=new Rr("0.0.0-0"),e.test(r)))return r;r=null;for(let o=0;o<e.set.length;++o){let n=e.set[o],s=null;n.forEach(i=>{let a=new Rr(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||es(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||es(r,s))&&(r=s)}return r&&e.test(r)?r:null};ts.exports=wl});var ns=w((xm,os)=>{"use strict";var El=_(),Sl=(e,t)=>{try{return new El(e,t).range||"*"}catch{return null}};os.exports=Sl});var yt=w(($m,cs)=>{"use strict";var Rl=T(),as=Ue(),{ANY:Al}=as,Pl=_(),vl=Fe(),ss=_e(),is=dt(),Il=ft(),bl=mt(),Cl=(e,t,r,o)=>{e=new Rl(e,o),t=new Pl(t,o);let n,s,i,a,l;switch(r){case">":n=ss,s=Il,i=is,a=">",l=">=";break;case"<":n=is,s=bl,i=ss,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(vl(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===Al&&(h=new as(">=0.0.0")),m=m||h,S=S||h,n(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)&&s(e,S.semver))return!1;if(S.operator===l&&i(e,S.semver))return!1}return!0};cs.exports=Cl});var us=w((Nm,ls)=>{"use strict";var Tl=yt(),Ol=(e,t,r)=>Tl(e,t,">",r);ls.exports=Ol});var ds=w((km,ps)=>{"use strict";var xl=yt(),$l=(e,t,r)=>xl(e,t,"<",r);ps.exports=$l});var hs=w((Lm,fs)=>{"use strict";var ms=_(),Nl=(e,t,r)=>(e=new ms(e,r),t=new ms(t,r),e.intersects(t,r));fs.exports=Nl});var ys=w((Mm,gs)=>{"use strict";var kl=Fe(),Ll=D();gs.exports=(e,t,r)=>{let o=[],n=null,s=null,i=e.sort((f,m)=>Ll(f,m,r));for(let f of i)kl(f,t,r)?(s=f,n||(n=f)):(s&&o.push([n,s]),s=null,n=null);n&&o.push([n,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 Ps=w((Dm,As)=>{"use strict";var ws=_(),Pr=Ue(),{ANY:Ar}=Pr,Be=Fe(),vr=D(),Ml=(e,t,r={})=>{if(e===t)return!0;e=new ws(e,r),t=new ws(t,r);let o=!1;e:for(let n of e.set){for(let s of t.set){let i=_l(n,s,r);if(o=o||i!==null,i)continue e}if(o)return!1}return!0},Dl=[new Pr(">=0.0.0-0")],Es=[new Pr(">=0.0.0")],_l=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Ar){if(t.length===1&&t[0].semver===Ar)return!0;r.includePrerelease?e=Dl:e=Es}if(t.length===1&&t[0].semver===Ar){if(r.includePrerelease)return!0;t=Es}let o=new Set,n,s;for(let h of e)h.operator===">"||h.operator===">="?n=Ss(n,h,r):h.operator==="<"||h.operator==="<="?s=Rs(s,h,r):o.add(h.semver);if(o.size>1)return null;let i;if(n&&s){if(i=vr(n.semver,s.semver,r),i>0)return null;if(i===0&&(n.operator!==">="||s.operator!=="<="))return null}for(let h of o){if(n&&!Be(h,String(n),r)||s&&!Be(h,String(s),r))return null;for(let b of t)if(!Be(h,String(b),r))return!1;return!0}let a,l,u,f,m=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,S=n&&!r.includePrerelease&&n.semver.prerelease.length?n.semver:!1;m&&m.prerelease.length===1&&s.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let h of t){if(f=f||h.operator===">"||h.operator===">=",u=u||h.operator==="<"||h.operator==="<=",n){if(S&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===S.major&&h.semver.minor===S.minor&&h.semver.patch===S.patch&&(S=!1),h.operator===">"||h.operator===">="){if(a=Ss(n,h,r),a===h&&a!==n)return!1}else if(n.operator===">="&&!Be(n.semver,String(h),r))return!1}if(s){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=Rs(s,h,r),l===h&&l!==s)return!1}else if(s.operator==="<="&&!Be(s.semver,String(h),r))return!1}if(!h.operator&&(s||n)&&i!==0)return!1}return!(n&&u&&!s&&i!==0||s&&f&&!n&&i!==0||S||m)},Ss=(e,t,r)=>{if(!e)return t;let o=vr(e.semver,t.semver,r);return o>0?e:o<0||t.operator===">"&&e.operator===">="?t:e},Rs=(e,t,r)=>{if(!e)return t;let o=vr(e.semver,t.semver,r);return o<0?e:o>0||t.operator==="<"&&e.operator==="<="?t:e};As.exports=Ml});var br=w((_m,bs)=>{"use strict";var Ir=we(),vs=Me(),Ul=T(),Is=lr(),jl=pe(),Fl=zo(),Bl=Qo(),Wl=tn(),Kl=nn(),ql=an(),Hl=ln(),Gl=pn(),Vl=mn(),Jl=D(),Xl=yn(),zl=En(),Yl=pt(),Ql=Pn(),Zl=In(),eu=_e(),tu=dt(),ru=dr(),ou=mr(),nu=mt(),su=ft(),iu=fr(),au=Ln(),cu=Ue(),lu=_(),uu=Fe(),pu=Xn(),du=Yn(),mu=Zn(),fu=rs(),hu=ns(),gu=yt(),yu=us(),wu=ds(),Eu=hs(),Su=ys(),Ru=Ps();bs.exports={parse:jl,valid:Fl,clean:Bl,inc:Wl,diff:Kl,major:ql,minor:Hl,patch:Gl,prerelease:Vl,compare:Jl,rcompare:Xl,compareLoose:zl,compareBuild:Yl,sort:Ql,rsort:Zl,gt:eu,lt:tu,eq:ru,neq:ou,gte:nu,lte:su,cmp:iu,coerce:au,Comparator:cu,Range:lu,satisfies:uu,toComparators:pu,maxSatisfying:du,minSatisfying:mu,minVersion:fu,validRange:hu,outside:gu,gtr:yu,ltr:wu,intersects:Eu,simplifyRange:Su,subset:Ru,SemVer:Ul,re:Ir.re,src:Ir.src,tokens:Ir.t,SEMVER_SPEC_VERSION:vs.SEMVER_SPEC_VERSION,RELEASE_TYPES:vs.RELEASE_TYPES,compareIdentifiers:Is.compareIdentifiers,rcompareIdentifiers:Is.rcompareIdentifiers}});var dp={};Wi(dp,{handleError:()=>ki,main:()=>Ni,run:()=>Li});module.exports=Ki(dp);var be=require("@medplum/core"),Xe=require("commander"),$i=k(require("dotenv"),1);var Z=require("@medplum/core"),st=require("commander");var Gr=require("@medplum/core");var qr=require("@medplum/core"),J=require("node:fs"),Hr=require("node:os"),Ft=require("node:path");var W=class extends qr.ClientStorage{constructor(r){super();P(this,"dirName");P(this,"fileName");this.dirName=(0,Ft.resolve)((0,Hr.homedir)(),".medplum"),this.fileName=(0,Ft.resolve)(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,o){let n=this.readFile()??{};o?n[r]=o:delete n[r],this.writeFile(n)}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((0,J.existsSync)(this.fileName))return JSON.parse((0,J.readFileSync)(this.fileName,"utf8"))}writeFile(r){(0,J.existsSync)(this.dirName)||(0,J.mkdirSync)(this.dirName),(0,J.writeFileSync)(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function R(e,t=!0){let r=e.profile??"default",o=new W(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:s,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:f,clientSecret:m}=qi(e,o),S=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await Hi(e.baseUrl,S);let h=new Gr.MedplumClient({fetch:S,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:o,onUnauthenticated:Gi,verbose:e.verbose});return t&&(a?h.setAccessToken(a):f&&m&&(h.setBasicAuth(f,m),n?.authType!=="basic"&&await h.startClientLogin(f,m))),h}function qi(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,s=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,i=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,a=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,l=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,u=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:s,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}async function Hi(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 Gi(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var q=require("@medplum/core"),yo=require("commander");var Jr=require("node:buffer");var ie=new TextEncoder,Bt=new TextDecoder,wp=2**32;function Vr(...e){let t=e.reduce((n,{length:s})=>n+s,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}var ze=e=>Jr.Buffer.from(e).toString("base64url");var ae=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(ae,"code","ERR_JOSE_GENERIC");var M=class extends ae{constructor(){super(...arguments);P(this,"code","ERR_JOSE_NOT_SUPPORTED")}};P(M,"code","ERR_JOSE_NOT_SUPPORTED");var X=class extends ae{constructor(){super(...arguments);P(this,"code","ERR_JWS_INVALID")}};P(X,"code","ERR_JWS_INVALID");var Te=class extends ae{constructor(){super(...arguments);P(this,"code","ERR_JWT_INVALID")}};P(Te,"code","ERR_JWT_INVALID");var Xr,zr,Wt=class extends(zr=ae,Xr=Symbol.asyncIterator,zr){constructor(r="multiple matching keys found in the JSON Web Key Set",o){super(r,o);P(this,Xr);P(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};P(Wt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Yr=k(require("node:util"),1),Ye=e=>Yr.types.isKeyObject(e);var Qr=k(require("node:crypto"),1),Zr=k(require("node:util"),1),Ji=Qr.webcrypto,eo=Ji,fe=e=>Zr.types.isCryptoKey(e);function K(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Oe(e,t){return e.name===t}function Kt(e){return parseInt(e.name.slice(4),10)}function Xi(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function zi(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 to(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Oe(e.algorithm,"HMAC"))throw K("HMAC");let o=parseInt(t.slice(2),10);if(Kt(e.algorithm.hash)!==o)throw K(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Oe(e.algorithm,"RSASSA-PKCS1-v1_5"))throw K("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Kt(e.algorithm.hash)!==o)throw K(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Oe(e.algorithm,"RSA-PSS"))throw K("RSA-PSS");let o=parseInt(t.slice(2),10);if(Kt(e.algorithm.hash)!==o)throw K(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw K("Ed25519 or Ed448");break}case"Ed25519":{if(!Oe(e.algorithm,"Ed25519"))throw K("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Oe(e.algorithm,"ECDSA"))throw K("ECDSA");let o=Xi(t);if(e.algorithm.namedCurve!==o)throw K(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}zi(e,r)}function ro(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 xe=(e,...t)=>ro("Key must be ",e,...t);function qt(e,t,...r){return ro(`Key for the ${e} algorithm must be `,t,...r)}var Ht=e=>Ye(e)||fe(e),z=["KeyObject"];(globalThis.CryptoKey||eo?.CryptoKey)&&z.push("CryptoKey");var Yi=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let s of n){if(r.has(s))return!1;r.add(s)}}return!0},oo=Yi;function Qi(e){return typeof e=="object"&&e!==null}function $e(e){if(!Qi(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var co=require("node:crypto");function te(e){return $e(e)&&typeof e.kty=="string"}function no(e){return e.kty!=="oct"&&typeof e.d=="string"}function so(e){return e.kty!=="oct"&&typeof e.d>"u"}function io(e){return te(e)&&e.kty==="oct"&&typeof e.k=="string"}var Zi=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 M("Unsupported key curve for this operation")}},ea=(e,t)=>{let r;if(fe(e))r=co.KeyObject.from(e);else if(Ye(e))r=e;else{if(te(e))return e.crv;throw new TypeError(xe(e,...z))}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:Zi(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},lo=ea;var uo=require("node:crypto"),Gt=(e,t)=>{let r;try{e instanceof uo.KeyObject?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 he=e=>e?.[Symbol.toStringTag],Vt=(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},ta=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&te(t)){if(io(t)&&Vt(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(!Ht(t))throw new TypeError(qt(e,t,...z,"Uint8Array",o?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${he(t)} instances for symmetric algorithms must be of type "secret"`)}},ra=(e,t,r,o)=>{if(o&&te(t))switch(r){case"sign":if(no(t)&&Vt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(so(t)&&Vt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ht(t))throw new TypeError(qt(e,t,...z,o?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${he(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function po(e,t,r,o){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?ta(t,r,o,e):ra(t,r,o,e)}var Wp=po.bind(void 0,!1),mo=po.bind(void 0,!0);function oa(e,t,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(let i of o.crit){if(!s.has(i))throw new M(`Extension Header Parameter "${i}" is not recognized`);if(n[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s.get(i)&&o[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(o.crit)}var fo=oa;function Jt(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 M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Ne=require("node:crypto");var na=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Xt(e,t){let r,o,n;if(t instanceof Ne.KeyObject)r=t.asymmetricKeyType,o=t.asymmetricKeyDetails;else switch(n=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let s;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Gt(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");Gt(t,e),s={padding:Ne.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ne.constants.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=lo(t),a=na.get(e);if(i!==a)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${a}, got ${i}`);s={dsaEncoding:"ieee-p1363"};break}default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return n?{format:"jwk",key:t,...s}:s?{...s,key:t}:t}var Qe=k(require("node:crypto"),1),ho=require("node:util");function zt(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var ge=require("node:crypto");function Yt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(xe(t,...z));return(0,ge.createSecretKey)(t)}if(t instanceof ge.KeyObject)return t;if(fe(t))return to(t,e,r),ge.KeyObject.from(t);if(te(t))return e.startsWith("HS")?(0,ge.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError(xe(t,...z,"Uint8Array","JSON Web Key"))}var sa=(0,ho.promisify)(Qe.sign),ia=async(e,t,r)=>{let o=Yt(e,t,"sign");if(e.startsWith("HS")){let n=Qe.createHmac(zt(e),o);return n.update(r),n.digest()}return sa(Jt(e),r,Xt(e,o))},go=ia;var re=e=>Math.floor(e.getTime()/1e3);var aa=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ze=e=>{let t=aa.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),o=t[3].toLowerCase(),n;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*3600);break;case"day":case"days":case"d":n=Math.round(r*86400);break;case"week":case"weeks":case"w":n=Math.round(r*604800);break;default:n=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-n:n};var et=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 X("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!oo(this._protectedHeader,this._unprotectedHeader))throw new X("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=fo(X,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),s=!0;if(n.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new X('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=o;if(typeof i!="string"||!i)throw new X('JWS "alg" (Algorithm) Header Parameter missing or invalid');mo(i,t,"sign");let a=this._payload;s&&(a=ie.encode(ze(a)));let l;this._protectedHeader?l=ie.encode(ze(JSON.stringify(this._protectedHeader))):l=ie.encode("");let u=Vr(l,ie.encode("."),a),f=await go(i,t,u),m={signature:ze(f),payload:""};return s&&(m.payload=Bt.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=Bt.decode(l)),m}};var tt=class{constructor(t){P(this,"_flattened");this._flattened=new et(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function ce(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var rt=class{constructor(t={}){P(this,"_payload");if(!$e(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:ce("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:ce("setNotBefore",re(t))}:this._payload={...this._payload,nbf:re(new Date)+Ze(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:ce("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:ce("setExpirationTime",re(t))}:this._payload={...this._payload,exp:re(new Date)+Ze(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:re(new Date)}:t instanceof Date?this._payload={...this._payload,iat:ce("setIssuedAt",re(t))}:typeof t=="string"?this._payload={...this._payload,iat:ce("setIssuedAt",re(new Date)+Ze(t))}:this._payload={...this._payload,iat:ce("setIssuedAt",t)},this}};var ke=class extends rt{constructor(){super(...arguments);P(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new tt(ie.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new Te("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var ye=require("node:crypto"),oe=require("node:fs"),Y=require("node:path"),wo=require("node:util/types"),Eo=require("tar");function Q(e){console.log(JSON.stringify(e,null,2))}async function Qt(e,t,r){let o=t.source,n=ot(o);if(!n)return;console.log("Saving source code...");let s=await e.createAttachment({data:n,filename:(0,Y.basename)(o),contentType:ua(o)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:s});console.log("Success! New bot version: "+i.meta?.versionId)}async function Zt(e,t,r){let o=t.dist??t.source,n=ot(o);if(!n)return;console.log("Deploying bot...");let s=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,Y.basename)(o)});console.log("Deploy result: "+s.issue?.[0]?.details?.text)}async function er(e,t,r,o,n,s,i){let a={name:t,description:"",runtimeVersion:s},l=await e.post("admin/projects/"+r+"/bot",a),u=await e.readResource("Bot",l.id),f={name:t,id:l.id,source:o,dist:n};await Qt(e,f,u),await Zt(e,f,u),console.log(`Success! Bot created: ${u.id}`),i&&ca(f)}function So(e){let t=new RegExp("^"+la(e).replaceAll(String.raw`\*`,".*")+"$"),r=H()?.bots?.filter(o=>t.test(o.name));return r||[]}function j(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){(0,oe.writeFileSync)((0,Y.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function H(e,t){let r=j(e,t),o=ot(r);if(o)return JSON.parse(o)}function Ro(e){let t=ot(j(e,{server:!0}));if(t)return JSON.parse(t)}function ot(e){let t=(0,Y.resolve)(e);return(0,oe.existsSync)(t)?(0,oe.readFileSync)(t,"utf8"):""}function ca(e){let t=H()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,oe.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function la(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Ao(e){let o=0,n=0;return(0,Eo.extract)({cwd:e,filter:(s,i)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=i.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function tr(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function ua(e){let t=(0,Y.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?q.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?q.ContentType.TYPESCRIPT:q.ContentType.TEXT}function nt(e,t){let r=new W(e),o={name:e,...t};return r.setObject("options",o),o}function Po(e){return new W(e).getObject("options")}async function vo(e,t){let r={typ:"JWT",alg:q.OAuthSigningAlgorithm.HS256},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},s=(0,q.encodeBase64)(JSON.stringify(r)),i=(0,q.encodeBase64)(JSON.stringify(n)),a=`${s}.${i}`,l=(0,ye.createHmac)("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Io(e,t){let r=(0,ye.createPrivateKey)((0,oe.readFileSync)((0,Y.resolve)(t.privateKeyPath))),o=await new ke({}).setProtectedHeader({typ:"JWT",alg:q.OAuthSigningAlgorithm.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,ye.randomBytes)(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 yo.Command{action(t){let r=pa(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 pa(e,t){return async r=>{let o=e.registeredArguments.length,n=r.slice(0,o);n[o]=e.optsWithGlobals();try{let s=t(...n);(0,wo.isPromise)(s)&&await s}finally{e.resetOptionDefaults()}}}var bo=new g("status").aliases(["info","list","ls"]),Co=new g("ping"),To=new g("push"),Oo=new g("reload-config"),xo=new g("upgrade"),le=new g("agent");y(le,bo);y(le,Co);y(le,To);y(le,Oo);y(le,xo);bo.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 st.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await rr({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=fa(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"}}})});Co.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let o=await R(r),n=await $o(o,t,r),s=Number.parseInt(r.count,10);if(Number.isNaN(s))throw new Error("--count <count> must be an integer if specified");try{let i=await o.pushToAgent(n,e,`PING ${s}`,Z.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});To.description("Push a message to a target device via a specified agent").argument("<deviceId>","The ID of the device to push the message to").argument("<message>","The message to send to the destination device").argument("[agentId]","Conditionally optional ID of the agent to send the message from. Mutually exclusive with --criteria <criteria> option").option("--content-type <contentType>","The content type of the message",Z.ContentType.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,o)=>{let n=await R(o),s=await $o(n,r,o),i;try{i=await n.pushToAgent(s,{reference:`Device/${e}`},t,o.contentType,o.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});Oo.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 st.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await rr({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});xo.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 st.Option("--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 rr({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});async function rr({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:n}){let s=ga(t,r),i=await R(r),a=s.type==="criteria"?s.criteria:`Agent?_id=${s.ids.join(",")}`,l=new URLSearchParams(a.split("?")[1]);for(let[b,V]of Object.entries(o))l.append(b,V.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=da(u);for(let V of b)V.result.resourceType==="Parameters"||(0,Z.isOk)(V.result)?f.push(V):m.push(V);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 V=n(b);S.push(V)}let h=[];for(let b of m){let jt=b.result.issue?.[0],Mi={id:b.agent.id,name:b.agent.name,severity:jt.severity,code:jt.code,details:jt.details?.text??"No details to show"};h.push(Mi)}console.info(`
|
|
2
|
+
"use strict";var Ui=Object.create;var Ce=Object.defineProperty;var ji=Object.getOwnPropertyDescriptor;var Fi=Object.getOwnPropertyNames;var Bi=Object.getPrototypeOf,Wi=Object.prototype.hasOwnProperty;var Ki=(e,t,r)=>t in e?Ce(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),qi=(e,t)=>{for(var r in t)Ce(e,r,{get:t[r],enumerable:!0})},Hr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Fi(t))!Wi.call(e,s)&&s!==r&&Ce(e,s,{get:()=>t[s],enumerable:!(o=ji(t,s))||o.enumerable});return e};var L=(e,t,r)=>(r=e!=null?Ui(Bi(e)):{},Hr(t||!e||!e.__esModule?Ce(r,"default",{value:e,enumerable:!0}):r,e)),Hi=e=>Hr(Ce({},"__esModule",{value:!0}),e);var P=(e,t,r)=>Ki(e,typeof t!="symbol"?t+"":t,r);var Me=w((Yd,Fo)=>{"use strict";var Oa="2.0.0",xa=Number.MAX_SAFE_INTEGER||9007199254740991,$a=16,Na=250,La=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Fo.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:$a,MAX_SAFE_BUILD_LENGTH:Na,MAX_SAFE_INTEGER:xa,RELEASE_TYPES:La,SEMVER_SPEC_VERSION:Oa,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var De=w((Qd,Bo)=>{"use strict";var ka=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};Bo.exports=ka});var we=w((G,Wo)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:ar,MAX_SAFE_BUILD_LENGTH:Ma,MAX_LENGTH:Da}=Me(),_a=De();G=Wo.exports={};var Ua=G.re=[],ja=G.safeRe=[],p=G.src=[],Fa=G.safeSrc=[],d=G.t={},Ba=0,cr="[a-zA-Z0-9-]",Wa=[["\\s",1],["\\d",Da],[cr,Ma]],Ka=e=>{for(let[t,r]of Wa)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let o=Ka(t),s=Ba++;_a(e,s,t),d[e]=s,p[s]=t,Fa[s]=o,Ua[s]=new RegExp(t,r?"g":void 0),ja[s]=new RegExp(o,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${cr}*`);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",`${cr}+`);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,${ar}})(?:\\.(\\d{1,${ar}}))?(?:\\.(\\d{1,${ar}}))?`);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);G.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);G.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);G.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 it=w((Zd,Ko)=>{"use strict";var qa=Object.freeze({loose:!0}),Ha=Object.freeze({}),Ga=e=>e?typeof e!="object"?qa:e:Ha;Ko.exports=Ga});var lr=w((em,Go)=>{"use strict";var qo=/^[0-9]+$/,Ho=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=qo.test(e),o=qo.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1},Va=(e,t)=>Ho(t,e);Go.exports={compareIdentifiers:Ho,rcompareIdentifiers:Va}});var T=w((tm,Jo)=>{"use strict";var at=De(),{MAX_LENGTH:Vo,MAX_SAFE_INTEGER:ct}=Me(),{safeRe:lt,t:ut}=we(),Ja=it(),{compareIdentifiers:ur}=lr(),pr=class e{constructor(t,r){if(r=Ja(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>Vo)throw new TypeError(`version is longer than ${Vo} characters`);at("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let o=t.trim().match(r.loose?lt[ut.LOOSE]:lt[ut.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>ct||this.major<0)throw new TypeError("Invalid major version");if(this.minor>ct||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>ct||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<ct)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(at("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(at("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 ur(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(at("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 ur(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?lt[ut.PRERELEASELOOSE]:lt[ut.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]),ur(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}};Jo.exports=pr});var pe=w((rm,zo)=>{"use strict";var Xo=T(),Xa=(e,t,r=!1)=>{if(e instanceof Xo)return e;try{return new Xo(e,t)}catch(o){if(!r)return null;throw o}};zo.exports=Xa});var Qo=w((om,Yo)=>{"use strict";var za=pe(),Ya=(e,t)=>{let r=za(e,t);return r?r.version:null};Yo.exports=Ya});var es=w((sm,Zo)=>{"use strict";var Qa=pe(),Za=(e,t)=>{let r=Qa(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Zo.exports=Za});var os=w((nm,rs)=>{"use strict";var ts=T(),ec=(e,t,r,o,s)=>{typeof r=="string"&&(s=o,o=r,r=void 0);try{return new ts(e instanceof ts?e.version:e,r).inc(t,o,s).version}catch{return null}};rs.exports=ec});var is=w((im,ns)=>{"use strict";var ss=pe(),tc=(e,t)=>{let r=ss(e,null,!0),o=ss(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"};ns.exports=tc});var cs=w((am,as)=>{"use strict";var rc=T(),oc=(e,t)=>new rc(e,t).major;as.exports=oc});var us=w((cm,ls)=>{"use strict";var sc=T(),nc=(e,t)=>new sc(e,t).minor;ls.exports=nc});var ds=w((lm,ps)=>{"use strict";var ic=T(),ac=(e,t)=>new ic(e,t).patch;ps.exports=ac});var fs=w((um,ms)=>{"use strict";var cc=pe(),lc=(e,t)=>{let r=cc(e,t);return r&&r.prerelease.length?r.prerelease:null};ms.exports=lc});var D=w((pm,gs)=>{"use strict";var hs=T(),uc=(e,t,r)=>new hs(e,r).compare(new hs(t,r));gs.exports=uc});var ws=w((dm,ys)=>{"use strict";var pc=D(),dc=(e,t,r)=>pc(t,e,r);ys.exports=dc});var Ss=w((mm,Es)=>{"use strict";var mc=D(),fc=(e,t)=>mc(e,t,!0);Es.exports=fc});var pt=w((fm,As)=>{"use strict";var Rs=T(),hc=(e,t,r)=>{let o=new Rs(e,r),s=new Rs(t,r);return o.compare(s)||o.compareBuild(s)};As.exports=hc});var vs=w((hm,Ps)=>{"use strict";var gc=pt(),yc=(e,t)=>e.sort((r,o)=>gc(r,o,t));Ps.exports=yc});var Is=w((gm,bs)=>{"use strict";var wc=pt(),Ec=(e,t)=>e.sort((r,o)=>wc(o,r,t));bs.exports=Ec});var _e=w((ym,Cs)=>{"use strict";var Sc=D(),Rc=(e,t,r)=>Sc(e,t,r)>0;Cs.exports=Rc});var dt=w((wm,Ts)=>{"use strict";var Ac=D(),Pc=(e,t,r)=>Ac(e,t,r)<0;Ts.exports=Pc});var dr=w((Em,Os)=>{"use strict";var vc=D(),bc=(e,t,r)=>vc(e,t,r)===0;Os.exports=bc});var mr=w((Sm,xs)=>{"use strict";var Ic=D(),Cc=(e,t,r)=>Ic(e,t,r)!==0;xs.exports=Cc});var mt=w((Rm,$s)=>{"use strict";var Tc=D(),Oc=(e,t,r)=>Tc(e,t,r)>=0;$s.exports=Oc});var ft=w((Am,Ns)=>{"use strict";var xc=D(),$c=(e,t,r)=>xc(e,t,r)<=0;Ns.exports=$c});var fr=w((Pm,Ls)=>{"use strict";var Nc=dr(),Lc=mr(),kc=_e(),Mc=mt(),Dc=dt(),_c=ft(),Uc=(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 Nc(e,r,o);case"!=":return Lc(e,r,o);case">":return kc(e,r,o);case">=":return Mc(e,r,o);case"<":return Dc(e,r,o);case"<=":return _c(e,r,o);default:throw new TypeError(`Invalid operator: ${t}`)}};Ls.exports=Uc});var Ms=w((vm,ks)=>{"use strict";var jc=T(),Fc=pe(),{safeRe:ht,t:gt}=we(),Bc=(e,t)=>{if(e instanceof jc)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?ht[gt.COERCEFULL]:ht[gt.COERCE]);else{let l=t.includePrerelease?ht[gt.COERCERTLFULL]:ht[gt.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 Fc(`${o}.${s}.${n}${i}${a}`,t)};ks.exports=Bc});var _s=w((bm,Ds)=>{"use strict";var hr=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}};Ds.exports=hr});var _=w((Im,Bs)=>{"use strict";var Wc=/\s+/g,gr=class e{constructor(t,r){if(r=qc(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof yr)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(Wc," "),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=>!js(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&&Yc(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&&Xc)|(this.options.loose&&zc))+":"+t,s=Us.get(o);if(s)return s;let n=this.options.loose,i=n?$[O.HYPHENRANGELOOSE]:$[O.HYPHENRANGE];t=t.replace(i,al(this.options.includePrerelease)),v("hyphen replace",t),t=t.replace($[O.COMPARATORTRIM],Gc),v("comparator trim",t),t=t.replace($[O.TILDETRIM],Vc),v("tilde trim",t),t=t.replace($[O.CARETTRIM],Jc),v("caret trim",t);let a=t.split(" ").map(m=>Qc(m,this.options)).join(" ").split(/\s+/).map(m=>il(m,this.options));n&&(a=a.filter(m=>(v("loose invalid filter",m,this.options),!!m.match($[O.COMPARATORLOOSE])))),v("range list",a);let l=new Map,u=a.map(m=>new yr(m,this.options));for(let m of u){if(js(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=>Fs(o,r)&&t.set.some(s=>Fs(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 Hc(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(cl(this.set[r],t,this.options))return!0;return!1}};Bs.exports=gr;var Kc=_s(),Us=new Kc,qc=it(),yr=Ue(),v=De(),Hc=T(),{safeRe:$,t:O,comparatorTrimReplace:Gc,tildeTrimReplace:Vc,caretTrimReplace:Jc}=we(),{FLAG_INCLUDE_PRERELEASE:Xc,FLAG_LOOSE:zc}=Me(),js=e=>e.value==="<0.0.0-0",Yc=e=>e.value==="",Fs=(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},Qc=(e,t)=>(e=e.replace($[O.BUILD],""),v("comp",e,t),e=tl(e,t),v("caret",e),e=Zc(e,t),v("tildes",e),e=ol(e,t),v("xrange",e),e=nl(e,t),v("stars",e),e),N=e=>!e||e.toLowerCase()==="x"||e==="*",Zc=(e,t)=>e.trim().split(/\s+/).map(r=>el(r,t)).join(" "),el=(e,t)=>{let r=t.loose?$[O.TILDELOOSE]:$[O.TILDE];return e.replace(r,(o,s,n,i,a)=>{v("tilde",e,o,s,n,i,a);let l;return N(s)?l="":N(n)?l=`>=${s}.0.0 <${+s+1}.0.0-0`:N(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})},tl=(e,t)=>e.trim().split(/\s+/).map(r=>rl(r,t)).join(" "),rl=(e,t)=>{v("caret",e,t);let r=t.loose?$[O.CARETLOOSE]:$[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(n)?u="":N(i)?u=`>=${n}.0.0${o} <${+n+1}.0.0-0`:N(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})},ol=(e,t)=>(v("replaceXRanges",e,t),e.split(/\s+/).map(r=>sl(r,t)).join(" ")),sl=(e,t)=>{e=e.trim();let r=t.loose?$[O.XRANGELOOSE]:$[O.XRANGE];return e.replace(r,(o,s,n,i,a,l)=>{v("xRange",e,o,s,n,i,a,l);let u=N(n),h=u||N(i),m=h||N(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})},nl=(e,t)=>(v("replaceStars",e,t),e.trim().replace($[O.STAR],"")),il=(e,t)=>(v("replaceGTE0",e,t),e.trim().replace($[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),al=e=>(t,r,o,s,n,i,a,l,u,h,m,S)=>(N(o)?r="":N(s)?r=`>=${o}.0.0${e?"-0":""}`:N(n)?r=`>=${o}.${s}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,N(u)?l="":N(h)?l=`<${+u+1}.0.0-0`:N(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()),cl=(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!==yr.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 Ue=w((Cm,Vs)=>{"use strict";var je=Symbol("SemVer ANY"),Sr=class e{static get ANY(){return je}constructor(t,r){if(r=Ws(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Er("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===je?this.value="":this.value=this.operator+this.semver.version,Er("comp",this)}parse(t){let r=this.options.loose?Ks[qs.COMPARATORLOOSE]:Ks[qs.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 Hs(o[2],this.options.loose):this.semver=je}toString(){return this.value}test(t){if(Er("Comparator.test",t,this.options.loose),this.semver===je||t===je)return!0;if(typeof t=="string")try{t=new Hs(t,this.options)}catch{return!1}return wr(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 Gs(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Gs(this.value,r).test(t.semver):(r=Ws(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("=")||wr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||wr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Vs.exports=Sr;var Ws=it(),{safeRe:Ks,t:qs}=we(),wr=fr(),Er=De(),Hs=T(),Gs=_()});var Fe=w((Tm,Js)=>{"use strict";var ll=_(),ul=(e,t,r)=>{try{t=new ll(t,r)}catch{return!1}return t.test(e)};Js.exports=ul});var zs=w((Om,Xs)=>{"use strict";var pl=_(),dl=(e,t)=>new pl(e,t).set.map(r=>r.map(o=>o.value).join(" ").trim().split(" "));Xs.exports=dl});var Qs=w((xm,Ys)=>{"use strict";var ml=T(),fl=_(),hl=(e,t,r)=>{let o=null,s=null,n=null;try{n=new fl(t,r)}catch{return null}return e.forEach(i=>{n.test(i)&&(!o||s.compare(i)===-1)&&(o=i,s=new ml(o,r))}),o};Ys.exports=hl});var en=w(($m,Zs)=>{"use strict";var gl=T(),yl=_(),wl=(e,t,r)=>{let o=null,s=null,n=null;try{n=new yl(t,r)}catch{return null}return e.forEach(i=>{n.test(i)&&(!o||s.compare(i)===1)&&(o=i,s=new gl(o,r))}),o};Zs.exports=wl});var on=w((Nm,rn)=>{"use strict";var Rr=T(),El=_(),tn=_e(),Sl=(e,t)=>{e=new El(e,t);let r=new Rr("0.0.0");if(e.test(r)||(r=new Rr("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 Rr(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!n||tn(a,n))&&(n=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!r||tn(r,n))&&(r=n)}return r&&e.test(r)?r:null};rn.exports=Sl});var nn=w((Lm,sn)=>{"use strict";var Rl=_(),Al=(e,t)=>{try{return new Rl(e,t).range||"*"}catch{return null}};sn.exports=Al});var yt=w((km,un)=>{"use strict";var Pl=T(),ln=Ue(),{ANY:vl}=ln,bl=_(),Il=Fe(),an=_e(),cn=dt(),Cl=ft(),Tl=mt(),Ol=(e,t,r,o)=>{e=new Pl(e,o),t=new bl(t,o);let s,n,i,a,l;switch(r){case">":s=an,n=Cl,i=cn,a=">",l=">=";break;case"<":s=cn,n=Tl,i=an,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===vl&&(f=new ln(">=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};un.exports=Ol});var dn=w((Mm,pn)=>{"use strict";var xl=yt(),$l=(e,t,r)=>xl(e,t,">",r);pn.exports=$l});var fn=w((Dm,mn)=>{"use strict";var Nl=yt(),Ll=(e,t,r)=>Nl(e,t,"<",r);mn.exports=Ll});var yn=w((_m,gn)=>{"use strict";var hn=_(),kl=(e,t,r)=>(e=new hn(e,r),t=new hn(t,r),e.intersects(t,r));gn.exports=kl});var En=w((Um,wn)=>{"use strict";var Ml=Fe(),Dl=D();wn.exports=(e,t,r)=>{let o=[],s=null,n=null,i=e.sort((h,m)=>Dl(h,m,r));for(let h of i)Ml(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 bn=w((jm,vn)=>{"use strict";var Sn=_(),Pr=Ue(),{ANY:Ar}=Pr,Be=Fe(),vr=D(),_l=(e,t,r={})=>{if(e===t)return!0;e=new Sn(e,r),t=new Sn(t,r);let o=!1;e:for(let s of e.set){for(let n of t.set){let i=jl(s,n,r);if(o=o||i!==null,i)continue e}if(o)return!1}return!0},Ul=[new Pr(">=0.0.0-0")],Rn=[new Pr(">=0.0.0")],jl=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Ar){if(t.length===1&&t[0].semver===Ar)return!0;r.includePrerelease?e=Ul:e=Rn}if(t.length===1&&t[0].semver===Ar){if(r.includePrerelease)return!0;t=Rn}let o=new Set,s,n;for(let f of e)f.operator===">"||f.operator===">="?s=An(s,f,r):f.operator==="<"||f.operator==="<="?n=Pn(n,f,r):o.add(f.semver);if(o.size>1)return null;let i;if(s&&n){if(i=vr(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&&!Be(f,String(s),r)||n&&!Be(f,String(n),r))return null;for(let I of t)if(!Be(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=An(s,f,r),a===f&&a!==s)return!1}else if(s.operator===">="&&!Be(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=Pn(n,f,r),l===f&&l!==n)return!1}else if(n.operator==="<="&&!Be(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)},An=(e,t,r)=>{if(!e)return t;let o=vr(e.semver,t.semver,r);return o>0?e:o<0||t.operator===">"&&e.operator===">="?t:e},Pn=(e,t,r)=>{if(!e)return t;let o=vr(e.semver,t.semver,r);return o<0?e:o>0||t.operator==="<"&&e.operator==="<="?t:e};vn.exports=_l});var Ir=w((Fm,Tn)=>{"use strict";var br=we(),In=Me(),Fl=T(),Cn=lr(),Bl=pe(),Wl=Qo(),Kl=es(),ql=os(),Hl=is(),Gl=cs(),Vl=us(),Jl=ds(),Xl=fs(),zl=D(),Yl=ws(),Ql=Ss(),Zl=pt(),eu=vs(),tu=Is(),ru=_e(),ou=dt(),su=dr(),nu=mr(),iu=mt(),au=ft(),cu=fr(),lu=Ms(),uu=Ue(),pu=_(),du=Fe(),mu=zs(),fu=Qs(),hu=en(),gu=on(),yu=nn(),wu=yt(),Eu=dn(),Su=fn(),Ru=yn(),Au=En(),Pu=bn();Tn.exports={parse:Bl,valid:Wl,clean:Kl,inc:ql,diff:Hl,major:Gl,minor:Vl,patch:Jl,prerelease:Xl,compare:zl,rcompare:Yl,compareLoose:Ql,compareBuild:Zl,sort:eu,rsort:tu,gt:ru,lt:ou,eq:su,neq:nu,gte:iu,lte:au,cmp:cu,coerce:lu,Comparator:uu,Range:pu,satisfies:du,toComparators:mu,maxSatisfying:fu,minSatisfying:hu,minVersion:gu,validRange:yu,outside:wu,gtr:Eu,ltr:Su,intersects:Ru,simplifyRange:Au,subset:Pu,SemVer:Fl,re:br.re,src:br.src,tokens:br.t,SEMVER_SPEC_VERSION:In.SEMVER_SPEC_VERSION,RELEASE_TYPES:In.RELEASE_TYPES,compareIdentifiers:Cn.compareIdentifiers,rcompareIdentifiers:Cn.rcompareIdentifiers}});var hp={};qi(hp,{handleError:()=>Mi,main:()=>ki,run:()=>Di});module.exports=Hi(hp);var Ie=require("@medplum/core"),Xe=require("commander"),Li=L(require("dotenv"),1);var Z=require("@medplum/core"),nt=require("commander");var Jr=require("@medplum/core");var Gr=require("@medplum/core"),J=require("node:fs"),Vr=require("node:os"),Ft=require("node:path");var W=class extends Gr.ClientStorage{constructor(r){super();P(this,"dirName");P(this,"fileName");this.dirName=(0,Ft.resolve)((0,Vr.homedir)(),".medplum"),this.fileName=(0,Ft.resolve)(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((0,J.existsSync)(this.fileName))return JSON.parse((0,J.readFileSync)(this.fileName,"utf8"))}writeFile(r){(0,J.existsSync)(this.dirName)||(0,J.mkdirSync)(this.dirName),(0,J.writeFileSync)(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function A(e,t=!0){let r=e.profile??"default",o=new W(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}=Gi(e,o),S=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await Vi(e.baseUrl,S);let f=new Jr.MedplumClient({fetch:S,baseUrl:n,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:o,onUnauthenticated:Ji,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 Gi(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 Vi(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 Ji(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var q=require("@medplum/core"),Eo=require("commander");var zr=require("node:buffer");var ie=new TextEncoder,Bt=new TextDecoder,Rp=2**32;function Xr(...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 ze=e=>zr.Buffer.from(e).toString("base64url");var ae=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(ae,"code","ERR_JOSE_GENERIC");var M=class extends ae{constructor(){super(...arguments);P(this,"code","ERR_JOSE_NOT_SUPPORTED")}};P(M,"code","ERR_JOSE_NOT_SUPPORTED");var X=class extends ae{constructor(){super(...arguments);P(this,"code","ERR_JWS_INVALID")}};P(X,"code","ERR_JWS_INVALID");var Te=class extends ae{constructor(){super(...arguments);P(this,"code","ERR_JWT_INVALID")}};P(Te,"code","ERR_JWT_INVALID");var Yr,Qr,Wt=class extends(Qr=ae,Yr=Symbol.asyncIterator,Qr){constructor(r="multiple matching keys found in the JSON Web Key Set",o){super(r,o);P(this,Yr);P(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};P(Wt,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Zr=L(require("node:util"),1),Ye=e=>Zr.types.isKeyObject(e);var eo=L(require("node:crypto"),1),to=L(require("node:util"),1),zi=eo.webcrypto,ro=zi,fe=e=>to.types.isCryptoKey(e);function K(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Oe(e,t){return e.name===t}function Kt(e){return parseInt(e.name.slice(4),10)}function Yi(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Qi(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 oo(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Oe(e.algorithm,"HMAC"))throw K("HMAC");let o=parseInt(t.slice(2),10);if(Kt(e.algorithm.hash)!==o)throw K(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Oe(e.algorithm,"RSASSA-PKCS1-v1_5"))throw K("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Kt(e.algorithm.hash)!==o)throw K(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Oe(e.algorithm,"RSA-PSS"))throw K("RSA-PSS");let o=parseInt(t.slice(2),10);if(Kt(e.algorithm.hash)!==o)throw K(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw K("Ed25519 or Ed448");break}case"Ed25519":{if(!Oe(e.algorithm,"Ed25519"))throw K("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Oe(e.algorithm,"ECDSA"))throw K("ECDSA");let o=Yi(t);if(e.algorithm.namedCurve!==o)throw K(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Qi(e,r)}function so(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 xe=(e,...t)=>so("Key must be ",e,...t);function qt(e,t,...r){return so(`Key for the ${e} algorithm must be `,t,...r)}var Ht=e=>Ye(e)||fe(e),z=["KeyObject"];(globalThis.CryptoKey||ro?.CryptoKey)&&z.push("CryptoKey");var Zi=(...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},no=Zi;function ea(e){return typeof e=="object"&&e!==null}function $e(e){if(!ea(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var uo=require("node:crypto");function te(e){return $e(e)&&typeof e.kty=="string"}function io(e){return e.kty!=="oct"&&typeof e.d=="string"}function ao(e){return e.kty!=="oct"&&typeof e.d>"u"}function co(e){return te(e)&&e.kty==="oct"&&typeof e.k=="string"}var ta=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 M("Unsupported key curve for this operation")}},ra=(e,t)=>{let r;if(fe(e))r=uo.KeyObject.from(e);else if(Ye(e))r=e;else{if(te(e))return e.crv;throw new TypeError(xe(e,...z))}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:ta(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},po=ra;var mo=require("node:crypto"),Gt=(e,t)=>{let r;try{e instanceof mo.KeyObject?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 he=e=>e?.[Symbol.toStringTag],Vt=(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},oa=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&te(t)){if(co(t)&&Vt(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(!Ht(t))throw new TypeError(qt(e,t,...z,"Uint8Array",o?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${he(t)} instances for symmetric algorithms must be of type "secret"`)}},sa=(e,t,r,o)=>{if(o&&te(t))switch(r){case"sign":if(io(t)&&Vt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(ao(t)&&Vt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ht(t))throw new TypeError(qt(e,t,...z,o?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${he(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function fo(e,t,r,o){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?oa(t,r,o,e):sa(t,r,o,e)}var Hp=fo.bind(void 0,!1),ho=fo.bind(void 0,!0);function na(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 M(`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 go=na;function Jt(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 M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Ne=require("node:crypto");var ia=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Xt(e,t){let r,o,s;if(t instanceof Ne.KeyObject)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");Gt(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");Gt(t,e),n={padding:Ne.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ne.constants.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=po(t),a=ia.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 M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return s?{format:"jwk",key:t,...n}:n?{...n,key:t}:t}var Qe=L(require("node:crypto"),1),yo=require("node:util");function zt(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var ge=require("node:crypto");function Yt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(xe(t,...z));return(0,ge.createSecretKey)(t)}if(t instanceof ge.KeyObject)return t;if(fe(t))return oo(t,e,r),ge.KeyObject.from(t);if(te(t))return e.startsWith("HS")?(0,ge.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError(xe(t,...z,"Uint8Array","JSON Web Key"))}var aa=(0,yo.promisify)(Qe.sign),ca=async(e,t,r)=>{let o=Yt(e,t,"sign");if(e.startsWith("HS")){let s=Qe.createHmac(zt(e),o);return s.update(r),s.digest()}return aa(Jt(e),r,Xt(e,o))},wo=ca;var re=e=>Math.floor(e.getTime()/1e3);var la=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ze=e=>{let t=la.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 et=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 X("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!no(this._protectedHeader,this._unprotectedHeader))throw new X("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},s=go(X,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),n=!0;if(s.has("b64")&&(n=this._protectedHeader.b64,typeof n!="boolean"))throw new X('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=o;if(typeof i!="string"||!i)throw new X('JWS "alg" (Algorithm) Header Parameter missing or invalid');ho(i,t,"sign");let a=this._payload;n&&(a=ie.encode(ze(a)));let l;this._protectedHeader?l=ie.encode(ze(JSON.stringify(this._protectedHeader))):l=ie.encode("");let u=Xr(l,ie.encode("."),a),h=await wo(i,t,u),m={signature:ze(h),payload:""};return n&&(m.payload=Bt.decode(a)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=Bt.decode(l)),m}};var tt=class{constructor(t){P(this,"_flattened");this._flattened=new et(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function ce(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var rt=class{constructor(t={}){P(this,"_payload");if(!$e(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:ce("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:ce("setNotBefore",re(t))}:this._payload={...this._payload,nbf:re(new Date)+Ze(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:ce("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:ce("setExpirationTime",re(t))}:this._payload={...this._payload,exp:re(new Date)+Ze(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:re(new Date)}:t instanceof Date?this._payload={...this._payload,iat:ce("setIssuedAt",re(t))}:typeof t=="string"?this._payload={...this._payload,iat:ce("setIssuedAt",re(new Date)+Ze(t))}:this._payload={...this._payload,iat:ce("setIssuedAt",t)},this}};var Le=class extends rt{constructor(){super(...arguments);P(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let s=new tt(ie.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 Te("JWTs MUST NOT use unencoded payload");return s.sign(r,o)}};var ye=require("node:crypto"),oe=require("node:fs"),Y=require("node:path"),So=require("node:util/types"),Ro=require("tar");function Q(e){console.log(JSON.stringify(e,null,2))}async function Qt(e,t,r){let o=t.source,s=ot(o);if(!s)return;console.log("Saving source code...");let n=await e.createAttachment({data:s,filename:(0,Y.basename)(o),contentType:da(o)});console.log("Updating bot...");let i=await e.updateResource({...r,sourceCode:n});console.log("Success! New bot version: "+i.meta?.versionId)}async function Zt(e,t,r){let o=t.dist??t.source,s=ot(o);if(!s)return;console.log("Deploying bot...");let n=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:s,filename:(0,Y.basename)(o)});console.log("Deploy result: "+n.issue?.[0]?.details?.text)}async function er(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 Qt(e,h,u),await Zt(e,h,u),console.log(`Success! Bot created: ${u.id}`),i&&ua(h)}function Ao(e){let t=new RegExp("^"+pa(e).replaceAll(String.raw`\*`,".*")+"$"),r=H()?.bots?.filter(o=>t.test(o.name));return r||[]}function j(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){(0,oe.writeFileSync)((0,Y.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function H(e,t){let r=j(e,t),o=ot(r);if(o)return JSON.parse(o)}function Po(e){let t=ot(j(e,{server:!0}));if(t)return JSON.parse(t)}function ot(e){let t=(0,Y.resolve)(e);return(0,oe.existsSync)(t)?(0,oe.readFileSync)(t,"utf8"):""}function ua(e){let t=H()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,oe.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function pa(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function vo(e){let o=0,s=0;return(0,Ro.extract)({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 tr(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function da(e){let t=(0,Y.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?q.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?q.ContentType.TYPESCRIPT:q.ContentType.TEXT}function st(e,t){let r=new W(e),o={name:e,...t};return r.setObject("options",o),o}function bo(e){return new W(e).getObject("options")}async function Io(e,t){let r={typ:"JWT",alg:q.OAuthSigningAlgorithm.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=(0,q.encodeBase64)(JSON.stringify(r)),i=(0,q.encodeBase64)(JSON.stringify(s)),a=`${n}.${i}`,l=(0,ye.createHmac)("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Co(e,t){let r=(0,ye.createPrivateKey)((0,oe.readFileSync)((0,Y.resolve)(t.privateKeyPath))),o=await new Le({}).setProtectedHeader({typ:"JWT",alg:q.OAuthSigningAlgorithm.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,ye.randomBytes)(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 Eo.Command{action(t){let r=ma(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 ma(e,t){return async r=>{let o=e.registeredArguments.length,s=r.slice(0,o);s[o]=e.optsWithGlobals();try{let n=t(...s);(0,So.isPromise)(n)&&await n}finally{e.resetOptionDefaults()}}}var To=new g("status").aliases(["info","list","ls"]),Oo=new g("ping"),xo=new g("push"),$o=new g("reload-config"),No=new g("upgrade"),le=new g("agent");y(le,To);y(le,Oo);y(le,xo);y(le,$o);y(le,No);To.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.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await rr({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=ga(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 Lo(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}`,Z.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});xo.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",Z.ContentType.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 Lo(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)});$o.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.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await rr({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});No.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.Option("--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 rr({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});async function rr({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:s}){let n=wa(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,V]of Object.entries(o))l.append(I,V.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=fa(u);for(let V of I)V.result.resourceType==="Parameters"||(0,Z.isOk)(V.result)?h.push(V):m.push(V);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 V=s(I);S.push(V)}let f=[];for(let I of m){let jt=I.result.issue?.[0],_i={id:I.agent.id,name:I.agent.name,severity:jt.severity,code:jt.code,details:jt.details?.text??"No details to show"};f.push(_i)}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 Lo(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{ko(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 fa(e){let t=[];for(let r of e.entry??Z.EMPTY){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(ha(r.resource))}return t}function ha(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 ga(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=ya(n,i);r[n]=a}return r}function ya(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 wa(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(!(0,Z.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return ko(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function ko(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 `=`")})}var F=require("@medplum/core"),Mo=require("node:child_process"),Do=require("node:http"),_o=require("node:os");var Uo=F.MEDPLUM_CLI_CLIENT_ID,jo="http://localhost:9615",or=new g("login"),sr=new g("whoami"),nr=new g("token");or.action(async e=>{let t=e.profile??"default",r=st(t,e),o=await A(e,!1);await Ea(o,r)});sr.action(async e=>{let t=await A(e);Aa(t)});nr.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 Ea(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Pa(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 Io(e,t);break;case"jwt-assertion":await Co(e,t);break}}async function Sa(e){let t=(0,Do.createServer)(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":F.ContentType.TEXT}),o.end("OK");return}if(s.pathname==="/"&&n)try{let i=await e.processCode(n,{clientId:Uo,redirectUri:jo});o.writeHead(200,{"Content-Type":F.ContentType.TEXT}),o.end(`Signed in as ${(0,F.getDisplayString)(i)}. You may close this window.`)}catch(i){o.writeHead(400,{"Content-Type":F.ContentType.TEXT}),o.end(`Error: ${(0,F.normalizeErrorString)(i)}`)}finally{t.close(),process.exit(0)}else o.writeHead(404,{"Content-Type":F.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function Ra(e){let t=(0,_o.platform)(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}return new Promise((o,s)=>{(0,Mo.exec)(r,(n,i,a)=>{if(n){s(n);return}if(a){s(new Error("Could not open browser: "+a));return}o()})})}function Aa(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 Pa(e){await Sa(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Uo),t.searchParams.set("redirect_uri",jo),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Ra(t.toString())}var ke="\x1B[0m",va="\x1B[1m",ba="\x1B[31m",Ia="\x1B[32m",Ca="\x1B[33m",Ta="\x1B[34m",ue={red:e=>`${ba}${e}${ke}`,green:e=>`${Ia}${e}${ke}`,yellow:e=>`${Ca}${e}${ke}`,blue:e=>`${Ta}${e}${ke}`,bold:e=>`${va}${e}${ke}`},ir=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>ue.bold(r));var ee=require("@aws-sdk/client-cloudformation"),Pt=require("@aws-sdk/client-cloudfront"),$n=require("@aws-sdk/client-ecs"),Nn=require("@aws-sdk/client-s3"),Se=require("@aws-sdk/client-ssm"),vt=require("@aws-sdk/client-sts"),bt=require("@medplum/core"),Ln=L(require("node-fetch"),1),kn=require("node:fs"),Mn=L(Ir(),1);var On=L(require("node:readline"),1),wt;function Et(){wt=On.default.createInterface({input:process.stdin,output:process.stdout})}function St(){wt.close()}function c(e){wt.write(e+`
|
|
5
|
+
`)}function b(e){c(`
|
|
6
6
|
`+e+`
|
|
7
|
-
`)}function L(e,t=""){return new Promise(r=>{wt.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Rt(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await L(o)||r;if(t.includes(n))return n;c("Please choose one of the following options: "+t.join(", "))}}async function Ee(e,t,r){return Number.parseInt(await Rt(e,t.map(o=>o.toString()),r.toString()),10)}async function ne(e){return(await Rt(e,["y","n"])).toLowerCase()==="y"}async function We(e){if(!await ne(e))throw c("Exiting..."),new Error("User cancelled")}var At=new ee.CloudFormationClient({}),Au=new Pt.CloudFrontClient({region:"us-east-1"}),Bm=new Os.ECSClient({}),Ke=new xs.S3Client({}),Pu="medplum:environment";async function Cr(){let e=[],t=(0,ee.paginateListStacks)({client:At},{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??It.EMPTY)e.push(o);return e}async function Re(e){let t=await Cr();for(let r of t){let o=r.StackName,n=await Tr(o);if(n?.tag===e)return n}}async function Tr(e){let t={};if(await Ts(At,e,t),await At.config.region()!=="us-east-1")try{await Ts(new ee.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Ts(e,t,r){let o=new ee.DescribeStacksCommand({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===Pu);if(!i)return;let a=await e.send(new ee.DescribeStackResourcesCommand({StackName:t}));if(a.StackResources){e===At&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)vu(l,r)}}function vu(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 bt(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: ${Iu(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 Iu(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Ct(e){let t=await Au.send(new Pt.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Tt(e){let o=(await(await(0,$s.default)("https://api.github.com/repos/medplum/medplum/releases?per_page=100",{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})).json()).map(n=>n.tag_name.startsWith("v")?n.tag_name.slice(1):n.tag_name);return o.sort((n,s)=>ks.compare(s,n)),e?o.slice(0,o.indexOf(e)):o}async function Ot(e,t,r){let o=new Se.SSMClient({region:e});for(let[n,s]of Object.entries(r)){let i=t+n,a=s.toString(),l=await bu(o,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await We(`Do you want to overwrite "${i}"?`)),await Cu(o,i,a)}}async function bu(e,t){let r=new Se.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Cu(e,t,r){let o=new Se.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function se(e,t){if(console.log(`Config not found: ${e} (${j(e,t)})`),t){let o=Object.entries(t);if(o.length>0){console.log("Additional options:");for(let[n,s]of o)console.log(` ${n}: ${s}`)}}console.log();let r=(0,Ns.readdirSync)(".",{withFileTypes:!0});if(r=r.filter(o=>o.isFile()&&o.name.startsWith("medplum.")&&o.name.endsWith(".json")).map(o=>o.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let o of r)console.log(` ${o.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${o})`)}}async function Ae(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new vt.STSClient,r=new vt.GetCallerIdentityCommand({}),o=await t.send(r),n=await t.config.region();console.log("AWS Region: ",n),console.log("AWS Account ID: ",o.Account),console.log("AWS Account ARN: ",o.Arn),console.log("AWS User ID: ",o.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",(0,It.normalizeErrorString)(t))}}async function Ls(e){let t=await Re(e);if(!t)throw await Ae(e),new Error(`Stack not found: ${e}`);bt(t)}var de=require("@aws-sdk/client-acm"),xt=require("@aws-sdk/client-cloudfront"),$t=require("@aws-sdk/client-sts"),Ds=require("@medplum/core"),qe=require("node:crypto"),_s=require("node:fs");var Tu=e=>`${e}DomainName`,Us=e=>`${e}SslCertArn`;async function js(){let e={apiPort:8103,region:"us-east-1"};Et(),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 Ou(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 We("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 L("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 L("What is the config file name?",`medplum.${e.name}.config.json`);(0,_s.existsSync)(r)&&(c("Config file already exists."),await We("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 L("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 L("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 L("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 L("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 n=await L("Enter your support email address:");I("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await L("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 L("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 L("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 L("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 Ee("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 ne("Do you want to create a new RDS database as part of the CloudFormation stack?")?(c("Medplum will create a new RDS database as part of the CloudFormation stack."),c(""),c("If you need high availability, you can choose multiple instances."),c("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await Ee("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 Ee("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 Ee("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 Ee("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 s=(await Tt())[0]??"latest";e.serverImage=await L("Enter the server image:",`medplum/medplum-server:${s}`),C(r,e),I("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await ku(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 xu(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 $u(e,a,u,f);e[Us(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:n};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await ne("Do you want to store these values in AWS Parameter Store?"))await Ot(e.region,`/medplum/${e.name}/`,l);else{let u=j(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(""),St()}async function Ou(e){try{let t=new $t.STSClient({region:e}),r=new $t.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function xu(e){let t=await Ms(e);if(e!=="us-east-1"){let r=await Ms("us-east-1");t.push(...r)}return t}async function Ms(e){try{let t=new de.ACMClient({region:e}),r=new de.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function $u(e,t,r,o){let n=e[Tu(o)],s=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===n);if(s)return c(`Found existing certificate for "${n}" in "${r}.`),s.CertificateArn;if(c(`No existing certificate found for "${n}" in "${r}.`),!await ne("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${Us(o)}" setting.`),"TODO";let i=await Nu(r,n);return c("Certificate ARN: "+i),i}async function Nu(e,t){try{let r=await Rt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new de.ACMClient({region:e}),n=new de.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function ku(e,t){let r=(0,qe.randomUUID)(),o=(0,qe.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new xt.CloudFrontClient({region:e}).send(new xt.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,qe.randomUUID)(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",(0,Ds.normalizeErrorString)(n));return}}async function Fs(){let e=await Cr();for(let t of e){let r=t.StackName,o=await Tr(r);o&&(bt(o),console.log(""))}}var Bs=require("@aws-sdk/client-s3"),B=require("@medplum/core"),Ws=k(require("fast-glob"),1),Or=k(require("node-fetch"),1),U=require("node:fs"),Ks=require("node:os"),me=require("node:path"),qs=require("node:stream/promises");async function Hs(e,t){let r=H(e,t);if(!r)throw se(e,t),new Error(`Config not found: ${e}`);let o=await Re(e);if(!o)throw await Ae(e),new Error(`Stack not found: ${e}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${e}`);let s;if(t.tarPath)s=t.tarPath;else{let i=t?.toVersion??"latest";s=await Mu("@medplum/app",i)}Gs(s,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await _u(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Ct(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Lu(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Or.default)(r)).json()}async function Mu(e,t){let o=(await Lu(e,t)).dist.tarball,n=(0,U.mkdtempSync)((0,me.join)((0,Ks.tmpdir)(),"tarball-"));try{let s=await(0,Or.default)(o),i=Ao(n);return await(0,qs.pipeline)(s.body,i),(0,me.join)(n,"package","dist")}catch(s){throw(0,U.rmSync)(n,{recursive:!0,force:!0}),s}}function Gs(e,t){for(let r of(0,U.readdirSync)(e,{withFileTypes:!0})){let o=(0,me.join)(e,r.name);r.isDirectory()?Gs(o,t):r.isFile()&&o.endsWith(".js")&&Du(o,t)}}function Du(e,t){let r=(0,U.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,U.writeFileSync)(e,r)}async function _u(e,t,r){let o=[["assets/**/*.css",B.ContentType.CSS,!0],["assets/**/*.css.map",B.ContentType.JSON,!0],["assets/**/*.js",B.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",B.ContentType.JSON,!0],["assets/**/*.txt",B.ContentType.TEXT,!0],["assets/**/*.ico",B.ContentType.FAVICON,!0],["img/**/*.png",B.ContentType.PNG,!0],["img/**/*.svg",B.ContentType.SVG,!0],["robots.txt",B.ContentType.TEXT,!0],["index.html",B.ContentType.HTML,!1]];for(let n of o)await Uu({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Uu(e){let t=Ws.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await ju((0,me.join)(e.rootDir,r),e)}async function ju(e,t){let r=(0,U.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(me.sep).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await Ke.send(new Bs.PutObjectCommand(n))}var Nt=require("@aws-sdk/client-s3");async function Js(e,t){if(!H(e,t))throw se(e,t),new Error(`Config not found: ${e}`);let o=await Re(e);if(!o)throw await Ae(e),new Error(`Stack not found: ${e}`);await Vs("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Vs("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Vs(e,t,r,o,n){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let s=t.PhysicalResourceId,i=o.PhysicalResourceId,a=await Fu(s);if(Wu(a,s,i))throw new Error(`${e} bucket already has policy statement`);Ku(a,s,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Bu(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Ct(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Fu(e){let t=await Ke.send(new Nt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Bu(e,t){await Ke.send(new Nt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Wu(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 Ku(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 Xs(e,t){try{Et();let r=H(e,t);if(!r)throw se(e,t),new Error(`Config not found: ${e}`);let o=Ro(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=j(e,{server:!0});if(console.log(ue.yellow(`Config file ${n} not found!`)),!await ne("Do you want to proceed?")){console.log(ue.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}qu(r,o),Gu(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(ue.yellow("Dry run - skipping updates!")):(t.yes||await ne("Do you want to store these values in AWS Parameter Store?"))&&await Ot(r.region,`/medplum/${r.name}/`,o)}finally{St()}}function qu(e,t){kt(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),kt(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),kt(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),kt(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function kt(e,t,r){if(Hu(e,t))throw new Error(r)}function Hu(e,t){return e!==void 0&&t!==void 0&&e!==t}function Gu(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 Ys=require("node:child_process"),Pe=k(br(),1);async function Qs(e,t){let r=await R(t),o=H(e,t);if(!o)throw console.log(`Configuration file ${j(e)} not found`),se(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await Vu(r,o),a=await zs(i);for(;a;){if(t.toVersion&&Pe.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),o.serverImage=`${s}:${a}`,Ju(e,o),await r.startAsyncRequest("/admin/super/migrate"),a=await zs(a)}}async function Vu(e,t){let r=t.serverImage.lastIndexOf(":"),o=t.serverImage.slice(r+1);if(o==="latest"){o=(await e.get("/healthcheck")).version;let s=o.indexOf("-");s>-1&&(o=o.slice(0,s))}return o}async function zs(e,t){let r=await Tt(e),o=r[0];return r.filter(n=>n===o||n===t||Pe.gte(n,Pe.inc(e,"minor"))).pop()}function Ju(e,t){let r=j(e);C(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,Ys.spawnSync)(o,{stdio:"inherit"});if(n.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${n.status}): ${n.stderr}`);console.log(n.stdout)}function Zs(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(js),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Fs),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Ls),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(ir(`Update the AWS Parameter Store config values.
|
|
7
|
+
`)}function k(e,t=""){return new Promise(r=>{wt.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Rt(e,t,r=""){let o=e+" ["+t.map(s=>s===r?"("+s+")":s).join("|")+"]";for(;;){let s=await k(o)||r;if(t.includes(s))return s;c("Please choose one of the following options: "+t.join(", "))}}async function Ee(e,t,r){return Number.parseInt(await Rt(e,t.map(o=>o.toString()),r.toString()),10)}async function se(e){return(await Rt(e,["y","n"])).toLowerCase()==="y"}async function We(e){if(!await se(e))throw c("Exiting..."),new Error("User cancelled")}var At=new ee.CloudFormationClient({}),vu=new Pt.CloudFrontClient({region:"us-east-1"}),qm=new $n.ECSClient({}),Ke=new Nn.S3Client({}),bu="medplum:environment";async function Cr(){let e=[],t=(0,ee.paginateListStacks)({client:At},{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??bt.EMPTY)e.push(o);return e}async function Re(e){let t=await Cr();for(let r of t){let o=r.StackName,s=await Tr(o);if(s?.tag===e)return s}}async function Tr(e){let t={};if(await xn(At,e,t),await At.config.region()!=="us-east-1")try{await xn(new ee.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function xn(e,t,r){let o=new ee.DescribeStacksCommand({StackName:t}),n=(await e.send(o))?.Stacks?.[0],i=n?.Tags?.find(l=>l.Key===bu);if(!i)return;let a=await e.send(new ee.DescribeStackResourcesCommand({StackName:t}));if(a.StackResources){e===At&&(r.stack=n,r.tag=i.Value);for(let l of a.StackResources)Iu(l,r)}}function Iu(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 It(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: ${Cu(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 Cu(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Ct(e){let t=await vu.send(new Pt.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Tt(e){let o=(await(await(0,Ln.default)("https://api.github.com/repos/medplum/medplum/releases?per_page=100",{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})).json()).map(s=>s.tag_name.startsWith("v")?s.tag_name.slice(1):s.tag_name);return o.sort((s,n)=>Mn.compare(n,s)),e?o.slice(0,o.indexOf(e)):o}async function Ot(e,t,r){let o=new Se.SSMClient({region:e});for(let[s,n]of Object.entries(r)){let i=t+s,a=n.toString(),l=await Tu(o,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await We(`Do you want to overwrite "${i}"?`)),await Ou(o,i,a)}}async function Tu(e,t){let r=new Se.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Ou(e,t,r){let o=new Se.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function ne(e,t){if(console.log(`Config not found: ${e} (${j(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=(0,kn.readdirSync)(".",{withFileTypes:!0});if(r=r.filter(o=>o.isFile()&&o.name.startsWith("medplum.")&&o.name.endsWith(".json")).map(o=>o.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let o of r)console.log(` ${o.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${o})`)}}async function Ae(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new vt.STSClient,r=new vt.GetCallerIdentityCommand({}),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",(0,bt.normalizeErrorString)(t))}}async function Dn(e){let t=await Re(e);if(!t)throw await Ae(e),new Error(`Stack not found: ${e}`);It(t)}var de=require("@aws-sdk/client-acm"),xt=require("@aws-sdk/client-cloudfront"),$t=require("@aws-sdk/client-sts"),Un=require("@medplum/core"),qe=require("node:crypto"),jn=require("node:fs");var xu=e=>`${e}DomainName`,Fn=e=>`${e}SslCertArn`;async function Bn(){let e={apiPort:8103,region:"us-east-1"};Et(),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 We("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 k("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 k("What is the config file name?",`medplum.${e.name}.config.json`);(0,jn.existsSync)(r)&&(c("Config file already exists."),await We("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 k("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 k("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 k("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 k("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 k("Enter your support email address:");b("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await k("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 k("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 k("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 k("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 Ee("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 se("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 Ee("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 Ee("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 Ee("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 Ee("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 Tt())[0]??"latest";e.serverImage=await k("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 Mu(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 Nu(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:h}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let m=await Lu(e,a,u,h);e[Fn(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 se("Do you want to store these values in AWS Parameter Store?"))await Ot(e.region,`/medplum/${e.name}/`,l);else{let u=j(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(""),St()}async function $u(e){try{let t=new $t.STSClient({region:e}),r=new $t.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Nu(e){let t=await _n(e);if(e!=="us-east-1"){let r=await _n("us-east-1");t.push(...r)}return t}async function _n(e){try{let t=new de.ACMClient({region:e}),r=new de.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Lu(e,t,r,o){let s=e[xu(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 se("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${Fn(o)}" setting.`),"TODO";let i=await ku(r,s);return c("Certificate ARN: "+i),i}async function ku(e,t){try{let r=await Rt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new de.ACMClient({region:e}),s=new de.RequestCertificateCommand({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 Mu(e,t){let r=(0,qe.randomUUID)(),o=(0,qe.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new xt.CloudFrontClient({region:e}).send(new xt.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,qe.randomUUID)(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(s){console.log("Error: Unable to create signing key: ",(0,Un.normalizeErrorString)(s));return}}async function Wn(){let e=await Cr();for(let t of e){let r=t.StackName,o=await Tr(r);o&&(It(o),console.log(""))}}var Kn=require("@aws-sdk/client-s3"),B=require("@medplum/core"),qn=L(require("fast-glob"),1),Or=L(require("node-fetch"),1),U=require("node:fs"),Hn=require("node:os"),me=require("node:path"),Gn=require("node:stream/promises");async function Vn(e,t){let r=H(e,t);if(!r)throw ne(e,t),new Error(`Config not found: ${e}`);let o=await Re(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 _u("@medplum/app",i)}Jn(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 ju(n,s.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Ct(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Du(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Or.default)(r)).json()}async function _u(e,t){let o=(await Du(e,t)).dist.tarball,s=(0,U.mkdtempSync)((0,me.join)((0,Hn.tmpdir)(),"tarball-"));try{let n=await(0,Or.default)(o),i=vo(s);return await(0,Gn.pipeline)(n.body,i),(0,me.join)(s,"package","dist")}catch(n){throw(0,U.rmSync)(s,{recursive:!0,force:!0}),n}}function Jn(e,t){for(let r of(0,U.readdirSync)(e,{withFileTypes:!0})){let o=(0,me.join)(e,r.name);r.isDirectory()?Jn(o,t):r.isFile()&&o.endsWith(".js")&&Uu(o,t)}}function Uu(e,t){let r=(0,U.readFileSync)(e,"utf-8");for(let[o,s]of Object.entries(t))r=r.replaceAll(`__${o}__`,s);(0,U.writeFileSync)(e,r)}async function ju(e,t,r){let o=[["assets/**/*.css",B.ContentType.CSS,!0],["assets/**/*.css.map",B.ContentType.JSON,!0],["assets/**/*.js",B.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",B.ContentType.JSON,!0],["assets/**/*.txt",B.ContentType.TEXT,!0],["assets/**/*.ico",B.ContentType.FAVICON,!0],["img/**/*.png",B.ContentType.PNG,!0],["img/**/*.svg",B.ContentType.SVG,!0],["robots.txt",B.ContentType.TEXT,!0],["index.html",B.ContentType.HTML,!1]];for(let s of o)await Fu({rootDir:e,bucketName:t,fileNamePattern:s[0],contentType:s[1],cached:s[2],dryrun:r.dryrun})}async function Fu(e){let t=qn.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Bu((0,me.join)(e.rootDir,r),e)}async function Bu(e,t){let r=(0,U.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(me.sep).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 Ke.send(new Kn.PutObjectCommand(s))}var Nt=require("@aws-sdk/client-s3");async function zn(e,t){if(!H(e,t))throw ne(e,t),new Error(`Config not found: ${e}`);let o=await Re(e);if(!o)throw await Ae(e),new Error(`Stack not found: ${e}`);await Xn("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Xn("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Xn(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 Wu(n);if(qu(a,n,i))throw new Error(`${e} bucket already has policy statement`);Hu(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 Ku(n,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Ct(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Wu(e){let t=await Ke.send(new Nt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Ku(e,t){await Ke.send(new Nt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function qu(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 Hu(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 Yn(e,t){try{Et();let r=H(e,t);if(!r)throw ne(e,t),new Error(`Config not found: ${e}`);let o=Po(e)??{};if(!t.yes&&Object.keys(o).length===0){let s=j(e,{server:!0});if(console.log(ue.yellow(`Config file ${s} not found!`)),!await se("Do you want to proceed?")){console.log(ue.red(`Run Aborted, please ensure ${s} is present and try again.`));return}}Gu(r,o),Ju(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(ue.yellow("Dry run - skipping updates!")):(t.yes||await se("Do you want to store these values in AWS Parameter Store?"))&&await Ot(r.region,`/medplum/${r.name}/`,o)}finally{St()}}function Gu(e,t){Lt(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Lt(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Lt(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Lt(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Lt(e,t,r){if(Vu(e,t))throw new Error(r)}function Vu(e,t){return e!==void 0&&t!==void 0&&e!==t}function Ju(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 Zn=require("node:child_process"),Pe=L(Ir(),1);async function ei(e,t){let r=await A(t),o=H(e,t);if(!o)throw console.log(`Configuration file ${j(e)} not found`),ne(e,t),new Error(`Config not found: ${e}`);let s=o.serverImage.lastIndexOf(":"),n=o.serverImage.slice(0,s),i=await Xu(r,o),a=await Qn(i);for(;a;){if(t.toVersion&&Pe.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),o.serverImage=`${n}:${a}`,zu(e,o),await r.startAsyncRequest("/admin/super/migrate"),a=await Qn(a)}}async function Xu(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 Qn(e,t){let r=await Tt(e),o=r[0];return r.filter(s=>s===o||s===t||Pe.gte(s,Pe.inc(e,"minor"))).pop()}function zu(e,t){let r=j(e);C(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let s=(0,Zn.spawnSync)(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 ti(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Bn),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Wn),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Dn),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(ir(`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
|
-
`+ue.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",ir("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(
|
|
11
|
+
`+ue.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",ir("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(Yn),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(ei)),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(Vn),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(zn),e}var ri=new g("save"),oi=new g("deploy"),si=new g("create"),He=new g("bot");y(He,ri);y(He,oi);y(He,si);var xr=new g("save-bot"),$r=new g("deploy-bot"),Nr=new g("create-bot");ri.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await A(t);await kt(r,e)});oi.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await A(t);await kt(r,e,!0)});si.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 er(n,e,t,r,o,s.runtimeVersion,!!s.writeConfig)});async function kt(e,t,r=!1){let o=Ao(t),s=[],n=[],i=0,a=0;for(let l of o)try{let u=await e.readResource("Bot",l.id);await Qt(e,l,u),i++,r&&(await Zt(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
|
-
${
|
|
14
|
-
`)}`,{cause:n})}xr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await Lt(r,e)});$r.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await R(t);await Lt(r,e,!0)});Nr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let s=await R(n);await er(s,e,t,r,o)});var ni=require("@medplum/core"),Mt=require("node:fs"),kr=require("node:path"),si=require("node:readline");var ii=new g("export"),ai=new g("import"),Dt=new g("bulk");y(Dt,ii);y(Dt,ai);ii.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,s=await R(e);(await s.bulkExport(t,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:a,url:l})=>{let u=new URL(l),f=await s.download(l),m=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",S=(0,kr.resolve)(n??"",m);(0,Mt.writeFile)(`${S}`,await f.text(),()=>{console.log(`${S} is created`)})})});ai.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,s=(0,kr.resolve)(n??process.cwd(),e),i=await R(t);await Xu(s,Number.parseInt(r,10),i,o)});async function Xu(e,t,r,o){let n=[],s=(0,Mt.createReadStream)(e),i=(0,si.createInterface)({input:s});for await(let a of i){let l=zu(a,o);n.push({resource:l,request:{method:"POST",url:l.resourceType}}),n.length%t===0&&(await oi(n,r),n=[])}n.length>0&&await oi(n,r)}async function oi(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let o of r.entry??ni.EMPTY)Q(o.response)}function zu(e,t){let r=JSON.parse(e);return t?Yu(r):r}function Yu(e){return e.resourceType==="ExplanationOfBenefit"?Qu(e):e}function Qu(e){return e.provider||(e.provider=tr()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=tr())}),e}var _t=require("@medplum/core");var Ge=k(require("node:assert"),1),ui=require("node:net"),N=require("@medplum/core"),Lr=k(require("iconv-lite"),1),op=require("@medplum/core"),fi=require("@medplum/core"),hi=k(require("node:net"),1),Zu=Object.defineProperty,ep=(e,t,r)=>t in e?Zu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t,r)=>ep(e,typeof t!="symbol"?t+"":t,r),li=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var tp=class extends Event{constructor(e,t){super("message"),A(this,"connection"),A(this,"message"),this.connection=e,this.message=t}},rp=class extends Event{constructor(e,t){super("enhancedAckSent"),A(this,"connection"),A(this,"message"),this.connection=e,this.message=t}},Ve=class extends Event{constructor(e){super("error"),A(this,"error"),this.error=e}},pi=class extends Event{constructor(e){super("warning"),A(this,"error"),this.error=e}},Mr=class extends Event{constructor(){super("close")}},ci="utf-8",np=60*1e3,di=class extends li{constructor(e,t=ci,r,o={}){super(),A(this,"socket"),A(this,"encoding"),A(this,"enhancedMode"),A(this,"messagesPerMin"),A(this,"chunks",[]),A(this,"pendingMessages",new Map),A(this,"responseQueue",[]),A(this,"lastMessageDispatchedTime",0),A(this,"responseQueueProcessing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=o.messagesPerMin,e.on("data",n=>{try{this.appendData(n);let s=this.parseMessages();for(let i of s)this.responseQueue.push(new tp(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new Ve(i))})}catch(s){this.dispatchEvent(new Ve(s))}}),e.on("error",n=>{this.resetBuffer(),this.dispatchEvent(new Ve(n))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new Mr)}),this.addEventListener("message",n=>{let s;this.enhancedMode==="standard"?s=n.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(s=n.message.buildAck({ackCode:"AA"})),s&&(this.send(s),this.dispatchEvent(new rp(this,s)));let i=n.message.getSegment("MSA")?.getField(2)?.toString();if(!i)return;let a=this.pendingMessages.get(i);if(!a){this.dispatchEvent(new pi(new N.OperationOutcomeError({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=n.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();l&&(a.returnAck===N.ReturnAckCategory.APPLICATION&&l==="CA"||(a.resolve(n.message),this.pendingMessages.delete(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Lr.default.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=np/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await(0,N.sleep)(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 n=t.subarray(r,o+1).subarray(1,-2),s=Lr.default.decode(n,this.encoding),i=N.Hl7Message.parse(s);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 n=e.getSegment("MSH")?.getField(10)?.toString();if(!n){o(new N.OperationOutcomeError((0,N.validationError)("Required field missing: MSH.10")));return}let s;t?.timeoutMs&&(s=setTimeout(()=>{this.pendingMessages.delete(n),o(new N.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"error",code:"timeout",details:{text:"Client timeout"},diagnostics:`Request timed out after waiting ${t.timeoutMs} milliseconds for response`}]}))},t.timeoutMs)),this.pendingMessages.set(n,{message:e,resolve:r,reject:o,returnAck:t?.returnAck??N.ReturnAckCategory.APPLICATION,timer:s}),this.sendImpl(e)})}async close(){this.isClosed()||(this.socket.end(),this.socket.destroy(),this.drainPendingMessages(),await new Promise(e=>{this.socket.once("close",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 N.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Ve(new N.OperationOutcomeError({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??ci}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}},mi=class extends li{constructor(e){super(),A(this,"options"),A(this,"host"),A(this,"port"),A(this,"encoding"),A(this,"connection"),A(this,"keepAlive"),A(this,"socket"),A(this,"connectTimeout"),A(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=(0,ui.connect)({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){(0,Ge.default)(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){(0,Ge.default)(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let o;this.connection=o=new di(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(o),e.resolve(o)};t.on("connect",r)}registerSocketErrorListener(e){(0,Ge.default)(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){(0,Ge.default)(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 Mr)}),e.addEventListener("error",t=>{this.dispatchEvent(new Ve(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new pi(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 Mr);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},sp=1e4,gi=class{constructor(e){A(this,"handler"),A(this,"server"),A(this,"encoding"),A(this,"enhancedMode"),A(this,"messagesPerMin"),A(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 n=hi.default.createServer(s=>{let i=new di(s,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(i),this.connections.add(i),i.addEventListener("close",()=>{this.connections.delete(i)})});return new Promise((s,i)=>{let a=u=>{n.listen(u,()=>{let f=n.address().port;s(f)})},l=u=>{u?.code==="EADDRINUSE"?n.close(()=>(0,fi.sleep)(50).then(()=>a(e))):i(u)};n.on("error",l),n.once("listening",()=>{n.off("error",l)}),a(e),this.server=n})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let o;e?.forceDrainTimeoutMs!==-1&&(o=setTimeout(()=>{for(let n of this.connections)n.close().catch(console.error)},e?.forceDrainTimeoutMs??sp)),this.server.close(n=>{if(n){r(n);return}o&&clearTimeout(o),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}};var yi=require("node:fs");var ip=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=cp():o.file&&(r=(0,yi.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new mi({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let s=await n.sendAndWait(_t.Hl7Message.parse(r));console.log(s.toString().replaceAll("\r",`
|
|
15
|
-
`))}finally{await
|
|
16
|
-
`)),o.send(
|
|
13
|
+
${n.join(`
|
|
14
|
+
`)}`,{cause:s})}xr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await A(t);await kt(r,e)});$r.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await A(t);await kt(r,e,!0)});Nr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,s)=>{let n=await A(s);await er(n,e,t,r,o)});var Lr=require("@medplum/core"),Mt=require("node:fs"),kr=require("node:path"),ii=require("node:readline"),ai=require("node:stream"),ci=require("node:stream/promises");var li=new g("export"),ui=new g("import"),Dt=new g("bulk");y(Dt,li);y(Dt,ui);li.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??Lr.EMPTY){let u=new URL(l),h=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",m=(0,kr.resolve)(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=ai.Readable.fromWeb(S.body);await(0,ci.pipeline)(f,(0,Mt.createWriteStream)(m)),console.log(`${m} is created`)}});ui.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=(0,kr.resolve)(s??process.cwd(),e),i=await A(t);await Yu(n,Number.parseInt(r,10),i,o)});async function Yu(e,t,r,o){let s=[],n=(0,Mt.createReadStream)(e),i=(0,ii.createInterface)({input:n});for await(let a of i){let l=Qu(a,o);s.push({resource:l,request:{method:"POST",url:l.resourceType}}),s.length%t===0&&(await ni(s,r),s=[])}s.length>0&&await ni(s,r)}async function ni(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let o of r.entry??Lr.EMPTY)Q(o.response)}function Qu(e,t){let r=JSON.parse(e);return t?Zu(r):r}function Zu(e){return e.resourceType==="ExplanationOfBenefit"?ep(e):e}function ep(e){return e.provider||(e.provider=tr()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=tr())}),e}var _t=require("@medplum/core");var Ge=L(require("node:assert"),1),mi=require("node:net"),x=require("@medplum/core"),Mr=L(require("iconv-lite"),1),np=require("@medplum/core"),gi=require("@medplum/core"),yi=L(require("node:net"),1),tp=Object.defineProperty,rp=(e,t,r)=>t in e?tp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,R=(e,t,r)=>rp(e,typeof t!="symbol"?t+"":t,r),di=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var op=class extends Event{constructor(e,t){super("message"),R(this,"connection"),R(this,"message"),this.connection=e,this.message=t}},sp=class extends Event{constructor(e,t){super("enhancedAckSent"),R(this,"connection"),R(this,"message"),this.connection=e,this.message=t}},Ve=class extends Event{constructor(e){super("error"),R(this,"error"),this.error=e}},Dr=class extends Event{constructor(e){super("warning"),R(this,"error"),this.error=e}},_r=class extends Event{constructor(){super("close")}},pi="utf-8",ip=5e3,ap=60*1e3,fi=class extends di{constructor(e,t=pi,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??ip,e.on("data",s=>{if(this.closing){this.dispatchEvent(new Dr(new x.OperationOutcomeError({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 op(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new Ve(i))})}catch(n){this.dispatchEvent(new Ve(n))}}),e.on("error",s=>{this.resetBuffer(),this.dispatchEvent(new Ve(s))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new _r)}),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 sp(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 Dr(new x.OperationOutcomeError({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===x.ReturnAckCategory.APPLICATION&&l==="CA"||(a.resolve(s.message),this.pendingMessages.delete(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Mr.default.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=ap/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await(0,x.sleep)(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=Mr.default.decode(s,this.encoding),i=x.Hl7Message.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 x.OperationOutcomeError((0,x.validationError)("Required field missing: MSH.10")));return}let n;t?.timeoutMs&&(n=setTimeout(()=>{this.pendingMessages.delete(s),o(new x.OperationOutcomeError({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??x.ReturnAckCategory.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 x.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Ve(new x.OperationOutcomeError({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??pi}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}},hi=class extends di{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=(0,mi.connect)({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){(0,Ge.default)(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){(0,Ge.default)(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let o;this.connection=o=new fi(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(o),e.resolve(o)};t.on("connect",r)}registerSocketErrorListener(e){(0,Ge.default)(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){(0,Ge.default)(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 _r)}),e.addEventListener("error",t=>{this.dispatchEvent(new Ve(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new Dr(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 _r);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},cp=1e4,wi=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=yi.default.createServer(n=>{let i=new fi(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(()=>(0,gi.sleep)(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??cp)),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}};var Ei=require("node:fs");var lp=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=pp():o.file&&(r=(0,Ei.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let s=new hi({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let n=await s.sendAndWait(_t.Hl7Message.parse(r));console.log(n.toString().replaceAll("\r",`
|
|
15
|
+
`))}finally{await s.close()}}),up=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 wi(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)}),Ut=new g("hl7");y(Ut,lp);y(Ut,up);function pp(){let e=(0,_t.formatHl7DateTime)(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|`}var
|
|
19
|
+
PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var Si=require("node:fs"),Ri=require("node:os"),Ai=require("node:path");var Pi=new g("set"),vi=new g("remove"),bi=new g("list"),Ii=new g("describe"),ve=new g("profile");y(ve,Pi);y(ve,vi);y(ve,bi);y(ve,Ii);Pi.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)=>{st(e,t)});vi.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new W(e).setObject("options",void 0),console.log(`${e} profile removed`)});bi.description("List all profiles saved").action(async()=>{let e=(0,Ai.resolve)((0,Ri.homedir)(),".medplum"),t=(0,Si.readdirSync)(e),r=[];t.forEach(o=>{let s=o.split(".")[0],i=new W(s).getObject("options");i&&r.push({profileName:s,profile:i})}),console.log(r)});Ii.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=bo(e);console.log(t)});var Ci=require("commander");var Ti=new g("list"),Oi=new g("current"),xi=new g("switch"),$i=new g("invite"),be=new g("project");y(be,Ti);y(be,Oi);y(be,xi);y(be,$i);Ti.description("List of current projects").action(async e=>{let t=await A(e);dp(t)});function dp(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
|
|
20
20
|
|
|
21
|
-
`);console.log(r)}
|
|
22
|
-
`)}async function
|
|
23
|
-
`):process.stderr.write(`Error: ${(0,
|
|
24
|
-
`)}async function
|
|
21
|
+
`);console.log(r)}Oi.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})`)});xi.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await A(t);await mp(r,e)});$i.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 Ci.Option("-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 fp(i,a,s)});async function mp(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 fp(e,t,r){await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var Ni=require("@medplum/core");var Ur=new g("delete"),jr=new g("get"),Fr=new g("patch"),Br=new g("post"),Wr=new g("put");Ur.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await A(t);Q(await r.delete(Je(r,e)))});jr.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(Je(r,e));t.asTransaction?Q((0,Ni.convertToTransactionBundle)(o)):Q(o)});Fr.arguments("<url> <body>").action(async(e,t,r)=>{let o=await A(r);Q(await o.patch(Je(o,e),Kr(t)))});Br.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;Q(await o.post(Je(o,e),Kr(t),void 0,{headers:s}))});Wr.arguments("<url> <body>").action(async(e,t,r)=>{let o=await A(r);Q(await o.put(Je(o,e),Kr(t)))});function Kr(e){if(e)try{return JSON.parse(e)}catch{return e}}function Je(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function ki(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 Xe.Option("--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(Ie.MEDPLUM_VERSION),t.configureHelp({showGlobalOptions:!0}),y(t,or),y(t,sr),y(t,nr),y(t,jr),y(t,Br),y(t,Fr),y(t,Wr),y(t,Ur),y(t,be),y(t,Dt),y(t,He),y(t,le),y(t,xr),y(t,$r),y(t,Nr),y(t,ve),y(t,ti()),y(t,Ut);try{await t.parseAsync(e)}catch(r){Mi(r)}}function Mi(e){let t=1,r=!0;if(e instanceof Xe.CommanderError&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){qr(e,!!process.env.VERBOSE);let o=e.cause;if(process.env.VERBOSE)if(Array.isArray(o))for(let s of o)qr(s,!0);else o instanceof Error&&qr(o,!0)}process.exit(t)}function qr(e,t=!1){if(t){console.error(e);return}e instanceof Xe.CommanderError?process.stderr.write(`${(0,Ie.normalizeErrorString)(e)}
|
|
23
|
+
`):process.stderr.write(`Error: ${(0,Ie.normalizeErrorString)(e)}
|
|
24
|
+
`)}async function Di(){Li.default.config({quiet:!0}),await ki(process.argv)}Di().catch(e=>{console.error("Unhandled error:",(0,Ie.normalizeErrorString)(e)),process.exit(1)});0&&(module.exports={handleError,main,run});
|
|
25
25
|
//# sourceMappingURL=index.cjs.map
|