@medplum/cli 5.1.40 → 5.1.41
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 +7 -7
- package/dist/cjs/index.cjs.map +3 -3
- package/dist/esm/index.mjs +2 -2
- package/dist/esm/index.mjs.map +3 -3
- package/package.json +5 -6
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var ta=Object.create;var Ce=Object.defineProperty;var ra=Object.getOwnPropertyDescriptor;var na=Object.getOwnPropertyNames;var oa=Object.getPrototypeOf,sa=Object.prototype.hasOwnProperty;var qr=e=>{throw TypeError(e)};var ia=(e,t,r)=>t in e?Ce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},aa=(e,t)=>{for(var r in t)Ce(e,r,{get:t[r],enumerable:!0})},Wr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of na(t))!sa.call(e,o)&&o!==r&&Ce(e,o,{get:()=>t[o],enumerable:!(n=ra(t,o))||n.enumerable});return e};var H=(e,t,r)=>(r=e!=null?ta(oa(e)):{},Wr(t||!e||!e.__esModule?Ce(r,"default",{value:e,enumerable:!0}):r,e)),ca=e=>Wr(Ce({},"__esModule",{value:!0}),e);var N=(e,t,r)=>ia(e,typeof t!="symbol"?t+"":t,r),Gr=(e,t,r)=>t.has(e)||qr("Cannot "+r);var Ut=(e,t,r)=>(Gr(e,t,"read from private field"),r?r.call(e):t.get(e)),Kr=(e,t,r)=>t.has(e)?qr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Vr=(e,t,r,n)=>(Gr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var he=w((rm,Xn)=>{"use strict";var Qa="2.0.0",Za=Number.MAX_SAFE_INTEGER||9007199254740991,ec=16,tc=250,rc=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Xn.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ec,MAX_SAFE_BUILD_LENGTH:tc,MAX_SAFE_INTEGER:Za,RELEASE_TYPES:rc,SEMVER_SPEC_VERSION:Qa,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Me=w((nm,zn)=>{"use strict";var nc=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};zn.exports=nc});var ye=w((z,Yn)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:nr,MAX_SAFE_BUILD_LENGTH:oc,MAX_LENGTH:sc}=he(),ic=Me();z=Yn.exports={};var ac=z.re=[],cc=z.safeRe=[],m=z.src=[],lc=z.safeSrc=[],f=z.t={},uc=0,or="[a-zA-Z0-9-]",pc=[["\\s",1],["\\d",sc],[or,oc]],dc=e=>{for(let[t,r]of pc)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},S=(e,t,r)=>{let n=dc(t),o=uc++;ic(e,o,t),f[e]=o,m[o]=t,lc[o]=n,ac[o]=new RegExp(t,r?"g":void 0),cc[o]=new RegExp(n,r?"g":void 0)};S("NUMERICIDENTIFIER","0|[1-9]\\d*");S("NUMERICIDENTIFIERLOOSE","\\d+");S("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${or}*`);S("MAINVERSION",`(${m[f.NUMERICIDENTIFIER]})\\.(${m[f.NUMERICIDENTIFIER]})\\.(${m[f.NUMERICIDENTIFIER]})`);S("MAINVERSIONLOOSE",`(${m[f.NUMERICIDENTIFIERLOOSE]})\\.(${m[f.NUMERICIDENTIFIERLOOSE]})\\.(${m[f.NUMERICIDENTIFIERLOOSE]})`);S("PRERELEASEIDENTIFIER",`(?:${m[f.NONNUMERICIDENTIFIER]}|${m[f.NUMERICIDENTIFIER]})`);S("PRERELEASEIDENTIFIERLOOSE",`(?:${m[f.NONNUMERICIDENTIFIER]}|${m[f.NUMERICIDENTIFIERLOOSE]})`);S("PRERELEASE",`(?:-(${m[f.PRERELEASEIDENTIFIER]}(?:\\.${m[f.PRERELEASEIDENTIFIER]})*))`);S("PRERELEASELOOSE",`(?:-?(${m[f.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${m[f.PRERELEASEIDENTIFIERLOOSE]})*))`);S("BUILDIDENTIFIER",`${or}+`);S("BUILD",`(?:\\+(${m[f.BUILDIDENTIFIER]}(?:\\.${m[f.BUILDIDENTIFIER]})*))`);S("FULLPLAIN",`v?${m[f.MAINVERSION]}${m[f.PRERELEASE]}?${m[f.BUILD]}?`);S("FULL",`^${m[f.FULLPLAIN]}$`);S("LOOSEPLAIN",`[v=\\s]*${m[f.MAINVERSIONLOOSE]}${m[f.PRERELEASELOOSE]}?${m[f.BUILD]}?`);S("LOOSE",`^${m[f.LOOSEPLAIN]}$`);S("GTLT","((?:<|>)?=?)");S("XRANGEIDENTIFIERLOOSE",`${m[f.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);S("XRANGEIDENTIFIER",`${m[f.NUMERICIDENTIFIER]}|x|X|\\*`);S("XRANGEPLAIN",`[v=\\s]*(${m[f.XRANGEIDENTIFIER]})(?:\\.(${m[f.XRANGEIDENTIFIER]})(?:\\.(${m[f.XRANGEIDENTIFIER]})(?:${m[f.PRERELEASE]})?${m[f.BUILD]}?)?)?`);S("XRANGEPLAINLOOSE",`[v=\\s]*(${m[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${m[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${m[f.XRANGEIDENTIFIERLOOSE]})(?:${m[f.PRERELEASELOOSE]})?${m[f.BUILD]}?)?)?`);S("XRANGE",`^${m[f.GTLT]}\\s*${m[f.XRANGEPLAIN]}$`);S("XRANGELOOSE",`^${m[f.GTLT]}\\s*${m[f.XRANGEPLAINLOOSE]}$`);S("COERCEPLAIN",`(^|[^\\d])(\\d{1,${nr}})(?:\\.(\\d{1,${nr}}))?(?:\\.(\\d{1,${nr}}))?`);S("COERCE",`${m[f.COERCEPLAIN]}(?:$|[^\\d])`);S("COERCEFULL",m[f.COERCEPLAIN]+`(?:${m[f.PRERELEASE]})?(?:${m[f.BUILD]})?(?:$|[^\\d])`);S("COERCERTL",m[f.COERCE],!0);S("COERCERTLFULL",m[f.COERCEFULL],!0);S("LONETILDE","(?:~>?)");S("TILDETRIM",`(\\s*)${m[f.LONETILDE]}\\s+`,!0);z.tildeTrimReplace="$1~";S("TILDE",`^${m[f.LONETILDE]}${m[f.XRANGEPLAIN]}$`);S("TILDELOOSE",`^${m[f.LONETILDE]}${m[f.XRANGEPLAINLOOSE]}$`);S("LONECARET","(?:\\^)");S("CARETTRIM",`(\\s*)${m[f.LONECARET]}\\s+`,!0);z.caretTrimReplace="$1^";S("CARET",`^${m[f.LONECARET]}${m[f.XRANGEPLAIN]}$`);S("CARETLOOSE",`^${m[f.LONECARET]}${m[f.XRANGEPLAINLOOSE]}$`);S("COMPARATORLOOSE",`^${m[f.GTLT]}\\s*(${m[f.LOOSEPLAIN]})$|^$`);S("COMPARATOR",`^${m[f.GTLT]}\\s*(${m[f.FULLPLAIN]})$|^$`);S("COMPARATORTRIM",`(\\s*)${m[f.GTLT]}\\s*(${m[f.LOOSEPLAIN]}|${m[f.XRANGEPLAIN]})`,!0);z.comparatorTrimReplace="$1$2$3";S("HYPHENRANGE",`^\\s*(${m[f.XRANGEPLAIN]})\\s+-\\s+(${m[f.XRANGEPLAIN]})\\s*$`);S("HYPHENRANGELOOSE",`^\\s*(${m[f.XRANGEPLAINLOOSE]})\\s+-\\s+(${m[f.XRANGEPLAINLOOSE]})\\s*$`);S("STAR","(<|>)?=?\\s*\\*");S("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");S("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var rt=w((om,Qn)=>{"use strict";var mc=Object.freeze({loose:!0}),fc=Object.freeze({}),gc=e=>e?typeof e!="object"?mc:e:fc;Qn.exports=gc});var sr=w((sm,to)=>{"use strict";var Zn=/^[0-9]+$/,eo=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=Zn.test(e),n=Zn.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},hc=(e,t)=>eo(t,e);to.exports={compareIdentifiers:eo,rcompareIdentifiers:hc}});var T=w((im,no)=>{"use strict";var nt=Me(),{MAX_LENGTH:ro,MAX_SAFE_INTEGER:ot}=he(),{safeRe:st,t:it}=ye(),yc=rt(),{compareIdentifiers:ir}=sr(),wc=(e,t)=>{let r=t.split(".");if(r.length>e.length)return!1;for(let n=0;n<r.length;n++)if(ir(e[n],r[n])!==0)return!1;return!0},ar=class e{constructor(t,r){if(r=yc(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>ro)throw new TypeError(`version is longer than ${ro} characters`);nt("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?st[it.LOOSE]:st[it.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>ot||this.major<0)throw new TypeError("Invalid major version");if(this.minor>ot||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>ot||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){let s=+o;if(s>=0&&s<ot)return s}return o}):this.prerelease=[],this.build=n[5]?n[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(nt("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 n=this.prerelease[r],o=t.prerelease[r];if(nt("prerelease compare",r,n,o),n===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(n===void 0)return-1;if(n===o)continue;return ir(n,o)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],o=t.build[r];if(nt("build compare",r,n,o),n===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(n===void 0)return-1;if(n===o)continue;return ir(n,o)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let o=`-${r}`.match(this.options.loose?st[it.PRERELEASELOOSE]:st[it.PRERELEASE]);if(!o||o[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,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);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 o=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[o];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(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(r){let s=[r,o];if(n===!1&&(s=[r]),wc(this.prerelease,r)){let i=this.prerelease[r.split(".").length];isNaN(i)&&(this.prerelease=s)}else 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}};no.exports=ar});var se=w((am,so)=>{"use strict";var oo=T(),Ec=(e,t,r=!1)=>{if(e instanceof oo)return e;try{return new oo(e,t)}catch(n){if(!r)return null;throw n}};so.exports=Ec});var ao=w((cm,io)=>{"use strict";var Sc=se(),Rc=(e,t)=>{let r=Sc(e,t);return r?r.version:null};io.exports=Rc});var lo=w((lm,co)=>{"use strict";var bc=se(),Ac=(e,t)=>{let r=bc(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};co.exports=Ac});var mo=w((um,po)=>{"use strict";var uo=T(),vc=(e,t,r,n,o)=>{typeof r=="string"&&(o=n,n=r,r=void 0);try{return new uo(e instanceof uo?e.version:e,r).inc(t,n,o).version}catch{return null}};po.exports=vc});var ho=w((pm,go)=>{"use strict";var fo=se(),Pc=(e,t)=>{let r=fo(e,null,!0),n=fo(t,null,!0),o=r.compare(n);if(o===0)return null;let s=o>0,i=s?r:n,a=s?n: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 p=l?"pre":"";return r.major!==n.major?p+"major":r.minor!==n.minor?p+"minor":r.patch!==n.patch?p+"patch":"prerelease"};go.exports=Pc});var wo=w((dm,yo)=>{"use strict";var Ic=T(),Cc=(e,t)=>new Ic(e,t).major;yo.exports=Cc});var So=w((mm,Eo)=>{"use strict";var Tc=T(),Oc=(e,t)=>new Tc(e,t).minor;Eo.exports=Oc});var bo=w((fm,Ro)=>{"use strict";var $c=T(),Nc=(e,t)=>new $c(e,t).patch;Ro.exports=Nc});var vo=w((gm,Ao)=>{"use strict";var kc=se(),xc=(e,t)=>{let r=kc(e,t);return r&&r.prerelease.length?r.prerelease:null};Ao.exports=xc});var _=w((hm,Io)=>{"use strict";var Po=T(),Dc=(e,t,r)=>new Po(e,r).compare(new Po(t,r));Io.exports=Dc});var To=w((ym,Co)=>{"use strict";var Mc=_(),Lc=(e,t,r)=>Mc(t,e,r);Co.exports=Lc});var $o=w((wm,Oo)=>{"use strict";var Uc=_(),_c=(e,t)=>Uc(e,t,!0);Oo.exports=_c});var at=w((Em,ko)=>{"use strict";var No=T(),Fc=(e,t,r)=>{let n=new No(e,r),o=new No(t,r);return n.compare(o)||n.compareBuild(o)};ko.exports=Fc});var Do=w((Sm,xo)=>{"use strict";var jc=at(),Bc=(e,t)=>e.sort((r,n)=>jc(r,n,t));xo.exports=Bc});var Lo=w((Rm,Mo)=>{"use strict";var qc=at(),Wc=(e,t)=>e.sort((r,n)=>qc(n,r,t));Mo.exports=Wc});var Le=w((bm,Uo)=>{"use strict";var Gc=_(),Kc=(e,t,r)=>Gc(e,t,r)>0;Uo.exports=Kc});var ct=w((Am,_o)=>{"use strict";var Vc=_(),Hc=(e,t,r)=>Vc(e,t,r)<0;_o.exports=Hc});var cr=w((vm,Fo)=>{"use strict";var Jc=_(),Xc=(e,t,r)=>Jc(e,t,r)===0;Fo.exports=Xc});var lr=w((Pm,jo)=>{"use strict";var zc=_(),Yc=(e,t,r)=>zc(e,t,r)!==0;jo.exports=Yc});var lt=w((Im,Bo)=>{"use strict";var Qc=_(),Zc=(e,t,r)=>Qc(e,t,r)>=0;Bo.exports=Zc});var ut=w((Cm,qo)=>{"use strict";var el=_(),tl=(e,t,r)=>el(e,t,r)<=0;qo.exports=tl});var ur=w((Tm,Wo)=>{"use strict";var rl=cr(),nl=lr(),ol=Le(),sl=lt(),il=ct(),al=ut(),cl=(e,t,r,n)=>{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 rl(e,r,n);case"!=":return nl(e,r,n);case">":return ol(e,r,n);case">=":return sl(e,r,n);case"<":return il(e,r,n);case"<=":return al(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Wo.exports=cl});var Ko=w((Om,Go)=>{"use strict";var ll=T(),ul=se(),{safeRe:pt,t:dt}=ye(),pl=(e,t)=>{if(e instanceof ll)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?pt[dt.COERCEFULL]:pt[dt.COERCE]);else{let l=t.includePrerelease?pt[dt.COERCERTLFULL]:pt[dt.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 n=r[2],o=r[3]||"0",s=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return ul(`${n}.${o}.${s}${i}${a}`,t)};Go.exports=pl});var Ho=w(($m,Vo)=>{"use strict";var dl=se(),ml=he(),fl=T(),gl=(e,t,r)=>{if(!ml.RELEASE_TYPES.includes(t))return null;let n=hl(e,r);return n&&yl(n,t)},hl=(e,t)=>{let r=e instanceof fl?e.version:e;return dl(r,t)},yl=(e,t)=>{if(wl(t))return e.version;switch(e.prerelease=[],t){case"major":e.minor=0,e.patch=0;break;case"minor":e.patch=0;break}return e.format()},wl=e=>e.startsWith("pre");Vo.exports=gl});var Xo=w((Nm,Jo)=>{"use strict";var pr=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 o=this.map.keys().next().value;this.delete(o)}this.map.set(t,r)}return this}};Jo.exports=pr});var F=w((km,Zo)=>{"use strict";var El=/\s+/g,dr=class e{constructor(t,r){if(r=Rl(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof mr)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(El," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(o=>!Yo(o[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let o of this.set)if(o.length===1&&$l(o[0])){this.set=[o];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 n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(Ol,"");let n=((this.options.includePrerelease&&Cl)|(this.options.loose&&Tl))+":"+t,o=zo.get(n);if(o)return o;let s=this.options.loose,i=s?k[O.HYPHENRANGELOOSE]:k[O.HYPHENRANGE];t=t.replace(i,Bl(this.options.includePrerelease)),A("hyphen replace",t),t=t.replace(k[O.COMPARATORTRIM],vl),A("comparator trim",t),t=t.replace(k[O.TILDETRIM],Pl),A("tilde trim",t),t=t.replace(k[O.CARETTRIM],Il),A("caret trim",t);let a=t.split(" ").map(d=>Nl(d,this.options)).join(" ").split(/\s+/).map(d=>jl(d,this.options));s&&(a=a.filter(d=>(A("loose invalid filter",d,this.options),!!d.match(k[O.COMPARATORLOOSE])))),A("range list",a);let l=new Map,u=a.map(d=>new mr(d,this.options));for(let d of u){if(Yo(d))return[d];l.set(d.value,d)}l.size>1&&l.has("")&&l.delete("");let p=[...l.values()];return zo.set(n,p),p}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Qo(n,r)&&t.set.some(o=>Qo(o,r)&&n.every(s=>o.every(i=>s.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new bl(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(ql(this.set[r],t,this.options))return!0;return!1}};Zo.exports=dr;var Sl=Xo(),zo=new Sl,Rl=rt(),mr=Ue(),A=Me(),bl=T(),{safeRe:k,src:Al,t:O,comparatorTrimReplace:vl,tildeTrimReplace:Pl,caretTrimReplace:Il}=ye(),{FLAG_INCLUDE_PRERELEASE:Cl,FLAG_LOOSE:Tl}=he(),Ol=new RegExp(Al[O.BUILD],"g"),Yo=e=>e.value==="<0.0.0-0",$l=e=>e.value==="",Qo=(e,t)=>{let r=!0,n=e.slice(),o=n.pop();for(;r&&n.length;)r=n.every(s=>o.intersects(s,t)),o=n.pop();return r},Nl=(e,t)=>(e=e.replace(k[O.BUILD],""),A("comp",e,t),e=Ml(e,t),A("caret",e),e=xl(e,t),A("tildes",e),e=Ul(e,t),A("xrange",e),e=Fl(e,t),A("stars",e),e),C=e=>!e||e.toLowerCase()==="x"||e==="*",kl=(e,t,r)=>C(e)&&!C(t)||C(t)&&r&&!C(r),xl=(e,t)=>e.trim().split(/\s+/).map(r=>Dl(r,t)).join(" "),Dl=(e,t)=>{let r=t.loose?k[O.TILDELOOSE]:k[O.TILDE],n=t.includePrerelease?"-0":"";return e.replace(r,(o,s,i,a,l)=>{A("tilde",e,o,s,i,a,l);let u;return C(s)?u="":C(i)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:C(a)?u=`>=${s}.${i}.0${n} <${s}.${+i+1}.0-0`:l?(A("replaceTilde pr",l),u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`):u=`>=${s}.${i}.${a} <${s}.${+i+1}.0-0`,A("tilde return",u),u})},Ml=(e,t)=>e.trim().split(/\s+/).map(r=>Ll(r,t)).join(" "),Ll=(e,t)=>{A("caret",e,t);let r=t.loose?k[O.CARETLOOSE]:k[O.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(o,s,i,a,l)=>{A("caret",e,o,s,i,a,l);let u;return C(s)?u="":C(i)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:C(a)?s==="0"?u=`>=${s}.${i}.0${n} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${n} <${+s+1}.0.0-0`:l?(A("replaceCaret pr",l),s==="0"?i==="0"?u=`>=${s}.${i}.${a}-${l} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a}-${l} <${+s+1}.0.0-0`):(A("no pr"),s==="0"?i==="0"?u=`>=${s}.${i}.${a} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a} <${+s+1}.0.0-0`),A("caret return",u),u})},Ul=(e,t)=>(A("replaceXRanges",e,t),e.split(/\s+/).map(r=>_l(r,t)).join(" ")),_l=(e,t)=>{e=e.trim();let r=t.loose?k[O.XRANGELOOSE]:k[O.XRANGE];return e.replace(r,(n,o,s,i,a,l)=>{if(A("xRange",e,n,o,s,i,a,l),kl(s,i,a))return e;let u=C(s),p=u||C(i),d=p||C(a),E=d;return o==="="&&E&&(o=""),l=t.includePrerelease?"-0":"",u?o===">"||o==="<"?n="<0.0.0-0":n="*":o&&E?(p&&(i=0),a=0,o===">"?(o=">=",p?(s=+s+1,i=0,a=0):(i=+i+1,a=0)):o==="<="&&(o="<",p?s=+s+1:i=+i+1),o==="<"&&(l="-0"),n=`${o+s}.${i}.${a}${l}`):p?n=`>=${s}.0.0${l} <${+s+1}.0.0-0`:d&&(n=`>=${s}.${i}.0${l} <${s}.${+i+1}.0-0`),A("xRange return",n),n})},Fl=(e,t)=>(A("replaceStars",e,t),e.trim().replace(k[O.STAR],"")),jl=(e,t)=>(A("replaceGTE0",e,t),e.trim().replace(k[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),Bl=e=>(t,r,n,o,s,i,a,l,u,p,d,E)=>(C(n)?r="":C(o)?r=`>=${n}.0.0${e?"-0":""}`:C(s)?r=`>=${n}.${o}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,C(u)?l="":C(p)?l=`<${+u+1}.0.0-0`:C(d)?l=`<${u}.${+p+1}.0-0`:E?l=`<=${u}.${p}.${d}-${E}`:e?l=`<${u}.${p}.${+d+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),ql=(e,t,r)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let n=0;n<e.length;n++)if(A(e[n].semver),e[n].semver!==mr.ANY&&e[n].semver.prerelease.length>0){let o=e[n].semver;if(o.major===t.major&&o.minor===t.minor&&o.patch===t.patch)return!0}return!1}return!0}});var Ue=w((xm,ss)=>{"use strict";var _e=Symbol("SemVer ANY"),hr=class e{static get ANY(){return _e}constructor(t,r){if(r=es(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),gr("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===_e?this.value="":this.value=this.operator+this.semver.version,gr("comp",this)}parse(t){let r=this.options.loose?ts[rs.COMPARATORLOOSE]:ts[rs.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new ns(n[2],this.options.loose):this.semver=_e}toString(){return this.value}test(t){if(gr("Comparator.test",t,this.options.loose),this.semver===_e||t===_e)return!0;if(typeof t=="string")try{t=new ns(t,this.options)}catch{return!1}return fr(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 os(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new os(this.value,r).test(t.semver):(r=es(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("=")||fr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||fr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};ss.exports=hr;var es=rt(),{safeRe:ts,t:rs}=ye(),fr=ur(),gr=Me(),ns=T(),os=F()});var Fe=w((Dm,is)=>{"use strict";var Wl=F(),Gl=(e,t,r)=>{try{t=new Wl(t,r)}catch{return!1}return t.test(e)};is.exports=Gl});var cs=w((Mm,as)=>{"use strict";var Kl=F(),Vl=(e,t)=>new Kl(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));as.exports=Vl});var us=w((Lm,ls)=>{"use strict";var Hl=T(),Jl=F(),Xl=(e,t,r)=>{let n=null,o=null,s=null;try{s=new Jl(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!n||o.compare(i)===-1)&&(n=i,o=new Hl(n,r))}),n};ls.exports=Xl});var ds=w((Um,ps)=>{"use strict";var zl=T(),Yl=F(),Ql=(e,t,r)=>{let n=null,o=null,s=null;try{s=new Yl(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!n||o.compare(i)===1)&&(n=i,o=new zl(n,r))}),n};ps.exports=Ql});var gs=w((_m,fs)=>{"use strict";var yr=T(),Zl=F(),ms=Le(),eu=(e,t)=>{e=new Zl(e,t);let r=new yr("0.0.0");if(e.test(r)||(r=new yr("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n<e.set.length;++n){let o=e.set[n],s=null;o.forEach(i=>{let a=new yr(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||ms(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||ms(r,s))&&(r=s)}return r&&e.test(r)?r:null};fs.exports=eu});var ys=w((Fm,hs)=>{"use strict";var tu=F(),ru=(e,t)=>{try{return new tu(e,t).range||"*"}catch{return null}};hs.exports=ru});var mt=w((jm,Rs)=>{"use strict";var nu=T(),Ss=Ue(),{ANY:ou}=Ss,su=F(),iu=Fe(),ws=Le(),Es=ct(),au=ut(),cu=lt(),lu=(e,t,r,n)=>{e=new nu(e,n),t=new su(t,n);let o,s,i,a,l;switch(r){case">":o=ws,s=au,i=Es,a=">",l=">=";break;case"<":o=Es,s=cu,i=ws,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(iu(e,t,n))return!1;for(let u=0;u<t.set.length;++u){let p=t.set[u],d=null,E=null;if(p.forEach(g=>{g.semver===ou&&(g=new Ss(">=0.0.0")),d=d||g,E=E||g,o(g.semver,d.semver,n)?d=g:i(g.semver,E.semver,n)&&(E=g)}),d.operator===a||d.operator===l||(!E.operator||E.operator===a)&&s(e,E.semver))return!1;if(E.operator===l&&i(e,E.semver))return!1}return!0};Rs.exports=lu});var As=w((Bm,bs)=>{"use strict";var uu=mt(),pu=(e,t,r)=>uu(e,t,">",r);bs.exports=pu});var Ps=w((qm,vs)=>{"use strict";var du=mt(),mu=(e,t,r)=>du(e,t,"<",r);vs.exports=mu});var Ts=w((Wm,Cs)=>{"use strict";var Is=F(),fu=(e,t,r)=>(e=new Is(e,r),t=new Is(t,r),e.intersects(t,r));Cs.exports=fu});var $s=w((Gm,Os)=>{"use strict";var gu=Fe(),hu=_();Os.exports=(e,t,r)=>{let n=[],o=null,s=null,i=e.sort((p,d)=>hu(p,d,r));for(let p of i)gu(p,t,r)?(s=p,o||(o=p)):(s&&n.push([o,s]),s=null,o=null);o&&n.push([o,null]);let a=[];for(let[p,d]of n)p===d?a.push(p):!d&&p===i[0]?a.push("*"):d?p===i[0]?a.push(`<=${d}`):a.push(`${p} - ${d}`):a.push(`>=${p}`);let l=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var Ls=w((Km,Ms)=>{"use strict";var Ns=F(),Sr=Ue(),{ANY:wr}=Sr,Er=Fe(),Rr=_(),yu=(e,t,r={})=>{if(e===t)return!0;e=new Ns(e,r),t=new Ns(t,r);let n=!1;e:for(let o of e.set){for(let s of t.set){let i=Eu(o,s,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},wu=[new Sr(">=0.0.0-0")],ks=[new Sr(">=0.0.0")],Eu=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===wr){if(t.length===1&&t[0].semver===wr)return!0;r.includePrerelease?e=wu:e=ks}if(t.length===1&&t[0].semver===wr){if(r.includePrerelease)return!0;t=ks}let n=new Set,o,s;for(let g of e)g.operator===">"||g.operator===">="?o=xs(o,g,r):g.operator==="<"||g.operator==="<="?s=Ds(s,g,r):n.add(g.semver);if(n.size>1)return null;let i;if(o&&s){if(i=Rr(o.semver,s.semver,r),i>0)return null;if(i===0&&(o.operator!==">="||s.operator!=="<="))return null}for(let g of n){if(o&&!Er(g,String(o),r)||s&&!Er(g,String(s),r))return null;for(let K of t)if(!Er(g,String(K),r))return!1;return!0}let a,l,u,p,d=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,E=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&s.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let g of t){if(p=p||g.operator===">"||g.operator===">=",u=u||g.operator==="<"||g.operator==="<=",o){if(E&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===E.major&&g.semver.minor===E.minor&&g.semver.patch===E.patch&&(E=!1),g.operator===">"||g.operator===">="){if(a=xs(o,g,r),a===g&&a!==o)return!1}else if(o.operator===">="&&!g.test(o.semver))return!1}if(s){if(d&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===d.major&&g.semver.minor===d.minor&&g.semver.patch===d.patch&&(d=!1),g.operator==="<"||g.operator==="<="){if(l=Ds(s,g,r),l===g&&l!==s)return!1}else if(s.operator==="<="&&!g.test(s.semver))return!1}if(!g.operator&&(s||o)&&i!==0)return!1}return!(o&&u&&!s&&i!==0||s&&p&&!o&&i!==0||E||d)},xs=(e,t,r)=>{if(!e)return t;let n=Rr(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},Ds=(e,t,r)=>{if(!e)return t;let n=Rr(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};Ms.exports=yu});var Ar=w((Vm,Fs)=>{"use strict";var br=ye(),Us=he(),Su=T(),_s=sr(),Ru=se(),bu=ao(),Au=lo(),vu=mo(),Pu=ho(),Iu=wo(),Cu=So(),Tu=bo(),Ou=vo(),$u=_(),Nu=To(),ku=$o(),xu=at(),Du=Do(),Mu=Lo(),Lu=Le(),Uu=ct(),_u=cr(),Fu=lr(),ju=lt(),Bu=ut(),qu=ur(),Wu=Ko(),Gu=Ho(),Ku=Ue(),Vu=F(),Hu=Fe(),Ju=cs(),Xu=us(),zu=ds(),Yu=gs(),Qu=ys(),Zu=mt(),ep=As(),tp=Ps(),rp=Ts(),np=$s(),op=Ls();Fs.exports={parse:Ru,valid:bu,clean:Au,inc:vu,diff:Pu,major:Iu,minor:Cu,patch:Tu,prerelease:Ou,compare:$u,rcompare:Nu,compareLoose:ku,compareBuild:xu,sort:Du,rsort:Mu,gt:Lu,lt:Uu,eq:_u,neq:Fu,gte:ju,lte:Bu,cmp:qu,coerce:Wu,truncate:Gu,Comparator:Ku,Range:Vu,satisfies:Hu,toComparators:Ju,maxSatisfying:Xu,minSatisfying:zu,minVersion:Yu,validRange:Qu,outside:Zu,gtr:ep,ltr:tp,intersects:rp,simplifyRange:np,subset:op,SemVer:Su,re:br.re,src:br.src,tokens:br.t,SEMVER_SPEC_VERSION:Us.SEMVER_SPEC_VERSION,RELEASE_TYPES:Us.RELEASE_TYPES,compareIdentifiers:_s.compareIdentifiers,rcompareIdentifiers:_s.rcompareIdentifiers}});var id={};aa(id,{handleError:()=>Qi,main:()=>Yi,run:()=>Zi});module.exports=ca(id);var Ie=require("@medplum/core"),Je=require("commander"),zi=H(require("dotenv"),1);var q=require("@medplum/core"),xe=require("commander");var Xr=require("@medplum/core");var Hr=require("@medplum/core"),Y=require("node:fs"),Jr=require("node:os"),_t=require("node:path");var J=class extends Hr.ClientStorage{constructor(r){super();N(this,"dirName");N(this,"fileName");this.dirName=(0,_t.resolve)((0,Jr.homedir)(),".medplum"),this.fileName=(0,_t.resolve)(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,n){let o=this.readFile()??{};n?o[r]=n:delete o[r],this.writeFile(o)}getObject(r){let n=this.getString(r);return n?JSON.parse(n):void 0}setObject(r,n){this.setString(r,n?JSON.stringify(n):void 0)}readFile(){if((0,Y.existsSync)(this.fileName))return JSON.parse((0,Y.readFileSync)(this.fileName,"utf8"))}writeFile(r){(0,Y.existsSync)(this.dirName)||(0,Y.mkdirSync)(this.dirName),(0,Y.writeFileSync)(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function R(e,t=!0){let r=e.profile??"default",n=new J(r),o=n.getObject("options");if(r!=="default"&&!o)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:s,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:p,clientSecret:d}=la(e,n),E=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await ua(e.baseUrl,E);let g=new Xr.MedplumClient({fetch:E,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:n,onUnauthenticated:pa,verbose:e.verbose});return t&&(a?g.setAccessToken(a):p&&d&&(g.setBasicAuth(p,d),o?.authType!=="basic"&&await g.startClientLogin(p,d))),g}function la(e,t){let r=t.getObject("options"),n=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",o=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:n,fhirUrlPath:o,accessToken:s,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}async function ua(e,t){try{let r=new URL("healthcheck",e).toString(),n=await t(r);if(!n.ok)throw new Error(`Healthcheck returned status ${n.status}`);if((await n.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${n}`)}}function pa(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var x=require("@medplum/core"),bn=require("commander");var ce=new TextEncoder,zr=new TextDecoder,da=new TextDecoder("utf-8",{fatal:!0}),dd=2**32;function Yr(...e){let t=e.reduce((o,{length:s})=>o+s,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}var ma=/[^\x00-\x7f]/;function Xe(e){if(typeof e=="string"&&e.length>=128){if(ma.test(e))throw new TypeError("non-ASCII string encountered in encode()");return ce.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function Qr(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});let r=32768,n=[];for(let s=0;s<e.length;s+=r)n.push(String.fromCharCode.apply(null,e.subarray(s,s+r)));let o=btoa(n.join(""));return t?o.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):o}function Zr(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o);return n}var le=class extends Error{constructor(r,n){super(r,n);N(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};N(le,"code","ERR_JOSE_GENERIC");var Q=class extends le{constructor(){super(...arguments);N(this,"code","ERR_JOSE_NOT_SUPPORTED")}};N(Q,"code","ERR_JOSE_NOT_SUPPORTED");var L=class extends le{constructor(){super(...arguments);N(this,"code","ERR_JWS_INVALID")}};N(L,"code","ERR_JWS_INVALID");var Te=class extends le{constructor(){super(...arguments);N(this,"code","ERR_JWT_INVALID")}};N(Te,"code","ERR_JWT_INVALID");var en,tn,Ft=class extends(tn=le,en=Symbol.asyncIterator,tn){constructor(r="multiple matching keys found in the JSON Web Key Set",n){super(r,n);N(this,en,async function*(){});N(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};N(Ft,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var fa="The input to be decoded is not correctly encoded.";function rn(e){try{return Zr(typeof e=="string"?e:zr.decode(e),!0)}catch(t){throw new TypeError(fa,{cause:t})}}function Oe(e){return Qr(typeof e=="string"?ce.encode(e):e,!0)}function $e(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function nn(...e){let t=new Set;for(let r of e)if(r)for(let n of Object.keys(r)){if(t.has(n))return!1;t.add(n)}return!0}function on(e,t){if(e!==void 0)throw new TypeError(`${t} can only be called once`)}var sn={__proto__:null,b64:!0};function an(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function cn(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return[];if(!Array.isArray(n.crit)||n.crit.length===0||n.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?t:{__proto__:null,...r,...t};for(let i of n.crit){if(!(i in s))throw new Q(`Extension Header Parameter "${i}" is not recognized`);if(!Object.hasOwn(o,i)||o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s[i]&&(!Object.hasOwn(n,i)||n[i]===void 0))throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return n.crit}function ln(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!="boolean")throw new L('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function jt(e,t){let r,n;try{r=JSON.stringify(t),n=JSON.parse(r)}catch(o){throw new e("JOSE Header is not valid JSON",{cause:o})}if(!$e(n))throw new e("JOSE Header is not a JSON object");return[n,r]}var ga=e=>e[Symbol.toStringTag],ha=(e,t,r)=>{let{alg:n}=e;if(t.use!==void 0){let o=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==o)throw new TypeError(`Invalid key for this operation, its "use" must be "${o}" when present`)}if(t.alg!==void 0&&t.alg!==n)throw new TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(t.key_ops)){let o=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(o&&!t.key_ops.includes(o))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}};async function pn(e,t,r){let{alg:n,secret:o}=e,s=r==="decrypt"||r==="sign";if(o&&t instanceof Uint8Array)return t;let i,a;if($e(t)){if(i=va(t),typeof i.kty!="string")throw un(n,t,o);if(!(o?i.kty==="oct"&&typeof i.k=="string":i.kty!=="oct"&&(s?i.kty==="AKP"&&typeof i.priv=="string"||typeof i.d=="string":i.d===void 0&&i.priv===void 0)))throw new TypeError(o?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${s?"private":"public"} JWK`);if(ha(e,i,r),i.kty==="oct")return rn(i.k);if(!Object.isFrozen(t)){let{key_ops:p}=t;Array.isArray(p)&&Object.freeze(p),Object.freeze(t)}}else{if(!Ea(t))throw un(n,t,o);let p=o?"secret":s?"private":"public";if(t.type!==p&&(o||["secret","public","private"].includes(t.type)))throw new TypeError(`${ga(t)} instances must be of type "${p}" for the ${n} algorithm`);if(dn(t))return t;if(a=t,a.type==="secret")return a.export()}Bt||=new WeakMap;let l=t,u=Bt.get(l);if(u?.[n])return u[n];if(u||Bt.set(l,u={}),a&&typeof a.toCryptoKey=="function"){let p=a.type==="public",d=ya[a.asymmetricKeyDetails?.namedCurve],E=e.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return u[n]=a.toCryptoKey(E,p,e.usages[p?0:1])}return i??=a.export({format:"jwk"}),i.alg=n,u[n]=await Pa(e,i)}var Bt,ya={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};var dn=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},wa=e=>e?.[Symbol.toStringTag]==="KeyObject",Ea=e=>dn(e)||wa(e);function Sa(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}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}function un(e,t,r){let n=["CryptoKey","KeyObject","JSON Web Key"];return r&&n.push("Uint8Array"),new TypeError(Sa(`Key for the ${e} algorithm must be `,t,...n))}var ze=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Ra(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function mn(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function ba(e,t,r){let n=e.algorithm;if(n.name!==t.name)throw ze(t.name);if(t.hash&&n.hash?.name!==t.hash)throw ze(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw ze(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&n.length!==t.length)throw ze(t.length,"algorithm.length");Ra(e,r)}function Aa(e){return{__proto__:null,...e}}function va(e){let t=Aa(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,n=Array.isArray(r)?[...r]:void 0;if(!n||n.some(o=>typeof o!="string")||new Set(n).size!==n.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=n}return t}async function Pa(e,t,r){if(!e.kty.includes(t.kty))throw new Q('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let n=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,o=!!(t.d||t.priv),s={...t,ext:r??t.ext};return s.kty!=="AKP"&&delete s.alg,delete s.use,crypto.subtle.importKey("jwk",s,n,s.ext??!o,t.key_ops??e.usages[o?1:0])}async function fn(e,t,r,n=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,n,[r])),ba(e,t,r),e}function gn(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var Ne=[["verify"],["sign"]];function qt(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Ne}}function me(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:Ne,minRsaBits:2048}}function Wt(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Ne}}function hn(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Ne}}function Gt(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Ne}}var Ia=gn({HS256:qt(256),HS384:qt(384),HS512:qt(512),RS256:me(256),RS384:me(384),RS512:me(512),PS256:me(256,32),PS384:me(384,48),PS512:me(512,64),ES256:Wt("P-256",256),ES384:Wt("P-384",384),ES512:Wt("P-521",512),EdDSA:hn(),Ed25519:hn(),"ML-DSA-44":Gt(44),"ML-DSA-65":Gt(65),"ML-DSA-87":Gt(87)});function yn(e){let t=typeof e=="string"?Ia[e]:void 0;if(!t)throw new Q(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}var Ye=e=>Math.floor(e.getTime()/1e3),Ca={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Ta=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Kt(){throw new TypeError("Invalid time period format")}function wn(e){typeof e!="string"&&Kt();let t=Ta.exec(e);(!t||t[4]&&t[1])&&Kt();let r=parseFloat(t[2]),n=Math.round(r*Ca[t[3][0].toLowerCase()]);return Number.isFinite(n)||Kt(),t[1]==="-"||t[4]==="ago"?-n:n}function Jt(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function Vt(e,t){if(typeof t!="string")throw new TypeError(`"${e}" claim must be a string`)}function Oa(e){if(typeof e!="string"&&(!Array.isArray(e)||Array.from(e).some(t=>typeof t!="string")))throw new TypeError('"aud" claim must be a string or an array of strings')}function Ht(e,t){return typeof e=="number"?Jt(t,e):e instanceof Date?Jt(t,Ye(e)):Ye(new Date)+wn(e)}var En;function re(e){return En.get(e)}function Sn(e){let t=re(e);for(let r of["iat","nbf","exp"]){let n=t[r];if(typeof n=="number"&&!Number.isFinite(n))throw new TypeError(`"${r}" claim must be a finite number`)}return ce.encode(JSON.stringify(t))}var Qe=class{constructor(t={}){if(!$e(t))throw new TypeError("JWT Claims Set MUST be an object");(En||=new WeakMap).set(this,structuredClone(t))}setIssuer(t){return Vt("iss",t),re(this).iss=t,this}setSubject(t){return Vt("sub",t),re(this).sub=t,this}setAudience(t){return Oa(t),re(this).aud=t,this}setJti(t){return Vt("jti",t),re(this).jti=t,this}setNotBefore(t){return re(this).nbf=Ht(t,"setNotBefore"),this}setExpirationTime(t){return re(this).exp=Ht(t,"setExpirationTime"),this}setIssuedAt(t){let r=re(this);return t===void 0?r.iat=Ye(new Date):typeof t=="string"?r.iat=Jt("setIssuedAt",Ye(new Date)+wn(t)):r.iat=Ht(t,"setIssuedAt"),this}};async function $a(e,t,r){let[n,o,s,i]=e,a="";if(o!==void 0){let V=jt(L,o);o=V[0],a=Oe(V[1])}if(s!==void 0&&(s=jt(L,s)[0]),!o&&!s)throw new L("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!nn(o,s))throw new L("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let l={...o,...s};an(L,o);let u=ln(o,cn(L,sn,i,o,l));u||r?.();let{alg:p}=l;if(typeof p!="string"||!p)throw new L('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=yn(p),E="",g=n,K;if(u){let V=e[4];V?(E=V[0]??=Oe(n),g=V[1]??=Xe(E)):(E=Oe(n),K=ce.encode(`${a}.${E}`))}K??=Yr(Xe(a),Xe("."),g);let P=await fn(await pn(d,t,"sign"),d.subtle,"sign");d.minRsaBits&&mn(d.alg,P);let M={signature:Oe(new Uint8Array(await crypto.subtle.sign(d.signing,P,K))),payload:E};return o&&(M.protected=a),s&&(M.header=s),[M,u]}async function Rn(e,t,r,n,o){let[s]=await $a([e,t,void 0,r],n,o);return`${s.protected}.${s.payload}.${s.signature}`}var Na=Qe,fe,ke=class extends Na{constructor(){super(...arguments);Kr(this,fe)}setProtectedHeader(r){return on(Ut(this,fe),"setProtectedHeader"),Vr(this,fe,r),this}async sign(r,n){return Rn(Sn(this),Ut(this,fe),n?.crit,r,()=>{throw new Te("JWTs MUST NOT use unencoded payload")})}};fe=new WeakMap;var ge=require("node:crypto"),ne=require("node:fs"),Z=require("node:path"),An=require("node:util/types"),vn=require("tar");function ee(e){console.log(JSON.stringify(e,null,2))}async function Xt(e,t,r){let n=t.source,o=Ze(n);if(!o)return;console.log("Saving source code...");let s=await e.createAttachment({data:o,filename:(0,Z.basename)(n),contentType:Da(n)});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 n=t.dist??t.source,o=Ze(n);if(!o)return;console.log("Deploying bot...");let s=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:o,filename:(0,Z.basename)(n)});if(console.log("Deploy result: "+s.issue?.[0]?.details?.text),!(0,x.isOk)(s))throw new Error(`Bot deploy failed: ${(0,x.normalizeErrorString)(s)}`)}async function Yt(e,t,r,n,o,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),p={name:t,id:l.id,source:n,dist:o};await Xt(e,p,u),await zt(e,p,u),console.log(`Success! Bot created: ${u.id}`),i&&ka(p)}function Pn(e){let t=new RegExp("^"+xa(e).replaceAll(String.raw`\*`,".*")+"$"),r=X()?.bots?.filter(n=>t.test(n.name));return r||[]}function B(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 I(e,t){(0,ne.writeFileSync)((0,Z.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function X(e,t){let r=B(e,t),n=Ze(r);if(n)return JSON.parse(n)}function In(e){let t=Ze(B(e,{server:!0}));if(t)return JSON.parse(t)}function Ze(e){let t=(0,Z.resolve)(e);return(0,ne.existsSync)(t)?(0,ne.readFileSync)(t,"utf8"):""}function ka(e){let t=X()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ne.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function xa(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Cn(e){let n=0,o=0;return(0,vn.extract)({cwd:e,filter:(s,i)=>{if(n++,n>100)throw new Error("Tar extractor reached max number of files");if(o+=i.size,o>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Qt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function Da(e){let t=(0,Z.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?x.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?x.ContentType.TYPESCRIPT:x.ContentType.TEXT}function et(e,t){let r=new J(e),n={name:e,...t};return r.setObject("options",n),n}function Tn(e){return new J(e).getObject("options")}async function On(e,t){let r={typ:"JWT",alg:x.OAuthSigningAlgorithm.HS256},n=Math.floor(Date.now()/1e3),o={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:n,iat:n,exp:n+604800},s=(0,x.encodeBase64)(JSON.stringify(r)),i=(0,x.encodeBase64)(JSON.stringify(o)),a=`${s}.${i}`,l=(0,ge.createHmac)("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function $n(e,t){let r=(0,ge.createPrivateKey)((0,ne.readFileSync)((0,Z.resolve)(t.privateKeyPath))),n=await new ke({}).setProtectedHeader({typ:"JWT",alg:x.OAuthSigningAlgorithm.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,ge.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(n)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var h=class extends bn.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 n=e.registeredArguments.length,o=r.slice(0,n);o[n]=e.optsWithGlobals();try{let s=t(...o);(0,An.isPromise)(s)&&await s}finally{e.resetOptionDefaults()}}}var Dn=new h("status").aliases(["info","list","ls"]),Mn=new h("ping"),Ln=new h("push"),Un=new h("reload-config"),_n=new h("upgrade"),Fn=new h("stats"),oe=new h("agent");y(oe,Dn);y(oe,Mn);y(oe,Ln);y(oe,Un);y(oe,_n);y(oe,Fn);Dn.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 xe.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await tt({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let n=Bn(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:n.version,connectionStatus:n.status,statusLastUpdated:n.lastUpdated??"N/A"}}})});Mn.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 n=await R(r),o=await jn(n,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 n.pushToAgent(o,e,`PING ${s}`,q.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});Ln.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",q.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,n)=>{let o=await R(n),s=await jn(o,r,n),i;try{i=await o.pushToAgent(s,{reference:`Device/${e}`},t,n.contentType,n.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});Un.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 xe.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await tt({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});_n.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 xe.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 tt({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:n=>({id:n.agent.id,name:n.agent.name,version:t.agentVersion??"latest"})})});Fn.description("Get runtime statistics for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) to get stats for. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to get stats for. Mutually exclusive with [agentIds...] arg").addOption(new xe.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await tt({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:n}=Bn(r.result,{required:["stats"]}),o;try{o=JSON.parse(n)}catch(s){console.error(`Failed to parse stats for agent ${r.agent.id}: ${(0,q.normalizeErrorString)(s)}`)}return{id:r.agent.id,name:r.agent.name,stats:o}},renderSuccessfulRows:r=>{for(let n=0;n<r.length;n++)n>0&&console.info(),La(r[n])}})});var Nn=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function kn(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function xn(e){return e?Object.entries(e).filter(([,t])=>t?.rtt).map(([t,r])=>({name:t,count:r.rtt.count,pending:r.rtt.pendingCount,"min (ms)":r.rtt.min,"avg (ms)":r.rtt.average,"max (ms)":r.rtt.max,"p50 (ms)":r.rtt.p50,"p95 (ms)":r.rtt.p95,"p99 (ms)":r.rtt.p99})):[]}function La(e){let t=e.name?`${e.name} (${e.id})`:e.id;if(console.info(`Agent: ${t}`),!e.stats){console.info(" (stats unavailable)");return}let r={};for(let i of Nn)r[i]=kn(e.stats[i]);let n=new Set([...Nn,"channelStats","clientStats"]);for(let[i,a]of Object.entries(e.stats))n.has(i)||(r[i]=kn(a));console.table(r);let o=xn(e.stats.channelStats);o.length&&(console.info("Channel Stats:"),console.table(o));let s=xn(e.stats.clientStats);s.length&&(console.info("Client Stats:"),console.table(s))}async function tt({operation:e,agentIds:t,options:r,params:n={},parseSuccessfulResponse:o,renderSuccessfulRows:s}){let i=ja(t,r),a=await R(r),l=i.type==="criteria"?i.criteria:`Agent?_id=${i.ids.join(",")}`,u=new URLSearchParams(l.split("?")[1]);for(let[P,M]of Object.entries(n))u.append(P,M.toString());let p;try{let P=a.fhirUrl("Agent",e);P.search=u.toString(),p=await a.get(P,{cache:"reload"})}catch(P){throw new Error(`Operation '${e}' failed`,{cause:P})}if(r.output==="json"){console.info(JSON.stringify(p,null,2));return}let d=[],E=[];switch(p.resourceType){case"Bundle":{let P=Ua(p);for(let M of P)M.result.resourceType==="Parameters"||(0,q.isOk)(M.result)?d.push(M):E.push(M);break}case"Parameters":case"OperationOutcome":{let P=await a.searchOne("Agent",u,{cache:"reload"});if(!P)throw new Error("Agent not found");p.resourceType==="Parameters"?d.push({agent:P,result:p}):E.push({agent:P,result:p});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(p)}`)}let g=[];for(let P of d){let M=o(P);g.push(M)}let K=[];for(let P of E){let V=P.result.issue?.[0],ea={id:P.agent.id,name:P.agent.name,severity:V.severity,code:V.code,details:V.details?.text??"No details to show"};K.push(ea)}console.info(`
|
|
2
|
+
"use strict";var ta=Object.create;var Ce=Object.defineProperty;var ra=Object.getOwnPropertyDescriptor;var na=Object.getOwnPropertyNames;var oa=Object.getPrototypeOf,sa=Object.prototype.hasOwnProperty;var qr=e=>{throw TypeError(e)};var ia=(e,t,r)=>t in e?Ce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},aa=(e,t)=>{for(var r in t)Ce(e,r,{get:t[r],enumerable:!0})},Wr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of na(t))!sa.call(e,o)&&o!==r&&Ce(e,o,{get:()=>t[o],enumerable:!(n=ra(t,o))||n.enumerable});return e};var z=(e,t,r)=>(r=e!=null?ta(oa(e)):{},Wr(t||!e||!e.__esModule?Ce(r,"default",{value:e,enumerable:!0}):r,e)),ca=e=>Wr(Ce({},"__esModule",{value:!0}),e);var N=(e,t,r)=>ia(e,typeof t!="symbol"?t+"":t,r),Gr=(e,t,r)=>t.has(e)||qr("Cannot "+r);var Ut=(e,t,r)=>(Gr(e,t,"read from private field"),r?r.call(e):t.get(e)),Kr=(e,t,r)=>t.has(e)?qr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Vr=(e,t,r,n)=>(Gr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var he=w((rm,Xn)=>{"use strict";var Qa="2.0.0",Za=Number.MAX_SAFE_INTEGER||9007199254740991,ec=16,tc=250,rc=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Xn.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ec,MAX_SAFE_BUILD_LENGTH:tc,MAX_SAFE_INTEGER:Za,RELEASE_TYPES:rc,SEMVER_SPEC_VERSION:Qa,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Me=w((nm,zn)=>{"use strict";var nc=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};zn.exports=nc});var ye=w((X,Yn)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:nr,MAX_SAFE_BUILD_LENGTH:oc,MAX_LENGTH:sc}=he(),ic=Me();X=Yn.exports={};var ac=X.re=[],cc=X.safeRe=[],m=X.src=[],lc=X.safeSrc=[],f=X.t={},uc=0,or="[a-zA-Z0-9-]",pc=[["\\s",1],["\\d",sc],[or,oc]],dc=e=>{for(let[t,r]of pc)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},S=(e,t,r)=>{let n=dc(t),o=uc++;ic(e,o,t),f[e]=o,m[o]=t,lc[o]=n,ac[o]=new RegExp(t,r?"g":void 0),cc[o]=new RegExp(n,r?"g":void 0)};S("NUMERICIDENTIFIER","0|[1-9]\\d*");S("NUMERICIDENTIFIERLOOSE","\\d+");S("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${or}*`);S("MAINVERSION",`(${m[f.NUMERICIDENTIFIER]})\\.(${m[f.NUMERICIDENTIFIER]})\\.(${m[f.NUMERICIDENTIFIER]})`);S("MAINVERSIONLOOSE",`(${m[f.NUMERICIDENTIFIERLOOSE]})\\.(${m[f.NUMERICIDENTIFIERLOOSE]})\\.(${m[f.NUMERICIDENTIFIERLOOSE]})`);S("PRERELEASEIDENTIFIER",`(?:${m[f.NONNUMERICIDENTIFIER]}|${m[f.NUMERICIDENTIFIER]})`);S("PRERELEASEIDENTIFIERLOOSE",`(?:${m[f.NONNUMERICIDENTIFIER]}|${m[f.NUMERICIDENTIFIERLOOSE]})`);S("PRERELEASE",`(?:-(${m[f.PRERELEASEIDENTIFIER]}(?:\\.${m[f.PRERELEASEIDENTIFIER]})*))`);S("PRERELEASELOOSE",`(?:-?(${m[f.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${m[f.PRERELEASEIDENTIFIERLOOSE]})*))`);S("BUILDIDENTIFIER",`${or}+`);S("BUILD",`(?:\\+(${m[f.BUILDIDENTIFIER]}(?:\\.${m[f.BUILDIDENTIFIER]})*))`);S("FULLPLAIN",`v?${m[f.MAINVERSION]}${m[f.PRERELEASE]}?${m[f.BUILD]}?`);S("FULL",`^${m[f.FULLPLAIN]}$`);S("LOOSEPLAIN",`[v=\\s]*${m[f.MAINVERSIONLOOSE]}${m[f.PRERELEASELOOSE]}?${m[f.BUILD]}?`);S("LOOSE",`^${m[f.LOOSEPLAIN]}$`);S("GTLT","((?:<|>)?=?)");S("XRANGEIDENTIFIERLOOSE",`${m[f.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);S("XRANGEIDENTIFIER",`${m[f.NUMERICIDENTIFIER]}|x|X|\\*`);S("XRANGEPLAIN",`[v=\\s]*(${m[f.XRANGEIDENTIFIER]})(?:\\.(${m[f.XRANGEIDENTIFIER]})(?:\\.(${m[f.XRANGEIDENTIFIER]})(?:${m[f.PRERELEASE]})?${m[f.BUILD]}?)?)?`);S("XRANGEPLAINLOOSE",`[v=\\s]*(${m[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${m[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${m[f.XRANGEIDENTIFIERLOOSE]})(?:${m[f.PRERELEASELOOSE]})?${m[f.BUILD]}?)?)?`);S("XRANGE",`^${m[f.GTLT]}\\s*${m[f.XRANGEPLAIN]}$`);S("XRANGELOOSE",`^${m[f.GTLT]}\\s*${m[f.XRANGEPLAINLOOSE]}$`);S("COERCEPLAIN",`(^|[^\\d])(\\d{1,${nr}})(?:\\.(\\d{1,${nr}}))?(?:\\.(\\d{1,${nr}}))?`);S("COERCE",`${m[f.COERCEPLAIN]}(?:$|[^\\d])`);S("COERCEFULL",m[f.COERCEPLAIN]+`(?:${m[f.PRERELEASE]})?(?:${m[f.BUILD]})?(?:$|[^\\d])`);S("COERCERTL",m[f.COERCE],!0);S("COERCERTLFULL",m[f.COERCEFULL],!0);S("LONETILDE","(?:~>?)");S("TILDETRIM",`(\\s*)${m[f.LONETILDE]}\\s+`,!0);X.tildeTrimReplace="$1~";S("TILDE",`^${m[f.LONETILDE]}${m[f.XRANGEPLAIN]}$`);S("TILDELOOSE",`^${m[f.LONETILDE]}${m[f.XRANGEPLAINLOOSE]}$`);S("LONECARET","(?:\\^)");S("CARETTRIM",`(\\s*)${m[f.LONECARET]}\\s+`,!0);X.caretTrimReplace="$1^";S("CARET",`^${m[f.LONECARET]}${m[f.XRANGEPLAIN]}$`);S("CARETLOOSE",`^${m[f.LONECARET]}${m[f.XRANGEPLAINLOOSE]}$`);S("COMPARATORLOOSE",`^${m[f.GTLT]}\\s*(${m[f.LOOSEPLAIN]})$|^$`);S("COMPARATOR",`^${m[f.GTLT]}\\s*(${m[f.FULLPLAIN]})$|^$`);S("COMPARATORTRIM",`(\\s*)${m[f.GTLT]}\\s*(${m[f.LOOSEPLAIN]}|${m[f.XRANGEPLAIN]})`,!0);X.comparatorTrimReplace="$1$2$3";S("HYPHENRANGE",`^\\s*(${m[f.XRANGEPLAIN]})\\s+-\\s+(${m[f.XRANGEPLAIN]})\\s*$`);S("HYPHENRANGELOOSE",`^\\s*(${m[f.XRANGEPLAINLOOSE]})\\s+-\\s+(${m[f.XRANGEPLAINLOOSE]})\\s*$`);S("STAR","(<|>)?=?\\s*\\*");S("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");S("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var rt=w((om,Qn)=>{"use strict";var mc=Object.freeze({loose:!0}),fc=Object.freeze({}),gc=e=>e?typeof e!="object"?mc:e:fc;Qn.exports=gc});var sr=w((sm,to)=>{"use strict";var Zn=/^[0-9]+$/,eo=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=Zn.test(e),n=Zn.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},hc=(e,t)=>eo(t,e);to.exports={compareIdentifiers:eo,rcompareIdentifiers:hc}});var T=w((im,no)=>{"use strict";var nt=Me(),{MAX_LENGTH:ro,MAX_SAFE_INTEGER:ot}=he(),{safeRe:st,t:it}=ye(),yc=rt(),{compareIdentifiers:ir}=sr(),wc=(e,t)=>{let r=t.split(".");if(r.length>e.length)return!1;for(let n=0;n<r.length;n++)if(ir(e[n],r[n])!==0)return!1;return!0},ar=class e{constructor(t,r){if(r=yc(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>ro)throw new TypeError(`version is longer than ${ro} characters`);nt("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?st[it.LOOSE]:st[it.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>ot||this.major<0)throw new TypeError("Invalid major version");if(this.minor>ot||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>ot||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){let s=+o;if(s>=0&&s<ot)return s}return o}):this.prerelease=[],this.build=n[5]?n[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(nt("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 n=this.prerelease[r],o=t.prerelease[r];if(nt("prerelease compare",r,n,o),n===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(n===void 0)return-1;if(n===o)continue;return ir(n,o)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],o=t.build[r];if(nt("build compare",r,n,o),n===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(n===void 0)return-1;if(n===o)continue;return ir(n,o)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let o=`-${r}`.match(this.options.loose?st[it.PRERELEASELOOSE]:st[it.PRERELEASE]);if(!o||o[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,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);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 o=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[o];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(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(r){let s=[r,o];if(n===!1&&(s=[r]),wc(this.prerelease,r)){let i=this.prerelease[r.split(".").length];isNaN(i)&&(this.prerelease=s)}else 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}};no.exports=ar});var se=w((am,so)=>{"use strict";var oo=T(),Ec=(e,t,r=!1)=>{if(e instanceof oo)return e;try{return new oo(e,t)}catch(n){if(!r)return null;throw n}};so.exports=Ec});var ao=w((cm,io)=>{"use strict";var Sc=se(),Rc=(e,t)=>{let r=Sc(e,t);return r?r.version:null};io.exports=Rc});var lo=w((lm,co)=>{"use strict";var bc=se(),Ac=(e,t)=>{let r=bc(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};co.exports=Ac});var mo=w((um,po)=>{"use strict";var uo=T(),vc=(e,t,r,n,o)=>{typeof r=="string"&&(o=n,n=r,r=void 0);try{return new uo(e instanceof uo?e.version:e,r).inc(t,n,o).version}catch{return null}};po.exports=vc});var ho=w((pm,go)=>{"use strict";var fo=se(),Pc=(e,t)=>{let r=fo(e,null,!0),n=fo(t,null,!0),o=r.compare(n);if(o===0)return null;let s=o>0,i=s?r:n,a=s?n: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 p=l?"pre":"";return r.major!==n.major?p+"major":r.minor!==n.minor?p+"minor":r.patch!==n.patch?p+"patch":"prerelease"};go.exports=Pc});var wo=w((dm,yo)=>{"use strict";var Ic=T(),Cc=(e,t)=>new Ic(e,t).major;yo.exports=Cc});var So=w((mm,Eo)=>{"use strict";var Tc=T(),Oc=(e,t)=>new Tc(e,t).minor;Eo.exports=Oc});var bo=w((fm,Ro)=>{"use strict";var $c=T(),Nc=(e,t)=>new $c(e,t).patch;Ro.exports=Nc});var vo=w((gm,Ao)=>{"use strict";var kc=se(),xc=(e,t)=>{let r=kc(e,t);return r&&r.prerelease.length?r.prerelease:null};Ao.exports=xc});var _=w((hm,Io)=>{"use strict";var Po=T(),Dc=(e,t,r)=>new Po(e,r).compare(new Po(t,r));Io.exports=Dc});var To=w((ym,Co)=>{"use strict";var Mc=_(),Lc=(e,t,r)=>Mc(t,e,r);Co.exports=Lc});var $o=w((wm,Oo)=>{"use strict";var Uc=_(),_c=(e,t)=>Uc(e,t,!0);Oo.exports=_c});var at=w((Em,ko)=>{"use strict";var No=T(),Fc=(e,t,r)=>{let n=new No(e,r),o=new No(t,r);return n.compare(o)||n.compareBuild(o)};ko.exports=Fc});var Do=w((Sm,xo)=>{"use strict";var jc=at(),Bc=(e,t)=>e.sort((r,n)=>jc(r,n,t));xo.exports=Bc});var Lo=w((Rm,Mo)=>{"use strict";var qc=at(),Wc=(e,t)=>e.sort((r,n)=>qc(n,r,t));Mo.exports=Wc});var Le=w((bm,Uo)=>{"use strict";var Gc=_(),Kc=(e,t,r)=>Gc(e,t,r)>0;Uo.exports=Kc});var ct=w((Am,_o)=>{"use strict";var Vc=_(),Hc=(e,t,r)=>Vc(e,t,r)<0;_o.exports=Hc});var cr=w((vm,Fo)=>{"use strict";var Jc=_(),Xc=(e,t,r)=>Jc(e,t,r)===0;Fo.exports=Xc});var lr=w((Pm,jo)=>{"use strict";var zc=_(),Yc=(e,t,r)=>zc(e,t,r)!==0;jo.exports=Yc});var lt=w((Im,Bo)=>{"use strict";var Qc=_(),Zc=(e,t,r)=>Qc(e,t,r)>=0;Bo.exports=Zc});var ut=w((Cm,qo)=>{"use strict";var el=_(),tl=(e,t,r)=>el(e,t,r)<=0;qo.exports=tl});var ur=w((Tm,Wo)=>{"use strict";var rl=cr(),nl=lr(),ol=Le(),sl=lt(),il=ct(),al=ut(),cl=(e,t,r,n)=>{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 rl(e,r,n);case"!=":return nl(e,r,n);case">":return ol(e,r,n);case">=":return sl(e,r,n);case"<":return il(e,r,n);case"<=":return al(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Wo.exports=cl});var Ko=w((Om,Go)=>{"use strict";var ll=T(),ul=se(),{safeRe:pt,t:dt}=ye(),pl=(e,t)=>{if(e instanceof ll)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?pt[dt.COERCEFULL]:pt[dt.COERCE]);else{let l=t.includePrerelease?pt[dt.COERCERTLFULL]:pt[dt.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 n=r[2],o=r[3]||"0",s=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return ul(`${n}.${o}.${s}${i}${a}`,t)};Go.exports=pl});var Ho=w(($m,Vo)=>{"use strict";var dl=se(),ml=he(),fl=T(),gl=(e,t,r)=>{if(!ml.RELEASE_TYPES.includes(t))return null;let n=hl(e,r);return n&&yl(n,t)},hl=(e,t)=>{let r=e instanceof fl?e.version:e;return dl(r,t)},yl=(e,t)=>{if(wl(t))return e.version;switch(e.prerelease=[],t){case"major":e.minor=0,e.patch=0;break;case"minor":e.patch=0;break}return e.format()},wl=e=>e.startsWith("pre");Vo.exports=gl});var Xo=w((Nm,Jo)=>{"use strict";var pr=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 o=this.map.keys().next().value;this.delete(o)}this.map.set(t,r)}return this}};Jo.exports=pr});var F=w((km,Zo)=>{"use strict";var El=/\s+/g,dr=class e{constructor(t,r){if(r=Rl(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof mr)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(El," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(o=>!Yo(o[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let o of this.set)if(o.length===1&&$l(o[0])){this.set=[o];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 n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(Ol,"");let n=((this.options.includePrerelease&&Cl)|(this.options.loose&&Tl))+":"+t,o=zo.get(n);if(o)return o;let s=this.options.loose,i=s?k[O.HYPHENRANGELOOSE]:k[O.HYPHENRANGE];t=t.replace(i,Bl(this.options.includePrerelease)),A("hyphen replace",t),t=t.replace(k[O.COMPARATORTRIM],vl),A("comparator trim",t),t=t.replace(k[O.TILDETRIM],Pl),A("tilde trim",t),t=t.replace(k[O.CARETTRIM],Il),A("caret trim",t);let a=t.split(" ").map(d=>Nl(d,this.options)).join(" ").split(/\s+/).map(d=>jl(d,this.options));s&&(a=a.filter(d=>(A("loose invalid filter",d,this.options),!!d.match(k[O.COMPARATORLOOSE])))),A("range list",a);let l=new Map,u=a.map(d=>new mr(d,this.options));for(let d of u){if(Yo(d))return[d];l.set(d.value,d)}l.size>1&&l.has("")&&l.delete("");let p=[...l.values()];return zo.set(n,p),p}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Qo(n,r)&&t.set.some(o=>Qo(o,r)&&n.every(s=>o.every(i=>s.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new bl(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(ql(this.set[r],t,this.options))return!0;return!1}};Zo.exports=dr;var Sl=Xo(),zo=new Sl,Rl=rt(),mr=Ue(),A=Me(),bl=T(),{safeRe:k,src:Al,t:O,comparatorTrimReplace:vl,tildeTrimReplace:Pl,caretTrimReplace:Il}=ye(),{FLAG_INCLUDE_PRERELEASE:Cl,FLAG_LOOSE:Tl}=he(),Ol=new RegExp(Al[O.BUILD],"g"),Yo=e=>e.value==="<0.0.0-0",$l=e=>e.value==="",Qo=(e,t)=>{let r=!0,n=e.slice(),o=n.pop();for(;r&&n.length;)r=n.every(s=>o.intersects(s,t)),o=n.pop();return r},Nl=(e,t)=>(e=e.replace(k[O.BUILD],""),A("comp",e,t),e=Ml(e,t),A("caret",e),e=xl(e,t),A("tildes",e),e=Ul(e,t),A("xrange",e),e=Fl(e,t),A("stars",e),e),C=e=>!e||e.toLowerCase()==="x"||e==="*",kl=(e,t,r)=>C(e)&&!C(t)||C(t)&&r&&!C(r),xl=(e,t)=>e.trim().split(/\s+/).map(r=>Dl(r,t)).join(" "),Dl=(e,t)=>{let r=t.loose?k[O.TILDELOOSE]:k[O.TILDE],n=t.includePrerelease?"-0":"";return e.replace(r,(o,s,i,a,l)=>{A("tilde",e,o,s,i,a,l);let u;return C(s)?u="":C(i)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:C(a)?u=`>=${s}.${i}.0${n} <${s}.${+i+1}.0-0`:l?(A("replaceTilde pr",l),u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`):u=`>=${s}.${i}.${a} <${s}.${+i+1}.0-0`,A("tilde return",u),u})},Ml=(e,t)=>e.trim().split(/\s+/).map(r=>Ll(r,t)).join(" "),Ll=(e,t)=>{A("caret",e,t);let r=t.loose?k[O.CARETLOOSE]:k[O.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(o,s,i,a,l)=>{A("caret",e,o,s,i,a,l);let u;return C(s)?u="":C(i)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:C(a)?s==="0"?u=`>=${s}.${i}.0${n} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.0${n} <${+s+1}.0.0-0`:l?(A("replaceCaret pr",l),s==="0"?i==="0"?u=`>=${s}.${i}.${a}-${l} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a}-${l} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a}-${l} <${+s+1}.0.0-0`):(A("no pr"),s==="0"?i==="0"?u=`>=${s}.${i}.${a} <${s}.${i}.${+a+1}-0`:u=`>=${s}.${i}.${a} <${s}.${+i+1}.0-0`:u=`>=${s}.${i}.${a} <${+s+1}.0.0-0`),A("caret return",u),u})},Ul=(e,t)=>(A("replaceXRanges",e,t),e.split(/\s+/).map(r=>_l(r,t)).join(" ")),_l=(e,t)=>{e=e.trim();let r=t.loose?k[O.XRANGELOOSE]:k[O.XRANGE];return e.replace(r,(n,o,s,i,a,l)=>{if(A("xRange",e,n,o,s,i,a,l),kl(s,i,a))return e;let u=C(s),p=u||C(i),d=p||C(a),E=d;return o==="="&&E&&(o=""),l=t.includePrerelease?"-0":"",u?o===">"||o==="<"?n="<0.0.0-0":n="*":o&&E?(p&&(i=0),a=0,o===">"?(o=">=",p?(s=+s+1,i=0,a=0):(i=+i+1,a=0)):o==="<="&&(o="<",p?s=+s+1:i=+i+1),o==="<"&&(l="-0"),n=`${o+s}.${i}.${a}${l}`):p?n=`>=${s}.0.0${l} <${+s+1}.0.0-0`:d&&(n=`>=${s}.${i}.0${l} <${s}.${+i+1}.0-0`),A("xRange return",n),n})},Fl=(e,t)=>(A("replaceStars",e,t),e.trim().replace(k[O.STAR],"")),jl=(e,t)=>(A("replaceGTE0",e,t),e.trim().replace(k[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),Bl=e=>(t,r,n,o,s,i,a,l,u,p,d,E)=>(C(n)?r="":C(o)?r=`>=${n}.0.0${e?"-0":""}`:C(s)?r=`>=${n}.${o}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,C(u)?l="":C(p)?l=`<${+u+1}.0.0-0`:C(d)?l=`<${u}.${+p+1}.0-0`:E?l=`<=${u}.${p}.${d}-${E}`:e?l=`<${u}.${p}.${+d+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),ql=(e,t,r)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let n=0;n<e.length;n++)if(A(e[n].semver),e[n].semver!==mr.ANY&&e[n].semver.prerelease.length>0){let o=e[n].semver;if(o.major===t.major&&o.minor===t.minor&&o.patch===t.patch)return!0}return!1}return!0}});var Ue=w((xm,ss)=>{"use strict";var _e=Symbol("SemVer ANY"),hr=class e{static get ANY(){return _e}constructor(t,r){if(r=es(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),gr("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===_e?this.value="":this.value=this.operator+this.semver.version,gr("comp",this)}parse(t){let r=this.options.loose?ts[rs.COMPARATORLOOSE]:ts[rs.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new ns(n[2],this.options.loose):this.semver=_e}toString(){return this.value}test(t){if(gr("Comparator.test",t,this.options.loose),this.semver===_e||t===_e)return!0;if(typeof t=="string")try{t=new ns(t,this.options)}catch{return!1}return fr(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 os(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new os(this.value,r).test(t.semver):(r=es(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("=")||fr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||fr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};ss.exports=hr;var es=rt(),{safeRe:ts,t:rs}=ye(),fr=ur(),gr=Me(),ns=T(),os=F()});var Fe=w((Dm,is)=>{"use strict";var Wl=F(),Gl=(e,t,r)=>{try{t=new Wl(t,r)}catch{return!1}return t.test(e)};is.exports=Gl});var cs=w((Mm,as)=>{"use strict";var Kl=F(),Vl=(e,t)=>new Kl(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));as.exports=Vl});var us=w((Lm,ls)=>{"use strict";var Hl=T(),Jl=F(),Xl=(e,t,r)=>{let n=null,o=null,s=null;try{s=new Jl(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!n||o.compare(i)===-1)&&(n=i,o=new Hl(n,r))}),n};ls.exports=Xl});var ds=w((Um,ps)=>{"use strict";var zl=T(),Yl=F(),Ql=(e,t,r)=>{let n=null,o=null,s=null;try{s=new Yl(t,r)}catch{return null}return e.forEach(i=>{s.test(i)&&(!n||o.compare(i)===1)&&(n=i,o=new zl(n,r))}),n};ps.exports=Ql});var gs=w((_m,fs)=>{"use strict";var yr=T(),Zl=F(),ms=Le(),eu=(e,t)=>{e=new Zl(e,t);let r=new yr("0.0.0");if(e.test(r)||(r=new yr("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n<e.set.length;++n){let o=e.set[n],s=null;o.forEach(i=>{let a=new yr(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||ms(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),s&&(!r||ms(r,s))&&(r=s)}return r&&e.test(r)?r:null};fs.exports=eu});var ys=w((Fm,hs)=>{"use strict";var tu=F(),ru=(e,t)=>{try{return new tu(e,t).range||"*"}catch{return null}};hs.exports=ru});var mt=w((jm,Rs)=>{"use strict";var nu=T(),Ss=Ue(),{ANY:ou}=Ss,su=F(),iu=Fe(),ws=Le(),Es=ct(),au=ut(),cu=lt(),lu=(e,t,r,n)=>{e=new nu(e,n),t=new su(t,n);let o,s,i,a,l;switch(r){case">":o=ws,s=au,i=Es,a=">",l=">=";break;case"<":o=Es,s=cu,i=ws,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(iu(e,t,n))return!1;for(let u=0;u<t.set.length;++u){let p=t.set[u],d=null,E=null;if(p.forEach(g=>{g.semver===ou&&(g=new Ss(">=0.0.0")),d=d||g,E=E||g,o(g.semver,d.semver,n)?d=g:i(g.semver,E.semver,n)&&(E=g)}),d.operator===a||d.operator===l||(!E.operator||E.operator===a)&&s(e,E.semver))return!1;if(E.operator===l&&i(e,E.semver))return!1}return!0};Rs.exports=lu});var As=w((Bm,bs)=>{"use strict";var uu=mt(),pu=(e,t,r)=>uu(e,t,">",r);bs.exports=pu});var Ps=w((qm,vs)=>{"use strict";var du=mt(),mu=(e,t,r)=>du(e,t,"<",r);vs.exports=mu});var Ts=w((Wm,Cs)=>{"use strict";var Is=F(),fu=(e,t,r)=>(e=new Is(e,r),t=new Is(t,r),e.intersects(t,r));Cs.exports=fu});var $s=w((Gm,Os)=>{"use strict";var gu=Fe(),hu=_();Os.exports=(e,t,r)=>{let n=[],o=null,s=null,i=e.sort((p,d)=>hu(p,d,r));for(let p of i)gu(p,t,r)?(s=p,o||(o=p)):(s&&n.push([o,s]),s=null,o=null);o&&n.push([o,null]);let a=[];for(let[p,d]of n)p===d?a.push(p):!d&&p===i[0]?a.push("*"):d?p===i[0]?a.push(`<=${d}`):a.push(`${p} - ${d}`):a.push(`>=${p}`);let l=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var Ls=w((Km,Ms)=>{"use strict";var Ns=F(),Sr=Ue(),{ANY:wr}=Sr,Er=Fe(),Rr=_(),yu=(e,t,r={})=>{if(e===t)return!0;e=new Ns(e,r),t=new Ns(t,r);let n=!1;e:for(let o of e.set){for(let s of t.set){let i=Eu(o,s,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},wu=[new Sr(">=0.0.0-0")],ks=[new Sr(">=0.0.0")],Eu=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===wr){if(t.length===1&&t[0].semver===wr)return!0;r.includePrerelease?e=wu:e=ks}if(t.length===1&&t[0].semver===wr){if(r.includePrerelease)return!0;t=ks}let n=new Set,o,s;for(let g of e)g.operator===">"||g.operator===">="?o=xs(o,g,r):g.operator==="<"||g.operator==="<="?s=Ds(s,g,r):n.add(g.semver);if(n.size>1)return null;let i;if(o&&s){if(i=Rr(o.semver,s.semver,r),i>0)return null;if(i===0&&(o.operator!==">="||s.operator!=="<="))return null}for(let g of n){if(o&&!Er(g,String(o),r)||s&&!Er(g,String(s),r))return null;for(let K of t)if(!Er(g,String(K),r))return!1;return!0}let a,l,u,p,d=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,E=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&s.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let g of t){if(p=p||g.operator===">"||g.operator===">=",u=u||g.operator==="<"||g.operator==="<=",o){if(E&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===E.major&&g.semver.minor===E.minor&&g.semver.patch===E.patch&&(E=!1),g.operator===">"||g.operator===">="){if(a=xs(o,g,r),a===g&&a!==o)return!1}else if(o.operator===">="&&!g.test(o.semver))return!1}if(s){if(d&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===d.major&&g.semver.minor===d.minor&&g.semver.patch===d.patch&&(d=!1),g.operator==="<"||g.operator==="<="){if(l=Ds(s,g,r),l===g&&l!==s)return!1}else if(s.operator==="<="&&!g.test(s.semver))return!1}if(!g.operator&&(s||o)&&i!==0)return!1}return!(o&&u&&!s&&i!==0||s&&p&&!o&&i!==0||E||d)},xs=(e,t,r)=>{if(!e)return t;let n=Rr(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},Ds=(e,t,r)=>{if(!e)return t;let n=Rr(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};Ms.exports=yu});var Ar=w((Vm,Fs)=>{"use strict";var br=ye(),Us=he(),Su=T(),_s=sr(),Ru=se(),bu=ao(),Au=lo(),vu=mo(),Pu=ho(),Iu=wo(),Cu=So(),Tu=bo(),Ou=vo(),$u=_(),Nu=To(),ku=$o(),xu=at(),Du=Do(),Mu=Lo(),Lu=Le(),Uu=ct(),_u=cr(),Fu=lr(),ju=lt(),Bu=ut(),qu=ur(),Wu=Ko(),Gu=Ho(),Ku=Ue(),Vu=F(),Hu=Fe(),Ju=cs(),Xu=us(),zu=ds(),Yu=gs(),Qu=ys(),Zu=mt(),ep=As(),tp=Ps(),rp=Ts(),np=$s(),op=Ls();Fs.exports={parse:Ru,valid:bu,clean:Au,inc:vu,diff:Pu,major:Iu,minor:Cu,patch:Tu,prerelease:Ou,compare:$u,rcompare:Nu,compareLoose:ku,compareBuild:xu,sort:Du,rsort:Mu,gt:Lu,lt:Uu,eq:_u,neq:Fu,gte:ju,lte:Bu,cmp:qu,coerce:Wu,truncate:Gu,Comparator:Ku,Range:Vu,satisfies:Hu,toComparators:Ju,maxSatisfying:Xu,minSatisfying:zu,minVersion:Yu,validRange:Qu,outside:Zu,gtr:ep,ltr:tp,intersects:rp,simplifyRange:np,subset:op,SemVer:Su,re:br.re,src:br.src,tokens:br.t,SEMVER_SPEC_VERSION:Us.SEMVER_SPEC_VERSION,RELEASE_TYPES:Us.RELEASE_TYPES,compareIdentifiers:_s.compareIdentifiers,rcompareIdentifiers:_s.rcompareIdentifiers}});var id={};aa(id,{handleError:()=>Qi,main:()=>Yi,run:()=>Zi});module.exports=ca(id);var Ie=require("@medplum/core"),Je=require("commander"),zi=require("node:fs");var q=require("@medplum/core"),xe=require("commander");var Xr=require("@medplum/core");var Hr=require("@medplum/core"),Y=require("node:fs"),Jr=require("node:os"),_t=require("node:path");var H=class extends Hr.ClientStorage{constructor(r){super();N(this,"dirName");N(this,"fileName");this.dirName=(0,_t.resolve)((0,Jr.homedir)(),".medplum"),this.fileName=(0,_t.resolve)(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,n){let o=this.readFile()??{};n?o[r]=n:delete o[r],this.writeFile(o)}getObject(r){let n=this.getString(r);return n?JSON.parse(n):void 0}setObject(r,n){this.setString(r,n?JSON.stringify(n):void 0)}readFile(){if((0,Y.existsSync)(this.fileName))return JSON.parse((0,Y.readFileSync)(this.fileName,"utf8"))}writeFile(r){(0,Y.existsSync)(this.dirName)||(0,Y.mkdirSync)(this.dirName),(0,Y.writeFileSync)(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function R(e,t=!0){let r=e.profile??"default",n=new H(r),o=n.getObject("options");if(r!=="default"&&!o)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:s,fhirUrlPath:i,accessToken:a,tokenUrl:l,authorizeUrl:u,clientId:p,clientSecret:d}=la(e,n),E=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await ua(e.baseUrl,E);let g=new Xr.MedplumClient({fetch:E,baseUrl:s,tokenUrl:l,fhirUrlPath:i,authorizeUrl:u,storage:n,onUnauthenticated:pa,verbose:e.verbose});return t&&(a?g.setAccessToken(a):p&&d&&(g.setBasicAuth(p,d),o?.authType!=="basic"&&await g.startClientLogin(p,d))),g}function la(e,t){let r=t.getObject("options"),n=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",o=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:n,fhirUrlPath:o,accessToken:s,tokenUrl:i,authorizeUrl:a,clientId:l,clientSecret:u}}async function ua(e,t){try{let r=new URL("healthcheck",e).toString(),n=await t(r);if(!n.ok)throw new Error(`Healthcheck returned status ${n.status}`);if((await n.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${n}`)}}function pa(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var x=require("@medplum/core"),bn=require("commander");var ce=new TextEncoder,zr=new TextDecoder,da=new TextDecoder("utf-8",{fatal:!0}),dd=2**32;function Yr(...e){let t=e.reduce((o,{length:s})=>o+s,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}var ma=/[^\x00-\x7f]/;function Xe(e){if(typeof e=="string"&&e.length>=128){if(ma.test(e))throw new TypeError("non-ASCII string encountered in encode()");return ce.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function Qr(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});let r=32768,n=[];for(let s=0;s<e.length;s+=r)n.push(String.fromCharCode.apply(null,e.subarray(s,s+r)));let o=btoa(n.join(""));return t?o.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):o}function Zr(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o);return n}var le=class extends Error{constructor(r,n){super(r,n);N(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};N(le,"code","ERR_JOSE_GENERIC");var Q=class extends le{constructor(){super(...arguments);N(this,"code","ERR_JOSE_NOT_SUPPORTED")}};N(Q,"code","ERR_JOSE_NOT_SUPPORTED");var L=class extends le{constructor(){super(...arguments);N(this,"code","ERR_JWS_INVALID")}};N(L,"code","ERR_JWS_INVALID");var Te=class extends le{constructor(){super(...arguments);N(this,"code","ERR_JWT_INVALID")}};N(Te,"code","ERR_JWT_INVALID");var en,tn,Ft=class extends(tn=le,en=Symbol.asyncIterator,tn){constructor(r="multiple matching keys found in the JSON Web Key Set",n){super(r,n);N(this,en,async function*(){});N(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};N(Ft,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var fa="The input to be decoded is not correctly encoded.";function rn(e){try{return Zr(typeof e=="string"?e:zr.decode(e),!0)}catch(t){throw new TypeError(fa,{cause:t})}}function Oe(e){return Qr(typeof e=="string"?ce.encode(e):e,!0)}function $e(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function nn(...e){let t=new Set;for(let r of e)if(r)for(let n of Object.keys(r)){if(t.has(n))return!1;t.add(n)}return!0}function on(e,t){if(e!==void 0)throw new TypeError(`${t} can only be called once`)}var sn={__proto__:null,b64:!0};function an(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function cn(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return[];if(!Array.isArray(n.crit)||n.crit.length===0||n.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?t:{__proto__:null,...r,...t};for(let i of n.crit){if(!(i in s))throw new Q(`Extension Header Parameter "${i}" is not recognized`);if(!Object.hasOwn(o,i)||o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s[i]&&(!Object.hasOwn(n,i)||n[i]===void 0))throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return n.crit}function ln(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!="boolean")throw new L('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function jt(e,t){let r,n;try{r=JSON.stringify(t),n=JSON.parse(r)}catch(o){throw new e("JOSE Header is not valid JSON",{cause:o})}if(!$e(n))throw new e("JOSE Header is not a JSON object");return[n,r]}var ga=e=>e[Symbol.toStringTag],ha=(e,t,r)=>{let{alg:n}=e;if(t.use!==void 0){let o=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==o)throw new TypeError(`Invalid key for this operation, its "use" must be "${o}" when present`)}if(t.alg!==void 0&&t.alg!==n)throw new TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(t.key_ops)){let o=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(o&&!t.key_ops.includes(o))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}};async function pn(e,t,r){let{alg:n,secret:o}=e,s=r==="decrypt"||r==="sign";if(o&&t instanceof Uint8Array)return t;let i,a;if($e(t)){if(i=va(t),typeof i.kty!="string")throw un(n,t,o);if(!(o?i.kty==="oct"&&typeof i.k=="string":i.kty!=="oct"&&(s?i.kty==="AKP"&&typeof i.priv=="string"||typeof i.d=="string":i.d===void 0&&i.priv===void 0)))throw new TypeError(o?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${s?"private":"public"} JWK`);if(ha(e,i,r),i.kty==="oct")return rn(i.k);if(!Object.isFrozen(t)){let{key_ops:p}=t;Array.isArray(p)&&Object.freeze(p),Object.freeze(t)}}else{if(!Ea(t))throw un(n,t,o);let p=o?"secret":s?"private":"public";if(t.type!==p&&(o||["secret","public","private"].includes(t.type)))throw new TypeError(`${ga(t)} instances must be of type "${p}" for the ${n} algorithm`);if(dn(t))return t;if(a=t,a.type==="secret")return a.export()}Bt||=new WeakMap;let l=t,u=Bt.get(l);if(u?.[n])return u[n];if(u||Bt.set(l,u={}),a&&typeof a.toCryptoKey=="function"){let p=a.type==="public",d=ya[a.asymmetricKeyDetails?.namedCurve],E=e.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return u[n]=a.toCryptoKey(E,p,e.usages[p?0:1])}return i??=a.export({format:"jwk"}),i.alg=n,u[n]=await Pa(e,i)}var Bt,ya={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};var dn=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},wa=e=>e?.[Symbol.toStringTag]==="KeyObject",Ea=e=>dn(e)||wa(e);function Sa(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}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}function un(e,t,r){let n=["CryptoKey","KeyObject","JSON Web Key"];return r&&n.push("Uint8Array"),new TypeError(Sa(`Key for the ${e} algorithm must be `,t,...n))}var ze=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Ra(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function mn(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function ba(e,t,r){let n=e.algorithm;if(n.name!==t.name)throw ze(t.name);if(t.hash&&n.hash?.name!==t.hash)throw ze(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw ze(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&n.length!==t.length)throw ze(t.length,"algorithm.length");Ra(e,r)}function Aa(e){return{__proto__:null,...e}}function va(e){let t=Aa(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,n=Array.isArray(r)?[...r]:void 0;if(!n||n.some(o=>typeof o!="string")||new Set(n).size!==n.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=n}return t}async function Pa(e,t,r){if(!e.kty.includes(t.kty))throw new Q('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let n=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,o=!!(t.d||t.priv),s={...t,ext:r??t.ext};return s.kty!=="AKP"&&delete s.alg,delete s.use,crypto.subtle.importKey("jwk",s,n,s.ext??!o,t.key_ops??e.usages[o?1:0])}async function fn(e,t,r,n=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,n,[r])),ba(e,t,r),e}function gn(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var Ne=[["verify"],["sign"]];function qt(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Ne}}function me(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:Ne,minRsaBits:2048}}function Wt(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Ne}}function hn(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Ne}}function Gt(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Ne}}var Ia=gn({HS256:qt(256),HS384:qt(384),HS512:qt(512),RS256:me(256),RS384:me(384),RS512:me(512),PS256:me(256,32),PS384:me(384,48),PS512:me(512,64),ES256:Wt("P-256",256),ES384:Wt("P-384",384),ES512:Wt("P-521",512),EdDSA:hn(),Ed25519:hn(),"ML-DSA-44":Gt(44),"ML-DSA-65":Gt(65),"ML-DSA-87":Gt(87)});function yn(e){let t=typeof e=="string"?Ia[e]:void 0;if(!t)throw new Q(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}var Ye=e=>Math.floor(e.getTime()/1e3),Ca={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Ta=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Kt(){throw new TypeError("Invalid time period format")}function wn(e){typeof e!="string"&&Kt();let t=Ta.exec(e);(!t||t[4]&&t[1])&&Kt();let r=parseFloat(t[2]),n=Math.round(r*Ca[t[3][0].toLowerCase()]);return Number.isFinite(n)||Kt(),t[1]==="-"||t[4]==="ago"?-n:n}function Jt(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function Vt(e,t){if(typeof t!="string")throw new TypeError(`"${e}" claim must be a string`)}function Oa(e){if(typeof e!="string"&&(!Array.isArray(e)||Array.from(e).some(t=>typeof t!="string")))throw new TypeError('"aud" claim must be a string or an array of strings')}function Ht(e,t){return typeof e=="number"?Jt(t,e):e instanceof Date?Jt(t,Ye(e)):Ye(new Date)+wn(e)}var En;function re(e){return En.get(e)}function Sn(e){let t=re(e);for(let r of["iat","nbf","exp"]){let n=t[r];if(typeof n=="number"&&!Number.isFinite(n))throw new TypeError(`"${r}" claim must be a finite number`)}return ce.encode(JSON.stringify(t))}var Qe=class{constructor(t={}){if(!$e(t))throw new TypeError("JWT Claims Set MUST be an object");(En||=new WeakMap).set(this,structuredClone(t))}setIssuer(t){return Vt("iss",t),re(this).iss=t,this}setSubject(t){return Vt("sub",t),re(this).sub=t,this}setAudience(t){return Oa(t),re(this).aud=t,this}setJti(t){return Vt("jti",t),re(this).jti=t,this}setNotBefore(t){return re(this).nbf=Ht(t,"setNotBefore"),this}setExpirationTime(t){return re(this).exp=Ht(t,"setExpirationTime"),this}setIssuedAt(t){let r=re(this);return t===void 0?r.iat=Ye(new Date):typeof t=="string"?r.iat=Jt("setIssuedAt",Ye(new Date)+wn(t)):r.iat=Ht(t,"setIssuedAt"),this}};async function $a(e,t,r){let[n,o,s,i]=e,a="";if(o!==void 0){let V=jt(L,o);o=V[0],a=Oe(V[1])}if(s!==void 0&&(s=jt(L,s)[0]),!o&&!s)throw new L("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!nn(o,s))throw new L("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let l={...o,...s};an(L,o);let u=ln(o,cn(L,sn,i,o,l));u||r?.();let{alg:p}=l;if(typeof p!="string"||!p)throw new L('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=yn(p),E="",g=n,K;if(u){let V=e[4];V?(E=V[0]??=Oe(n),g=V[1]??=Xe(E)):(E=Oe(n),K=ce.encode(`${a}.${E}`))}K??=Yr(Xe(a),Xe("."),g);let P=await fn(await pn(d,t,"sign"),d.subtle,"sign");d.minRsaBits&&mn(d.alg,P);let M={signature:Oe(new Uint8Array(await crypto.subtle.sign(d.signing,P,K))),payload:E};return o&&(M.protected=a),s&&(M.header=s),[M,u]}async function Rn(e,t,r,n,o){let[s]=await $a([e,t,void 0,r],n,o);return`${s.protected}.${s.payload}.${s.signature}`}var Na=Qe,fe,ke=class extends Na{constructor(){super(...arguments);Kr(this,fe)}setProtectedHeader(r){return on(Ut(this,fe),"setProtectedHeader"),Vr(this,fe,r),this}async sign(r,n){return Rn(Sn(this),Ut(this,fe),n?.crit,r,()=>{throw new Te("JWTs MUST NOT use unencoded payload")})}};fe=new WeakMap;var ge=require("node:crypto"),ne=require("node:fs"),Z=require("node:path"),An=require("node:util/types"),vn=require("tar");function ee(e){console.log(JSON.stringify(e,null,2))}async function Xt(e,t,r){let n=t.source,o=Ze(n);if(!o)return;console.log("Saving source code...");let s=await e.createAttachment({data:o,filename:(0,Z.basename)(n),contentType:Da(n)});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 n=t.dist??t.source,o=Ze(n);if(!o)return;console.log("Deploying bot...");let s=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:o,filename:(0,Z.basename)(n)});if(console.log("Deploy result: "+s.issue?.[0]?.details?.text),!(0,x.isOk)(s))throw new Error(`Bot deploy failed: ${(0,x.normalizeErrorString)(s)}`)}async function Yt(e,t,r,n,o,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),p={name:t,id:l.id,source:n,dist:o};await Xt(e,p,u),await zt(e,p,u),console.log(`Success! Bot created: ${u.id}`),i&&ka(p)}function Pn(e){let t=new RegExp("^"+xa(e).replaceAll(String.raw`\*`,".*")+"$"),r=J()?.bots?.filter(n=>t.test(n.name));return r||[]}function B(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 I(e,t){(0,ne.writeFileSync)((0,Z.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function J(e,t){let r=B(e,t),n=Ze(r);if(n)return JSON.parse(n)}function In(e){let t=Ze(B(e,{server:!0}));if(t)return JSON.parse(t)}function Ze(e){let t=(0,Z.resolve)(e);return(0,ne.existsSync)(t)?(0,ne.readFileSync)(t,"utf8"):""}function ka(e){let t=J()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ne.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function xa(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Cn(e){let n=0,o=0;return(0,vn.extract)({cwd:e,filter:(s,i)=>{if(n++,n>100)throw new Error("Tar extractor reached max number of files");if(o+=i.size,o>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Qt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function Da(e){let t=(0,Z.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?x.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?x.ContentType.TYPESCRIPT:x.ContentType.TEXT}function et(e,t){let r=new H(e),n={name:e,...t};return r.setObject("options",n),n}function Tn(e){return new H(e).getObject("options")}async function On(e,t){let r={typ:"JWT",alg:x.OAuthSigningAlgorithm.HS256},n=Math.floor(Date.now()/1e3),o={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:n,iat:n,exp:n+604800},s=(0,x.encodeBase64)(JSON.stringify(r)),i=(0,x.encodeBase64)(JSON.stringify(o)),a=`${s}.${i}`,l=(0,ge.createHmac)("sha256",t.clientSecret).update(a).digest("base64url"),u=`${a}.${l}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function $n(e,t){let r=(0,ge.createPrivateKey)((0,ne.readFileSync)((0,Z.resolve)(t.privateKeyPath))),n=await new ke({}).setProtectedHeader({typ:"JWT",alg:x.OAuthSigningAlgorithm.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,ge.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(n)}function y(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var h=class extends bn.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 n=e.registeredArguments.length,o=r.slice(0,n);o[n]=e.optsWithGlobals();try{let s=t(...o);(0,An.isPromise)(s)&&await s}finally{e.resetOptionDefaults()}}}var Dn=new h("status").aliases(["info","list","ls"]),Mn=new h("ping"),Ln=new h("push"),Un=new h("reload-config"),_n=new h("upgrade"),Fn=new h("stats"),oe=new h("agent");y(oe,Dn);y(oe,Mn);y(oe,Ln);y(oe,Un);y(oe,_n);y(oe,Fn);Dn.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 xe.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await tt({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let n=Bn(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:n.version,connectionStatus:n.status,statusLastUpdated:n.lastUpdated??"N/A"}}})});Mn.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 n=await R(r),o=await jn(n,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 n.pushToAgent(o,e,`PING ${s}`,q.ContentType.PING,!0,{maxRetries:0});console.info(i)}catch(i){throw new Error("Unexpected response from agent while pinging",{cause:i})}});Ln.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",q.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,n)=>{let o=await R(n),s=await jn(o,r,n),i;try{i=await o.pushToAgent(s,{reference:`Device/${e}`},t,n.contentType,n.wait!==!1,{maxRetries:0})}catch(a){throw new Error("Unexpected response from agent while pushing message to agent",{cause:a})}console.info(i)});Un.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 xe.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await tt({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});_n.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 xe.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 tt({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:n=>({id:n.agent.id,name:n.agent.name,version:t.agentVersion??"latest"})})});Fn.description("Get runtime statistics for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) to get stats for. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to get stats for. Mutually exclusive with [agentIds...] arg").addOption(new xe.Option("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await tt({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:n}=Bn(r.result,{required:["stats"]}),o;try{o=JSON.parse(n)}catch(s){console.error(`Failed to parse stats for agent ${r.agent.id}: ${(0,q.normalizeErrorString)(s)}`)}return{id:r.agent.id,name:r.agent.name,stats:o}},renderSuccessfulRows:r=>{for(let n=0;n<r.length;n++)n>0&&console.info(),La(r[n])}})});var Nn=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function kn(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function xn(e){return e?Object.entries(e).filter(([,t])=>t?.rtt).map(([t,r])=>({name:t,count:r.rtt.count,pending:r.rtt.pendingCount,"min (ms)":r.rtt.min,"avg (ms)":r.rtt.average,"max (ms)":r.rtt.max,"p50 (ms)":r.rtt.p50,"p95 (ms)":r.rtt.p95,"p99 (ms)":r.rtt.p99})):[]}function La(e){let t=e.name?`${e.name} (${e.id})`:e.id;if(console.info(`Agent: ${t}`),!e.stats){console.info(" (stats unavailable)");return}let r={};for(let i of Nn)r[i]=kn(e.stats[i]);let n=new Set([...Nn,"channelStats","clientStats"]);for(let[i,a]of Object.entries(e.stats))n.has(i)||(r[i]=kn(a));console.table(r);let o=xn(e.stats.channelStats);o.length&&(console.info("Channel Stats:"),console.table(o));let s=xn(e.stats.clientStats);s.length&&(console.info("Client Stats:"),console.table(s))}async function tt({operation:e,agentIds:t,options:r,params:n={},parseSuccessfulResponse:o,renderSuccessfulRows:s}){let i=ja(t,r),a=await R(r),l=i.type==="criteria"?i.criteria:`Agent?_id=${i.ids.join(",")}`,u=new URLSearchParams(l.split("?")[1]);for(let[P,M]of Object.entries(n))u.append(P,M.toString());let p;try{let P=a.fhirUrl("Agent",e);P.search=u.toString(),p=await a.get(P,{cache:"reload"})}catch(P){throw new Error(`Operation '${e}' failed`,{cause:P})}if(r.output==="json"){console.info(JSON.stringify(p,null,2));return}let d=[],E=[];switch(p.resourceType){case"Bundle":{let P=Ua(p);for(let M of P)M.result.resourceType==="Parameters"||(0,q.isOk)(M.result)?d.push(M):E.push(M);break}case"Parameters":case"OperationOutcome":{let P=await a.searchOne("Agent",u,{cache:"reload"});if(!P)throw new Error("Agent not found");p.resourceType==="Parameters"?d.push({agent:P,result:p}):E.push({agent:P,result:p});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(p)}`)}let g=[];for(let P of d){let M=o(P);g.push(M)}let K=[];for(let P of E){let V=P.result.issue?.[0],ea={id:P.agent.id,name:P.agent.name,severity:V.severity,code:V.code,details:V.details?.text??"No details to show"};K.push(ea)}console.info(`
|
|
3
3
|
${g.length} successful response(s):
|
|
4
|
-
`),s?g.length?s(g):console.info("No successful responses received"):console.table(g.length?g:"No successful responses received"),console.info(),K.length&&(console.info(`${K.length} failed response(s):`),console.info(),console.table(K))}async function jn(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 n;if(t)n=t;else{qn(r.criteria);let o=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!o?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(o.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");n=o.entry[0].resource?.id}return{reference:`Agent/${n}`}}function Ua(e){let t=[];for(let r of e.entry??q.EMPTY){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(_a(r.resource))}return t}function _a(e){let t=e.parameter?.find(n=>n.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(n=>n.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 Bn(e,t){let r={},n=t.required,o=t.optional;for(let s of n){let i=e.parameter?.find(l=>l.name===s);if(!i)throw new Error(`Failed to find parameter '${s}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${s}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${s}'`);r[s]=i[a]}if(o?.length)for(let s of o){let i=e.parameter?.find(l=>l.name===s);if(!i)continue;let a=Fa(s,i);r[s]=a}return r}function Fa(e,t){let r;for(let n in t)if(n.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=n}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function ja(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,q.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return qn(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function qn(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,n]=e.split("?");if(r!=="Agent"||!n)throw new Error(t);try{new URLSearchParams(n)}catch(o){throw new Error(t,{cause:o})}if(!n.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}var W=require("@medplum/core"),Wn=require("node:child_process"),Gn=require("node:http"),Kn=require("node:os"),Vn=require("node:util");var Ba=(0,Vn.promisify)(Wn.exec),Hn=W.MEDPLUM_CLI_CLIENT_ID,Jn="http://localhost:9615",Zt=new h("login"),er=new h("whoami"),tr=new h("token");Zt.action(async e=>{let t=e.profile??"default",r=et(t,e),n=await R(e,!1);await qa(n,r)});er.action(async e=>{let t=await R(e);Ka(t)});tr.action(async e=>{let t=await R(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function qa(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Va(e,t);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 On(e,t);break;case"jwt-assertion":await $n(e,t);break}}async function Wa(e){let t=(0,Gn.createServer)(async(r,n)=>{let o=new URL(r.url,"http://localhost:9615"),s=o.searchParams.get("code");if(r.method==="OPTIONS"){n.writeHead(200,{Allow:"GET, POST","Content-Type":W.ContentType.TEXT}),n.end("OK");return}if(o.pathname==="/"&&s)try{let i=await e.processCode(s,{clientId:Hn,redirectUri:Jn});n.writeHead(200,{"Content-Type":W.ContentType.TEXT}),n.end(`Signed in as ${(0,W.getDisplayString)(i)}. You may close this window.`)}catch(i){n.writeHead(400,{"Content-Type":W.ContentType.TEXT}),n.end(`Error: ${(0,W.normalizeErrorString)(i)}`)}finally{t.close(),process.exit(0)}else n.writeHead(404,{"Content-Type":W.ContentType.TEXT}),n.end("Not found")}).listen(9615)}async function Ga(e){let t=(0,Kn.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)}await Ba(r)}function Ka(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 Va(e,t){await Wa(e);let r=new URL(e.getAuthorizeUrl());r.searchParams.set("client_id",Hn),r.searchParams.set("redirect_uri",Jn),r.searchParams.set("scope",t.scope??"openid offline_access"),r.searchParams.set("response_type","code"),r.searchParams.set("prompt","login"),await Ga(r.toString())}var De="\x1B[0m",Ha="\x1B[1m",Ja="\x1B[31m",Xa="\x1B[32m",za="\x1B[33m",Ya="\x1B[34m",ue={red:e=>`${Ja}${e}${De}`,green:e=>`${Xa}${e}${De}`,yellow:e=>`${za}${e}${De}`,blue:e=>`${Ya}${e}${De}`,bold:e=>`${Ha}${e}${De}`},rr=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>ue.bold(r));var te=require("@aws-sdk/client-cloudformation"),Et=require("@aws-sdk/client-cloudfront"),qs=require("@aws-sdk/client-ecs"),Ws=require("@aws-sdk/client-s3"),Ee=require("@aws-sdk/client-ssm"),St=require("@aws-sdk/client-sts"),Rt=require("@medplum/core"),Gs=require("node:fs"),Ks=
|
|
4
|
+
`),s?g.length?s(g):console.info("No successful responses received"):console.table(g.length?g:"No successful responses received"),console.info(),K.length&&(console.info(`${K.length} failed response(s):`),console.info(),console.table(K))}async function jn(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 n;if(t)n=t;else{qn(r.criteria);let o=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!o?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(o.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");n=o.entry[0].resource?.id}return{reference:`Agent/${n}`}}function Ua(e){let t=[];for(let r of e.entry??q.EMPTY){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(_a(r.resource))}return t}function _a(e){let t=e.parameter?.find(n=>n.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(n=>n.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 Bn(e,t){let r={},n=t.required,o=t.optional;for(let s of n){let i=e.parameter?.find(l=>l.name===s);if(!i)throw new Error(`Failed to find parameter '${s}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${s}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${s}'`);r[s]=i[a]}if(o?.length)for(let s of o){let i=e.parameter?.find(l=>l.name===s);if(!i)continue;let a=Fa(s,i);r[s]=a}return r}function Fa(e,t){let r;for(let n in t)if(n.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=n}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function ja(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,q.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return qn(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function qn(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,n]=e.split("?");if(r!=="Agent"||!n)throw new Error(t);try{new URLSearchParams(n)}catch(o){throw new Error(t,{cause:o})}if(!n.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}var W=require("@medplum/core"),Wn=require("node:child_process"),Gn=require("node:http"),Kn=require("node:os"),Vn=require("node:util");var Ba=(0,Vn.promisify)(Wn.exec),Hn=W.MEDPLUM_CLI_CLIENT_ID,Jn="http://localhost:9615",Zt=new h("login"),er=new h("whoami"),tr=new h("token");Zt.action(async e=>{let t=e.profile??"default",r=et(t,e),n=await R(e,!1);await qa(n,r)});er.action(async e=>{let t=await R(e);Ka(t)});tr.action(async e=>{let t=await R(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function qa(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Va(e,t);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 On(e,t);break;case"jwt-assertion":await $n(e,t);break}}async function Wa(e){let t=(0,Gn.createServer)(async(r,n)=>{let o=new URL(r.url,"http://localhost:9615"),s=o.searchParams.get("code");if(r.method==="OPTIONS"){n.writeHead(200,{Allow:"GET, POST","Content-Type":W.ContentType.TEXT}),n.end("OK");return}if(o.pathname==="/"&&s)try{let i=await e.processCode(s,{clientId:Hn,redirectUri:Jn});n.writeHead(200,{"Content-Type":W.ContentType.TEXT}),n.end(`Signed in as ${(0,W.getDisplayString)(i)}. You may close this window.`)}catch(i){n.writeHead(400,{"Content-Type":W.ContentType.TEXT}),n.end(`Error: ${(0,W.normalizeErrorString)(i)}`)}finally{t.close(),process.exit(0)}else n.writeHead(404,{"Content-Type":W.ContentType.TEXT}),n.end("Not found")}).listen(9615)}async function Ga(e){let t=(0,Kn.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)}await Ba(r)}function Ka(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 Va(e,t){await Wa(e);let r=new URL(e.getAuthorizeUrl());r.searchParams.set("client_id",Hn),r.searchParams.set("redirect_uri",Jn),r.searchParams.set("scope",t.scope??"openid offline_access"),r.searchParams.set("response_type","code"),r.searchParams.set("prompt","login"),await Ga(r.toString())}var De="\x1B[0m",Ha="\x1B[1m",Ja="\x1B[31m",Xa="\x1B[32m",za="\x1B[33m",Ya="\x1B[34m",ue={red:e=>`${Ja}${e}${De}`,green:e=>`${Xa}${e}${De}`,yellow:e=>`${za}${e}${De}`,blue:e=>`${Ya}${e}${De}`,bold:e=>`${Ha}${e}${De}`},rr=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>ue.bold(r));var te=require("@aws-sdk/client-cloudformation"),Et=require("@aws-sdk/client-cloudfront"),qs=require("@aws-sdk/client-ecs"),Ws=require("@aws-sdk/client-s3"),Ee=require("@aws-sdk/client-ssm"),St=require("@aws-sdk/client-sts"),Rt=require("@medplum/core"),Gs=require("node:fs"),Ks=z(Ar(),1);var js=z(require("node:readline"),1),ft;function gt(){ft=js.default.createInterface({input:process.stdin,output:process.stdout})}function ht(){ft.close()}function c(e){ft.write(e+`
|
|
5
5
|
`)}function v(e){c(`
|
|
6
6
|
`+e+`
|
|
7
|
-
`)}function D(e,t=""){return new Promise(r=>{ft.question(e+(t?" ("+t+")":"")+" ",n=>{r(n||t.toString())})})}async function yt(e,t,r=""){let n=e+" ["+t.map(o=>o===r?"("+o+")":o).join("|")+"]";for(;;){let o=await D(n)||r;if(t.includes(o))return o;c("Please choose one of the following options: "+t.join(", "))}}async function we(e,t,r){return Number.parseInt(await yt(e,t.map(n=>n.toString()),r.toString()),10)}async function ie(e){return(await yt(e,["y","n"])).toLowerCase()==="y"}async function je(e){if(!await ie(e))throw c("Exiting..."),new Error("User cancelled")}var wt=new te.CloudFormationClient({}),sp=new Et.CloudFrontClient({region:"us-east-1"}),zm=new qs.ECSClient({}),Be=new Ws.S3Client({}),ip="medplum:environment";async function vr(){let e=[],t=(0,te.paginateListStacks)({client:wt},{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 n of r.StackSummaries??Rt.EMPTY)e.push(n);return e}async function Se(e){let t=await vr();for(let r of t){let n=r.StackName,o=await Pr(n);if(o?.tag===e)return o}}async function Pr(e){let t={};if(await Bs(wt,e,t),await wt.config.region()!=="us-east-1")try{await Bs(new te.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Bs(e,t,r){let n=new te.DescribeStacksCommand({StackName:t}),s=(await e.send(n))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===ip);if(!i)return;let a=await e.send(new te.DescribeStackResourcesCommand({StackName:t}));if(a.StackResources){e===wt&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)ap(l,r)}}function ap(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: ${cp(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 cp(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function At(e){let t=await sp.send(new Et.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function vt(e){let n=(await(await fetch("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(o=>o.tag_name.startsWith("v")?o.tag_name.slice(1):o.tag_name);return n.sort((o,s)=>Ks.compare(s,o)),e?n.slice(0,n.indexOf(e)):n}async function Pt(e,t,r){let n=new Ee.SSMClient({region:e});for(let[o,s]of Object.entries(r)){let i=t+o,a=typeof s=="object"?JSON.stringify(s):s.toString(),l=await lp(n,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await je(`Do you want to overwrite "${i}"?`)),await up(n,i,a)}}async function lp(e,t){let r=new Ee.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(n){if(n.name==="ParameterNotFound")return;throw n}}async function up(e,t,r){let n=new Ee.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(n)}function ae(e,t){if(console.log(`Config not found: ${e} (${B(e,t)})`),t){let n=Object.entries(t);if(n.length>0){console.log("Additional options:");for(let[o,s]of n)console.log(` ${o}: ${s}`)}}console.log();let r=(0,Gs.readdirSync)(".",{withFileTypes:!0});if(r=r.filter(n=>n.isFile()&&n.name.startsWith("medplum.")&&n.name.endsWith(".json")).map(n=>n.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let n of r)console.log(` ${n.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${n})`)}}async function Re(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new St.STSClient,r=new St.GetCallerIdentityCommand({}),n=await t.send(r),o=await t.config.region();console.log("AWS Region: ",o),console.log("AWS Account ID: ",n.Account),console.log("AWS Account ARN: ",n.Arn),console.log("AWS User ID: ",n.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",(0,Rt.normalizeErrorString)(t))}}async function Vs(e){let t=await Se(e);if(!t)throw await Re(e),new Error(`Stack not found: ${e}`);bt(t)}var pe=require("@aws-sdk/client-acm"),It=require("@aws-sdk/client-cloudfront"),Ct=require("@aws-sdk/client-sts"),Js=require("@medplum/core"),qe=require("node:crypto"),Xs=require("node:fs");var pp=e=>`${e}DomainName`,zs=e=>`${e}SslCertArn`;async function Ys(){let e={apiPort:8103,region:"us-east-1"};gt(),v("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 dp(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 je("Do you want to continue without AWS credentials?")),v("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await D("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),v("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await D("What is the config file name?",`medplum.${e.name}.config.json`);(0,Xs.existsSync)(r)&&(c("Config file already exists."),await je("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),I(r,e),v("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await D("Enter your AWS region:","us-east-1"),I(r,e),v("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await D("What is your AWS account number?",t),I(r,e),v("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let n="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await D("Enter your CloudFormation stack name?",n),I(r,e),v("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await D("Enter your base domain name:");I(r,e),v("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 o=await D("Enter your support email address:");v("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await D("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,I(r,e),v("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await D("Enter your web application domain name:","app."+e.domainName),I(r,e),v("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await D("Enter your storage domain name:","storage."+e.domainName),I(r,e),v("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await D("Enter your storage bucket name:",e.storageDomainName),I(r,e),v("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 we("Enter the maximum number of availability zones:",[2,3,99],2),v("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 ie("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 we("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"),I(r,e),v("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 we("Enter the number of server instances:",[1,2,3,4,6,8],1),I(r,e),v("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 we("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),I(r,e),v("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 we("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),I(r,e),v("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 vt())[0]??"latest";e.serverImage=await D("Enter the server image:",`medplum/medplum-server:${s}`),I(r,e),v("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await hp(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,I(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.')),v("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await mp(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:p}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let d=await fp(e,a,u,p);e[zs(p)]=d,I(r,e)}v("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:o};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await ie("Do you want to store these values in AWS Parameter Store?"))await Pt(e.region,`/medplum/${e.name}/`,l);else{let u=B(e.name,{server:!0});I(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.")}v("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(""),ht()}async function dp(e){try{let t=new Ct.STSClient({region:e}),r=new Ct.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function mp(e){let t=await Hs(e);if(e!=="us-east-1"){let r=await Hs("us-east-1");t.push(...r)}return t}async function Hs(e){try{let t=new pe.ACMClient({region:e}),r=new pe.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function fp(e,t,r,n){let o=e[pp(n)],s=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===o);if(s)return c(`Found existing certificate for "${o}" in "${r}.`),s.CertificateArn;if(c(`No existing certificate found for "${o}" in "${r}.`),!await ie("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${zs(n)}" setting.`),"TODO";let i=await gp(r,o);return c("Certificate ARN: "+i),i}async function gp(e,t){try{let r=await yt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),n=new pe.ACMClient({region:e}),o=new pe.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await n.send(o)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function hp(e,t){let r=(0,qe.randomUUID)(),n=(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 It.CloudFrontClient({region:e}).send(new It.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,qe.randomUUID)(),EncodedKey:n.publicKey}}))).PublicKey?.Id,publicKey:n.publicKey,privateKey:n.privateKey,passphrase:r}}catch(o){console.log("Error: Unable to create signing key: ",(0,Js.normalizeErrorString)(o));return}}async function Qs(){let e=await vr();for(let t of e){let r=t.StackName,n=await Pr(r);n&&(bt(n),console.log(""))}}var Zs=require("@aws-sdk/client-s3"),G=require("@medplum/core"),ei=H(require("fast-glob"),1),j=require("node:fs"),ti=require("node:os"),de=require("node:path"),ri=require("node:stream"),ni=require("node:stream/promises");async function oi(e,t){let r=X(e,t);if(!r)throw ae(e,t),new Error(`Config not found: ${e}`);let n=await Se(e);if(!n)throw await Re(e),new Error(`Stack not found: ${e}`);let o=n.appBucket;if(!o)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 wp("@medplum/app",i)}si(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 Sp(s,o.PhysicalResourceId,t),n.appDistribution?.PhysicalResourceId&&!t.dryrun&&await At(n.appDistribution.PhysicalResourceId),console.log("Done")}async function yp(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await fetch(r)).json()}async function wp(e,t){let n=(await yp(e,t)).dist.tarball,o=(0,j.mkdtempSync)((0,de.join)((0,ti.tmpdir)(),"tarball-"));try{let s=await fetch(n);if(!s.body)throw new Error("Received empty response body");let i=Cn(o);return await(0,ni.pipeline)(ri.Readable.fromWeb(s.body),i),(0,de.join)(o,"package","dist")}catch(s){throw(0,j.rmSync)(o,{recursive:!0,force:!0}),s}}function si(e,t){for(let r of(0,j.readdirSync)(e,{withFileTypes:!0})){let n=(0,de.join)(e,r.name);r.isDirectory()?si(n,t):r.isFile()&&n.endsWith(".js")&&Ep(n,t)}}function Ep(e,t){let r=(0,j.readFileSync)(e,"utf-8");for(let[n,o]of Object.entries(t))r=r.replaceAll(`__${n}__`,o);(0,j.writeFileSync)(e,r)}async function Sp(e,t,r){let n=[["assets/**/*.css",G.ContentType.CSS,!0],["assets/**/*.css.map",G.ContentType.JSON,!0],["assets/**/*.js",G.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",G.ContentType.JSON,!0],["assets/**/*.txt",G.ContentType.TEXT,!0],["assets/**/*.ico",G.ContentType.FAVICON,!0],["img/**/*.png",G.ContentType.PNG,!0],["img/**/*.svg",G.ContentType.SVG,!0],["robots.txt",G.ContentType.TEXT,!0],["index.html",G.ContentType.HTML,!1]];for(let o of n)await Rp({rootDir:e,bucketName:t,fileNamePattern:o[0],contentType:o[1],cached:o[2],dryrun:r.dryrun})}async function Rp(e){let t=ei.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await bp((0,de.join)(e.rootDir,r),e)}async function bp(e,t){let r=(0,j.createReadStream)(e),n=e.substring(t.rootDir.length+1).split(de.sep).join("/"),o={Bucket:t.bucketName,Key:n,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${n} to ${t.bucketName}...`),t.dryrun||await Be.send(new Zs.PutObjectCommand(o))}var Tt=require("@aws-sdk/client-s3");async function ci(e,t){if(!X(e,t))throw ae(e,t),new Error(`Config not found: ${e}`);let n=await Se(e);if(!n)throw await Re(e),new Error(`Stack not found: ${e}`);try{await ii("App",n.appBucket,n.appDistribution,n.appOriginAccessIdentity,t)}catch(o){console.error(`Error updating App bucket policy: ${o.message}`)}try{await ii("Storage",n.storageBucket,n.storageDistribution,n.storageOriginAccessIdentity,t)}catch(o){console.error(`Error updating Storage bucket policy: ${o.message}`)}console.log("Done")}async function ii(e,t,r,n,o){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!n?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let s=t.PhysicalResourceId,i=n.PhysicalResourceId,a=await Ap(s);if(Pp(a,s,i))throw new Error(`${e} bucket already has policy statement`);Ip(a,s,i),e==="Storage"&&o.guarddutyMalwareProtection&&Cp(a,s,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),o.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await vp(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await At(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Ap(e){let t=await Be.send(new Tt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function vp(e,t){await Be.send(new Tt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Pp(e,t,r){return!!e?.Statement?.some(n=>n?.Effect==="Allow"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(n?.Action)&&n?.Action?.includes("s3:GetObject*")&&n?.Action?.includes("s3:GetBucket*")&&n?.Action?.includes("s3:List*")&&Array.isArray(n?.Resource)&&n?.Resource?.includes(`arn:aws:s3:::${t}`)&&n?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Ip(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}/*`]})}function Cp(e,t,r){e.Statement?.some(n=>n?.Effect==="Deny"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&ai(n,"s3:GetObject")&&ai(n,"s3:GetObjectVersion")&&n?.Condition?.StringNotEquals?.["s3:ExistingObjectTag/GuardDutyMalwareScanStatus"]==="NO_THREATS_FOUND")||e.Statement?.push({Sid:"GuardDutyMalwareProtectionReadGate",Effect:"Deny",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject","s3:GetObjectVersion"],Resource:`arn:aws:s3:::${t}/*`,Condition:{StringNotEquals:{"s3:ExistingObjectTag/GuardDutyMalwareScanStatus":"NO_THREATS_FOUND"}}})}function ai(e,t){return e.Action===t?!0:Array.isArray(e.Action)&&e.Action.includes(t)}async function li(e,t){try{gt();let r=X(e,t);if(!r)throw ae(e,t),new Error(`Config not found: ${e}`);let n=In(e)??{};if(!t.yes&&Object.keys(n).length===0){let o=B(e,{server:!0});if(console.log(ue.yellow(`Config file ${o} not found!`)),!await ie("Do you want to proceed?")){console.log(ue.red(`Run Aborted, please ensure ${o} is present and try again.`));return}}Tp(r,n),$p(r,n),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({...n,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(ue.yellow("Dry run - skipping updates!")):(t.yes||await ie("Do you want to store these values in AWS Parameter Store?"))&&await Pt(r.region,`/medplum/${r.name}/`,n)}finally{ht()}}function Tp(e,t){Ot(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Ot(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Ot(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Ot(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Ot(e,t,r){if(Op(e,t))throw new Error(r)}function Op(e,t){return e!==void 0&&t!==void 0&&e!==t}function $p(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 pi=require("node:child_process"),be=H(Ar(),1);async function di(e,t){let r=await R(t),n=X(e,t);if(!n)throw console.log(`Configuration file ${B(e)} not found`),ae(e,t),new Error(`Config not found: ${e}`);let o=n.serverImage.lastIndexOf(":"),s=n.serverImage.slice(0,o),i=await Np(r,n),a=await ui(i);for(;a;){if(t.toVersion&&be.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),n.serverImage=`${s}:${a}`,kp(e,n),await r.startAsyncRequest("/admin/super/migrate"),a=await ui(a)}}async function Np(e,t){let r=t.serverImage.lastIndexOf(":"),n=t.serverImage.slice(r+1);if(n==="latest"){n=(await e.get("/healthcheck")).version;let s=n.indexOf("-");s>-1&&(n=n.slice(0,s))}return n}async function ui(e,t){let r=await vt(e),n=r[0];return r.filter(o=>o===n||o===t||be.gte(o,be.inc(e,"minor"))).pop()}function kp(e,t){let r=B(e);I(r,t);let n=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+n);let o=(0,pi.spawnSync)(n,{stdio:"inherit"});if(o.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${o.status}): ${o.stderr}`);console.log(o.stdout)}function mi(){let e=new h("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Ys),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Qs),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Vs),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(rr(`Update the AWS Parameter Store config values.
|
|
7
|
+
`)}function D(e,t=""){return new Promise(r=>{ft.question(e+(t?" ("+t+")":"")+" ",n=>{r(n||t.toString())})})}async function yt(e,t,r=""){let n=e+" ["+t.map(o=>o===r?"("+o+")":o).join("|")+"]";for(;;){let o=await D(n)||r;if(t.includes(o))return o;c("Please choose one of the following options: "+t.join(", "))}}async function we(e,t,r){return Number.parseInt(await yt(e,t.map(n=>n.toString()),r.toString()),10)}async function ie(e){return(await yt(e,["y","n"])).toLowerCase()==="y"}async function je(e){if(!await ie(e))throw c("Exiting..."),new Error("User cancelled")}var wt=new te.CloudFormationClient({}),sp=new Et.CloudFrontClient({region:"us-east-1"}),zm=new qs.ECSClient({}),Be=new Ws.S3Client({}),ip="medplum:environment";async function vr(){let e=[],t=(0,te.paginateListStacks)({client:wt},{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 n of r.StackSummaries??Rt.EMPTY)e.push(n);return e}async function Se(e){let t=await vr();for(let r of t){let n=r.StackName,o=await Pr(n);if(o?.tag===e)return o}}async function Pr(e){let t={};if(await Bs(wt,e,t),await wt.config.region()!=="us-east-1")try{await Bs(new te.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Bs(e,t,r){let n=new te.DescribeStacksCommand({StackName:t}),s=(await e.send(n))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===ip);if(!i)return;let a=await e.send(new te.DescribeStackResourcesCommand({StackName:t}));if(a.StackResources){e===wt&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)ap(l,r)}}function ap(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: ${cp(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 cp(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function At(e){let t=await sp.send(new Et.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function vt(e){let n=(await(await fetch("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(o=>o.tag_name.startsWith("v")?o.tag_name.slice(1):o.tag_name);return n.sort((o,s)=>Ks.compare(s,o)),e?n.slice(0,n.indexOf(e)):n}async function Pt(e,t,r){let n=new Ee.SSMClient({region:e});for(let[o,s]of Object.entries(r)){let i=t+o,a=typeof s=="object"?JSON.stringify(s):s.toString(),l=await lp(n,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await je(`Do you want to overwrite "${i}"?`)),await up(n,i,a)}}async function lp(e,t){let r=new Ee.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(n){if(n.name==="ParameterNotFound")return;throw n}}async function up(e,t,r){let n=new Ee.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(n)}function ae(e,t){if(console.log(`Config not found: ${e} (${B(e,t)})`),t){let n=Object.entries(t);if(n.length>0){console.log("Additional options:");for(let[o,s]of n)console.log(` ${o}: ${s}`)}}console.log();let r=(0,Gs.readdirSync)(".",{withFileTypes:!0});if(r=r.filter(n=>n.isFile()&&n.name.startsWith("medplum.")&&n.name.endsWith(".json")).map(n=>n.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let n of r)console.log(` ${n.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${n})`)}}async function Re(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new St.STSClient,r=new St.GetCallerIdentityCommand({}),n=await t.send(r),o=await t.config.region();console.log("AWS Region: ",o),console.log("AWS Account ID: ",n.Account),console.log("AWS Account ARN: ",n.Arn),console.log("AWS User ID: ",n.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",(0,Rt.normalizeErrorString)(t))}}async function Vs(e){let t=await Se(e);if(!t)throw await Re(e),new Error(`Stack not found: ${e}`);bt(t)}var pe=require("@aws-sdk/client-acm"),It=require("@aws-sdk/client-cloudfront"),Ct=require("@aws-sdk/client-sts"),Js=require("@medplum/core"),qe=require("node:crypto"),Xs=require("node:fs");var pp=e=>`${e}DomainName`,zs=e=>`${e}SslCertArn`;async function Ys(){let e={apiPort:8103,region:"us-east-1"};gt(),v("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 dp(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 je("Do you want to continue without AWS credentials?")),v("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await D("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),v("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await D("What is the config file name?",`medplum.${e.name}.config.json`);(0,Xs.existsSync)(r)&&(c("Config file already exists."),await je("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),I(r,e),v("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await D("Enter your AWS region:","us-east-1"),I(r,e),v("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await D("What is your AWS account number?",t),I(r,e),v("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let n="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await D("Enter your CloudFormation stack name?",n),I(r,e),v("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await D("Enter your base domain name:");I(r,e),v("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 o=await D("Enter your support email address:");v("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await D("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,I(r,e),v("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await D("Enter your web application domain name:","app."+e.domainName),I(r,e),v("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await D("Enter your storage domain name:","storage."+e.domainName),I(r,e),v("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await D("Enter your storage bucket name:",e.storageDomainName),I(r,e),v("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 we("Enter the maximum number of availability zones:",[2,3,99],2),v("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 ie("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 we("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"),I(r,e),v("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 we("Enter the number of server instances:",[1,2,3,4,6,8],1),I(r,e),v("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 we("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),I(r,e),v("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 we("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),I(r,e),v("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 vt())[0]??"latest";e.serverImage=await D("Enter the server image:",`medplum/medplum-server:${s}`),I(r,e),v("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await hp(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,I(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.')),v("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await mp(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:p}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let d=await fp(e,a,u,p);e[zs(p)]=d,I(r,e)}v("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:o};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await ie("Do you want to store these values in AWS Parameter Store?"))await Pt(e.region,`/medplum/${e.name}/`,l);else{let u=B(e.name,{server:!0});I(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.")}v("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(""),ht()}async function dp(e){try{let t=new Ct.STSClient({region:e}),r=new Ct.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function mp(e){let t=await Hs(e);if(e!=="us-east-1"){let r=await Hs("us-east-1");t.push(...r)}return t}async function Hs(e){try{let t=new pe.ACMClient({region:e}),r=new pe.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function fp(e,t,r,n){let o=e[pp(n)],s=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===o);if(s)return c(`Found existing certificate for "${o}" in "${r}.`),s.CertificateArn;if(c(`No existing certificate found for "${o}" in "${r}.`),!await ie("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${zs(n)}" setting.`),"TODO";let i=await gp(r,o);return c("Certificate ARN: "+i),i}async function gp(e,t){try{let r=await yt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),n=new pe.ACMClient({region:e}),o=new pe.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await n.send(o)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function hp(e,t){let r=(0,qe.randomUUID)(),n=(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 It.CloudFrontClient({region:e}).send(new It.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,qe.randomUUID)(),EncodedKey:n.publicKey}}))).PublicKey?.Id,publicKey:n.publicKey,privateKey:n.privateKey,passphrase:r}}catch(o){console.log("Error: Unable to create signing key: ",(0,Js.normalizeErrorString)(o));return}}async function Qs(){let e=await vr();for(let t of e){let r=t.StackName,n=await Pr(r);n&&(bt(n),console.log(""))}}var Zs=require("@aws-sdk/client-s3"),G=require("@medplum/core"),ei=z(require("fast-glob"),1),j=require("node:fs"),ti=require("node:os"),de=require("node:path"),ri=require("node:stream"),ni=require("node:stream/promises");async function oi(e,t){let r=J(e,t);if(!r)throw ae(e,t),new Error(`Config not found: ${e}`);let n=await Se(e);if(!n)throw await Re(e),new Error(`Stack not found: ${e}`);let o=n.appBucket;if(!o)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 wp("@medplum/app",i)}si(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 Sp(s,o.PhysicalResourceId,t),n.appDistribution?.PhysicalResourceId&&!t.dryrun&&await At(n.appDistribution.PhysicalResourceId),console.log("Done")}async function yp(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await fetch(r)).json()}async function wp(e,t){let n=(await yp(e,t)).dist.tarball,o=(0,j.mkdtempSync)((0,de.join)((0,ti.tmpdir)(),"tarball-"));try{let s=await fetch(n);if(!s.body)throw new Error("Received empty response body");let i=Cn(o);return await(0,ni.pipeline)(ri.Readable.fromWeb(s.body),i),(0,de.join)(o,"package","dist")}catch(s){throw(0,j.rmSync)(o,{recursive:!0,force:!0}),s}}function si(e,t){for(let r of(0,j.readdirSync)(e,{withFileTypes:!0})){let n=(0,de.join)(e,r.name);r.isDirectory()?si(n,t):r.isFile()&&n.endsWith(".js")&&Ep(n,t)}}function Ep(e,t){let r=(0,j.readFileSync)(e,"utf-8");for(let[n,o]of Object.entries(t))r=r.replaceAll(`__${n}__`,o);(0,j.writeFileSync)(e,r)}async function Sp(e,t,r){let n=[["assets/**/*.css",G.ContentType.CSS,!0],["assets/**/*.css.map",G.ContentType.JSON,!0],["assets/**/*.js",G.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",G.ContentType.JSON,!0],["assets/**/*.txt",G.ContentType.TEXT,!0],["assets/**/*.ico",G.ContentType.FAVICON,!0],["img/**/*.png",G.ContentType.PNG,!0],["img/**/*.svg",G.ContentType.SVG,!0],["robots.txt",G.ContentType.TEXT,!0],["index.html",G.ContentType.HTML,!1]];for(let o of n)await Rp({rootDir:e,bucketName:t,fileNamePattern:o[0],contentType:o[1],cached:o[2],dryrun:r.dryrun})}async function Rp(e){let t=ei.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await bp((0,de.join)(e.rootDir,r),e)}async function bp(e,t){let r=(0,j.createReadStream)(e),n=e.substring(t.rootDir.length+1).split(de.sep).join("/"),o={Bucket:t.bucketName,Key:n,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${n} to ${t.bucketName}...`),t.dryrun||await Be.send(new Zs.PutObjectCommand(o))}var Tt=require("@aws-sdk/client-s3");async function ci(e,t){if(!J(e,t))throw ae(e,t),new Error(`Config not found: ${e}`);let n=await Se(e);if(!n)throw await Re(e),new Error(`Stack not found: ${e}`);try{await ii("App",n.appBucket,n.appDistribution,n.appOriginAccessIdentity,t)}catch(o){console.error(`Error updating App bucket policy: ${o.message}`)}try{await ii("Storage",n.storageBucket,n.storageDistribution,n.storageOriginAccessIdentity,t)}catch(o){console.error(`Error updating Storage bucket policy: ${o.message}`)}console.log("Done")}async function ii(e,t,r,n,o){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!n?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let s=t.PhysicalResourceId,i=n.PhysicalResourceId,a=await Ap(s);if(Pp(a,s,i))throw new Error(`${e} bucket already has policy statement`);Ip(a,s,i),e==="Storage"&&o.guarddutyMalwareProtection&&Cp(a,s,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),o.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await vp(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await At(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Ap(e){let t=await Be.send(new Tt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function vp(e,t){await Be.send(new Tt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Pp(e,t,r){return!!e?.Statement?.some(n=>n?.Effect==="Allow"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(n?.Action)&&n?.Action?.includes("s3:GetObject*")&&n?.Action?.includes("s3:GetBucket*")&&n?.Action?.includes("s3:List*")&&Array.isArray(n?.Resource)&&n?.Resource?.includes(`arn:aws:s3:::${t}`)&&n?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Ip(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}/*`]})}function Cp(e,t,r){e.Statement?.some(n=>n?.Effect==="Deny"&&n?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&ai(n,"s3:GetObject")&&ai(n,"s3:GetObjectVersion")&&n?.Condition?.StringNotEquals?.["s3:ExistingObjectTag/GuardDutyMalwareScanStatus"]==="NO_THREATS_FOUND")||e.Statement?.push({Sid:"GuardDutyMalwareProtectionReadGate",Effect:"Deny",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject","s3:GetObjectVersion"],Resource:`arn:aws:s3:::${t}/*`,Condition:{StringNotEquals:{"s3:ExistingObjectTag/GuardDutyMalwareScanStatus":"NO_THREATS_FOUND"}}})}function ai(e,t){return e.Action===t?!0:Array.isArray(e.Action)&&e.Action.includes(t)}async function li(e,t){try{gt();let r=J(e,t);if(!r)throw ae(e,t),new Error(`Config not found: ${e}`);let n=In(e)??{};if(!t.yes&&Object.keys(n).length===0){let o=B(e,{server:!0});if(console.log(ue.yellow(`Config file ${o} not found!`)),!await ie("Do you want to proceed?")){console.log(ue.red(`Run Aborted, please ensure ${o} is present and try again.`));return}}Tp(r,n),$p(r,n),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({...n,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(ue.yellow("Dry run - skipping updates!")):(t.yes||await ie("Do you want to store these values in AWS Parameter Store?"))&&await Pt(r.region,`/medplum/${r.name}/`,n)}finally{ht()}}function Tp(e,t){Ot(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Ot(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Ot(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Ot(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Ot(e,t,r){if(Op(e,t))throw new Error(r)}function Op(e,t){return e!==void 0&&t!==void 0&&e!==t}function $p(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 pi=require("node:child_process"),be=z(Ar(),1);async function di(e,t){let r=await R(t),n=J(e,t);if(!n)throw console.log(`Configuration file ${B(e)} not found`),ae(e,t),new Error(`Config not found: ${e}`);let o=n.serverImage.lastIndexOf(":"),s=n.serverImage.slice(0,o),i=await Np(r,n),a=await ui(i);for(;a;){if(t.toVersion&&be.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),n.serverImage=`${s}:${a}`,kp(e,n),await r.startAsyncRequest("/admin/super/migrate"),a=await ui(a)}}async function Np(e,t){let r=t.serverImage.lastIndexOf(":"),n=t.serverImage.slice(r+1);if(n==="latest"){n=(await e.get("/healthcheck")).version;let s=n.indexOf("-");s>-1&&(n=n.slice(0,s))}return n}async function ui(e,t){let r=await vt(e),n=r[0];return r.filter(o=>o===n||o===t||be.gte(o,be.inc(e,"minor"))).pop()}function kp(e,t){let r=B(e);I(r,t);let n=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+n);let o=(0,pi.spawnSync)(n,{stdio:"inherit"});if(o.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${o.status}): ${o.stderr}`);console.log(o.stdout)}function mi(){let e=new h("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Ys),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Qs),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Vs),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(rr(`Update the AWS Parameter Store config values.
|
|
8
8
|
|
|
9
9
|
Configuration values come from a file named **medplum.<tag>.config.server.json** where **<tag>** is the Medplum stack tag.
|
|
10
10
|
|
|
11
11
|
`+ue.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",rr("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(li),y(e,new h("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(di)),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(oi),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("--guardduty-malware-protection","Adds the GuardDuty Malware Protection for S3 read-gating deny to the storage bucket policy.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(ci),e}var fi=new h("save"),gi=new h("deploy"),hi=new h("create"),We=new h("bot");y(We,fi);y(We,gi);y(We,hi);var Ir=new h("save-bot"),Cr=new h("deploy-bot"),Tr=new h("create-bot");fi.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await $t(r,e)});gi.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await R(t);await $t(r,e,!0)});hi.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,n,o)=>{let s=await R(o);await Yt(s,e,t,r,n,o.runtimeVersion,!!o.writeConfig)});async function $t(e,t,r=!1){let n=Pn(t),o=[],s=[],i=0,a=0;for(let l of n)try{let u=await e.readResource("Bot",l.id);await Xt(e,l,u),i++,r&&(await zt(e,l,u),a++)}catch(u){o.push(u),s.push(`${l.name} [${l.id}]`)}if(console.log(`Number of bots saved: ${i}`),console.log(`Number of bots deployed: ${a}`),console.log(`Number of errors: ${o.length}`),o.length)throw new Error(`${o.length} bot(s) had failures. Bots with failures:
|
|
12
12
|
|
|
13
13
|
${s.join(`
|
|
14
|
-
`)}`,{cause:o})}Ir.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await $t(r,e)});Cr.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await R(t);await $t(r,e,!0)});Tr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,n,o)=>{let s=await R(o);await Yt(s,e,t,r,n)});var U=require("@medplum/core"),Nt=require("node:fs"),Or=require("node:path"),Ei=require("node:readline"),Si=require("node:stream"),Ri=require("node:stream/promises");var bi=new h("export"),Ai=new h("import"),kt=new h("bulk");y(kt,bi);y(kt,Ai);bi.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:n,targetDirectory:o}=e,s=await R(e),i=await s.bulkExport(t,r,n,{pollStatusOnAccepted:!0});for(let{type:a,url:l}of i.output??U.EMPTY){let u=new URL(l),p=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",d=(0,Or.resolve)(o??"",p),E=await s.downloadResponse(l);if(!E.ok)throw new Error(`Download failed: ${E.status} ${E.statusText}`);if(!E.body)throw new Error("Download response missing body");let g=Si.Readable.fromWeb(E.body);await(0,Ri.pipeline)(g,(0,Nt.createWriteStream)(d)),console.log(`${d} 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:n,targetDirectory:o}=t,s=(0,Or.resolve)(o??process.cwd(),e),i=await R(t);await xp(s,Number.parseInt(r,10),i,n)});async function xp(e,t,r,n){let o=[],s=(0,Nt.createReadStream)(e),i=(0,Ei.createInterface)({input:s});for await(let a of i){let l=Dp(a,n);o.push({resource:l,request:{method:"POST",url:l.resourceType}}),o.length%t===0&&(await yi(o,r),o=[])}o.length>0&&await yi(o,r)}async function yi(e,t){let r=e;for(;r.length>0;){let n;try{n=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:r},{maxRetries:0})}catch(s){if(!(s instanceof U.OperationOutcomeError)||(0,U.getStatus)(s.outcome)!==429)throw s;await(0,U.sleep)(wi(s.outcome,t));continue}let o=[];for(let s=0;s<r.length;s++){let i=n.entry?.[s];i?.response?.outcome&&(0,U.getStatus)(i.response.outcome)===429?o.push(r[s]):ee(i?.response)}if(o.length>0){let s=n.entry?.find(i=>i.response?.outcome&&(0,U.getStatus)(i.response.outcome)===429)?.response?.outcome;await(0,U.sleep)(wi(s,t))}r=o}}function wi(e,t){let r=e&&(0,U.getRateLimitReset)(e);return r!==void 0?r:Math.max(500,...t.rateLimitStatus().filter(n=>n.remainingUnits===0).map(n=>n.secondsUntilReset*1e3))}function Dp(e,t){let r=JSON.parse(e);return t?Mp(r):r}function Mp(e){return e.resourceType==="ExplanationOfBenefit"?Lp(e):e}function Lp(e){return e.provider||(e.provider=Qt()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Qt())}),e}var xt=
|
|
14
|
+
`)}`,{cause:o})}Ir.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await R(t);await $t(r,e)});Cr.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await R(t);await $t(r,e,!0)});Tr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,n,o)=>{let s=await R(o);await Yt(s,e,t,r,n)});var U=require("@medplum/core"),Nt=require("node:fs"),Or=require("node:path"),Ei=require("node:readline"),Si=require("node:stream"),Ri=require("node:stream/promises");var bi=new h("export"),Ai=new h("import"),kt=new h("bulk");y(kt,bi);y(kt,Ai);bi.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:n,targetDirectory:o}=e,s=await R(e),i=await s.bulkExport(t,r,n,{pollStatusOnAccepted:!0});for(let{type:a,url:l}of i.output??U.EMPTY){let u=new URL(l),p=`${a}_${u.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",d=(0,Or.resolve)(o??"",p),E=await s.downloadResponse(l);if(!E.ok)throw new Error(`Download failed: ${E.status} ${E.statusText}`);if(!E.body)throw new Error("Download response missing body");let g=Si.Readable.fromWeb(E.body);await(0,Ri.pipeline)(g,(0,Nt.createWriteStream)(d)),console.log(`${d} 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:n,targetDirectory:o}=t,s=(0,Or.resolve)(o??process.cwd(),e),i=await R(t);await xp(s,Number.parseInt(r,10),i,n)});async function xp(e,t,r,n){let o=[],s=(0,Nt.createReadStream)(e),i=(0,Ei.createInterface)({input:s});for await(let a of i){let l=Dp(a,n);o.push({resource:l,request:{method:"POST",url:l.resourceType}}),o.length%t===0&&(await yi(o,r),o=[])}o.length>0&&await yi(o,r)}async function yi(e,t){let r=e;for(;r.length>0;){let n;try{n=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:r},{maxRetries:0})}catch(s){if(!(s instanceof U.OperationOutcomeError)||(0,U.getStatus)(s.outcome)!==429)throw s;await(0,U.sleep)(wi(s.outcome,t));continue}let o=[];for(let s=0;s<r.length;s++){let i=n.entry?.[s];i?.response?.outcome&&(0,U.getStatus)(i.response.outcome)===429?o.push(r[s]):ee(i?.response)}if(o.length>0){let s=n.entry?.find(i=>i.response?.outcome&&(0,U.getStatus)(i.response.outcome)===429)?.response?.outcome;await(0,U.sleep)(wi(s,t))}r=o}}function wi(e,t){let r=e&&(0,U.getRateLimitReset)(e);return r!==void 0?r:Math.max(500,...t.rateLimitStatus().filter(n=>n.remainingUnits===0).map(n=>n.secondsUntilReset*1e3))}function Dp(e,t){let r=JSON.parse(e);return t?Mp(r):r}function Mp(e){return e.resourceType==="ExplanationOfBenefit"?Lp(e):e}function Lp(e){return e.provider||(e.provider=Qt()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Qt())}),e}var xt=z(require("fast-glob"),1),$r=require("node:events"),vi=require("node:fs"),Dt=require("node:fs/promises"),Ae=require("node:path"),Pi=require("node:stream");var Up=25,_p=new Set([".dcm",".dicom",".ima"]),Ii=Buffer.from("DICM"),Ci=128,Fp=Ci+Ii.length,jp=2;async function Bp(e){if((0,Ae.basename)(e).toUpperCase()==="DICOMDIR")return!1;let t=await(0,Dt.open)(e,"r");try{let r=Buffer.alloc(Fp),{bytesRead:n}=await t.read(r,0,r.length,0);if(n===r.length&&r.subarray(Ci).equals(Ii)||n>=2&&r.readUInt16LE(0)===jp)return!0}finally{await t.close()}return _p.has((0,Ae.extname)(e).toLowerCase())}async function qp(e){let t=new Set;for(let r of e){let n=await(0,Dt.stat)(r).catch(()=>{});if(n?.isFile()){t.add((0,Ae.resolve)(r));continue}let o;if(n?.isDirectory())o=await(0,xt.default)("**/*",{cwd:r,onlyFiles:!0,absolute:!0});else if(xt.default.isDynamicPattern(r))o=await(0,xt.default)(r,{onlyFiles:!0,absolute:!0,caseSensitiveMatch:!1});else throw new Error(`File not found: ${r}`);let s=0;for(let i of o)await Bp(i)?t.add(i):s++;s>0&&console.log(`Skipped ${s} non-DICOM file(s) in "${r}"`)}return Array.from(t).sort((r,n)=>r.localeCompare(n))}async function Ge(e,t){e.write(t)||await(0,$r.once)(e,"drain")}async function Wp(e,t){let r=(0,vi.createReadStream)(e);try{for await(let n of r)t.write(n)||await(0,$r.once)(t,"drain")}finally{r.destroy()}}async function Gp(e,t,r){try{for(let n of t)await Ge(e,Buffer.from(`--${r}\r
|
|
15
15
|
`)),await Ge(e,Buffer.from(`Content-Type: application/dicom\r
|
|
16
16
|
`)),await Ge(e,Buffer.from(`\r
|
|
17
17
|
`)),await Wp(n,e),await Ge(e,Buffer.from(`\r
|
|
18
18
|
`));await Ge(e,Buffer.from(`--${r}--\r
|
|
19
|
-
`)),e.end()}catch(n){throw e.destroy(n),n}}var Kp=new h("stow").description("Send DICOM instances via DICOMweb STOW-RS").argument("<files...>","DICOM files, directories, or quoted glob patterns to send").option("--batch-size <count>","Maximum number of instances per STOW-RS request",String(Up)).action(async(e,t)=>{let r=Number.parseInt(t.batchSize,10);if(!Number.isInteger(r)||r<1)throw new Error(`Invalid batch size: ${t.batchSize}`);let n=await qp(e);if(n.length===0)throw new Error("No DICOM files found");console.log(`Sending ${n.length} DICOM file(s)`);let o=await R(t);for(let s=0;s<n.length;s+=r){let i=n.slice(s,s+r),a=`medplum-${Date.now()}`,l=`multipart/related; type=application/dicom; boundary=${a}`,u=new Pi.PassThrough,p=Gp(u,i,a),d=o.post("/dicomweb/studies",u,l);await p;let E=await d;console.log("STOW-RS response received",E)}}),Nr=new h("dicomweb");y(Nr,Kp);var Mt=require("@medplum/core");var Ke=H(require("node:assert"),1),$i=H(require("node:net"),1),$=require("@medplum/core"),kr=H(require("iconv-lite"),1),zp=require("@medplum/core");var xi=require("@medplum/core"),Di=H(require("node:net"),1),Vp=Object.defineProperty,Hp=(e,t,r)=>t in e?Vp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,b=(e,t,r)=>Hp(e,typeof t!="symbol"?t+"":t,r),Oi=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var Jp=class extends Event{constructor(e,t){super("message"),b(this,"connection"),b(this,"message"),this.connection=e,this.message=t}},Xp=class extends Event{constructor(e,t){super("enhancedAckSent"),b(this,"connection"),b(this,"message"),this.connection=e,this.message=t}},Ve=class extends Event{constructor(e){super("error"),b(this,"error"),this.error=e}},xr=class extends Event{constructor(e){super("warning"),b(this,"error"),this.error=e}},Dr=class extends Event{constructor(){super("close")}},Ti="utf-8",Yp=5e3,Qp=60*1e3,Ni=class extends Oi{constructor(e,t=Ti,r,n={}){super(),b(this,"socket"),b(this,"encoding"),b(this,"enhancedMode"),b(this,"messagesPerMin"),b(this,"gracefulCloseTimeoutMs"),b(this,"chunks",[]),b(this,"pendingMessages",new Map),b(this,"responseQueue",[]),b(this,"lastMessageDispatchedTime",0),b(this,"responseQueueProcessing",!1),b(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=n.messagesPerMin,this.gracefulCloseTimeoutMs=n.gracefulCloseTimeoutMs??Yp,e.on("data",o=>{if(this.closing){this.dispatchEvent(new xr(new $.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(o);let s=this.parseMessages();for(let i of s)this.responseQueue.push(new Jp(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new Ve(i))})}catch(s){this.dispatchEvent(new Ve(s))}}),e.on("error",o=>{this.resetBuffer(),this.dispatchEvent(new Ve(o))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new Dr)}),this.addEventListener("message",o=>{let s;this.enhancedMode==="standard"?s=o.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(s=o.message.buildAck({ackCode:"AA"})),s&&(this.send(s),this.dispatchEvent(new Xp(this,s)));let i=o.message.getSegment("MSA")?.getField(2)?.toString();if(!i)return;let a=this.getPendingMessage(i);if(!a){this.dispatchEvent(new xr(new $.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=o.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();l&&(a.returnAck===$.ReturnAckCategory.APPLICATION&&l==="CA"||(a.timer&&clearTimeout(a.timer),a.resolve(o.message),this.deletePendingMessage(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=kr.default.encode(t,this.encoding),n=Buffer.alloc(r.length+3);n.writeInt8(11,0),r.copy(n,1),n.writeInt8(28,r.length+1),n.writeInt8(13,r.length+2),this.socket.write(n)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=Qp/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await(0,$.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 n=-1;for(let a=r+1;a<t.length-1;a++)if(t[a]===28&&t[a+1]===13){n=a+1;break}if(n===-1)break;let o=t.subarray(r,n+1).subarray(1,-2),s=kr.default.decode(o,this.encoding),i=$.Hl7Message.parse(s);e.push(i),r=n+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,n)=>{let o=e.getSegment("MSH")?.getField(10)?.toString();if(!o){n(new $.OperationOutcomeError((0,$.validationError)("Required field missing: MSH.10")));return}let s;t?.timeoutMs&&(s=setTimeout(()=>{this.deletePendingMessage(o),n(new $.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.setPendingMessage(o,{message:e,resolve:r,reject:n,returnAck:t?.returnAck??$.ReturnAckCategory.APPLICATION,timer:s}),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 $.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Ve(new $.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??Ti}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}getPendingMessage(e){return this.pendingMessages.get(e)}setPendingMessage(e,t){this.pendingMessages.set(e,t)}deletePendingMessage(e){this.pendingMessages.delete(e)}},ki=class extends Oi{constructor(e){super(),b(this,"options"),b(this,"host"),b(this,"port"),b(this,"encoding"),b(this,"connection"),b(this,"keepAlive"),b(this,"socket"),b(this,"connectTimeout"),b(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=$i.default.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,Ke.default)(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let n=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,n)};t.on("timeout",r)}registerSocketConnectListener(e){(0,Ke.default)(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let n;this.connection=n=this.createConnection(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(n),e.resolve(n)};t.on("connect",r)}registerSocketErrorListener(e){(0,Ke.default)(this.socket);let t=this.socket,r=n=>{this.cleanupSocket(t),n.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,n.errors[0]):this.rejectDeferredPromise(e,n)};t.on("error",r)}registerSocketCloseListener(e){(0,Ke.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 Dr)}),e.addEventListener("error",t=>{this.dispatchEvent(new Ve(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new xr(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),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)}createConnection(e,t,r,n){return new Ni(e,t,r,n)}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 Dr);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}};var Zp=1e4,Mi=class{constructor(e){b(this,"handler"),b(this,"server"),b(this,"encoding"),b(this,"enhancedMode"),b(this,"messagesPerMin"),b(this,"connections",new Set),this.handler=e}async start(e,t,r,n){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),n?.messagesPerMin!==void 0&&this.setMessagesPerMin(n.messagesPerMin);let o=Di.default.createServer(s=>{let i=new Ni(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=>{o.listen(u,()=>{let p=o.address().port;s(p)})},l=u=>{u?.code==="EADDRINUSE"?o.close(()=>(0,xi.sleep)(50).then(()=>a(e))):i(u)};o.on("error",l),o.once("listening",()=>{o.off("error",l)}),a(e),this.server=o})}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 n;e?.forceDrainTimeoutMs!==-1&&(n=setTimeout(()=>{for(let o of this.connections)o.close().catch(console.error)},e?.forceDrainTimeoutMs??Zp)),this.server.close(o=>{if(o){r(o);return}n&&clearTimeout(n),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 Li=require("node:fs");var ed=new h("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,n)=>{if(n.generateExample?r=rd():n.file&&(r=(0,Li.readFileSync)(n.file,"utf8")),!r)throw new Error("Missing HL7 message body");let o=new ki({host:e,port:Number.parseInt(t,10),encoding:n.encoding});try{let s=await o.sendAndWait(Mt.Hl7Message.parse(r));console.log(s.toString().replaceAll("\r",`
|
|
19
|
+
`)),e.end()}catch(n){throw e.destroy(n),n}}var Kp=new h("stow").description("Send DICOM instances via DICOMweb STOW-RS").argument("<files...>","DICOM files, directories, or quoted glob patterns to send").option("--batch-size <count>","Maximum number of instances per STOW-RS request",String(Up)).action(async(e,t)=>{let r=Number.parseInt(t.batchSize,10);if(!Number.isInteger(r)||r<1)throw new Error(`Invalid batch size: ${t.batchSize}`);let n=await qp(e);if(n.length===0)throw new Error("No DICOM files found");console.log(`Sending ${n.length} DICOM file(s)`);let o=await R(t);for(let s=0;s<n.length;s+=r){let i=n.slice(s,s+r),a=`medplum-${Date.now()}`,l=`multipart/related; type=application/dicom; boundary=${a}`,u=new Pi.PassThrough,p=Gp(u,i,a),d=o.post("/dicomweb/studies",u,l);await p;let E=await d;console.log("STOW-RS response received",E)}}),Nr=new h("dicomweb");y(Nr,Kp);var Mt=require("@medplum/core");var Ke=z(require("node:assert"),1),$i=z(require("node:net"),1),$=require("@medplum/core"),kr=z(require("iconv-lite"),1),zp=require("@medplum/core");var xi=require("@medplum/core"),Di=z(require("node:net"),1),Vp=Object.defineProperty,Hp=(e,t,r)=>t in e?Vp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,b=(e,t,r)=>Hp(e,typeof t!="symbol"?t+"":t,r),Oi=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}};var Jp=class extends Event{constructor(e,t){super("message"),b(this,"connection"),b(this,"message"),this.connection=e,this.message=t}},Xp=class extends Event{constructor(e,t){super("enhancedAckSent"),b(this,"connection"),b(this,"message"),this.connection=e,this.message=t}},Ve=class extends Event{constructor(e){super("error"),b(this,"error"),this.error=e}},xr=class extends Event{constructor(e){super("warning"),b(this,"error"),this.error=e}},Dr=class extends Event{constructor(){super("close")}},Ti="utf-8",Yp=5e3,Qp=60*1e3,Ni=class extends Oi{constructor(e,t=Ti,r,n={}){super(),b(this,"socket"),b(this,"encoding"),b(this,"enhancedMode"),b(this,"messagesPerMin"),b(this,"gracefulCloseTimeoutMs"),b(this,"chunks",[]),b(this,"pendingMessages",new Map),b(this,"responseQueue",[]),b(this,"lastMessageDispatchedTime",0),b(this,"responseQueueProcessing",!1),b(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=n.messagesPerMin,this.gracefulCloseTimeoutMs=n.gracefulCloseTimeoutMs??Yp,e.on("data",o=>{if(this.closing){this.dispatchEvent(new xr(new $.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(o);let s=this.parseMessages();for(let i of s)this.responseQueue.push(new Jp(this,i));this.processResponseQueue().catch(i=>{this.dispatchEvent(new Ve(i))})}catch(s){this.dispatchEvent(new Ve(s))}}),e.on("error",o=>{this.resetBuffer(),this.dispatchEvent(new Ve(o))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new Dr)}),this.addEventListener("message",o=>{let s;this.enhancedMode==="standard"?s=o.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(s=o.message.buildAck({ackCode:"AA"})),s&&(this.send(s),this.dispatchEvent(new Xp(this,s)));let i=o.message.getSegment("MSA")?.getField(2)?.toString();if(!i)return;let a=this.getPendingMessage(i);if(!a){this.dispatchEvent(new xr(new $.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=o.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();l&&(a.returnAck===$.ReturnAckCategory.APPLICATION&&l==="CA"||(a.timer&&clearTimeout(a.timer),a.resolve(o.message),this.deletePendingMessage(i)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=kr.default.encode(t,this.encoding),n=Buffer.alloc(r.length+3);n.writeInt8(11,0),r.copy(n,1),n.writeInt8(28,r.length+1),n.writeInt8(13,r.length+2),this.socket.write(n)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=Qp/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await(0,$.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 n=-1;for(let a=r+1;a<t.length-1;a++)if(t[a]===28&&t[a+1]===13){n=a+1;break}if(n===-1)break;let o=t.subarray(r,n+1).subarray(1,-2),s=kr.default.decode(o,this.encoding),i=$.Hl7Message.parse(s);e.push(i),r=n+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,n)=>{let o=e.getSegment("MSH")?.getField(10)?.toString();if(!o){n(new $.OperationOutcomeError((0,$.validationError)("Required field missing: MSH.10")));return}let s;t?.timeoutMs&&(s=setTimeout(()=>{this.deletePendingMessage(o),n(new $.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.setPendingMessage(o,{message:e,resolve:r,reject:n,returnAck:t?.returnAck??$.ReturnAckCategory.APPLICATION,timer:s}),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 $.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Ve(new $.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??Ti}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}getPendingMessage(e){return this.pendingMessages.get(e)}setPendingMessage(e,t){this.pendingMessages.set(e,t)}deletePendingMessage(e){this.pendingMessages.delete(e)}},ki=class extends Oi{constructor(e){super(),b(this,"options"),b(this,"host"),b(this,"port"),b(this,"encoding"),b(this,"connection"),b(this,"keepAlive"),b(this,"socket"),b(this,"connectTimeout"),b(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=$i.default.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,Ke.default)(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let n=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,n)};t.on("timeout",r)}registerSocketConnectListener(e){(0,Ke.default)(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let n;this.connection=n=this.createConnection(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(n),e.resolve(n)};t.on("connect",r)}registerSocketErrorListener(e){(0,Ke.default)(this.socket);let t=this.socket,r=n=>{this.cleanupSocket(t),n.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,n.errors[0]):this.rejectDeferredPromise(e,n)};t.on("error",r)}registerSocketCloseListener(e){(0,Ke.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 Dr)}),e.addEventListener("error",t=>{this.dispatchEvent(new Ve(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new xr(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),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)}createConnection(e,t,r,n){return new Ni(e,t,r,n)}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 Dr);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}};var Zp=1e4,Mi=class{constructor(e){b(this,"handler"),b(this,"server"),b(this,"encoding"),b(this,"enhancedMode"),b(this,"messagesPerMin"),b(this,"connections",new Set),this.handler=e}async start(e,t,r,n){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),n?.messagesPerMin!==void 0&&this.setMessagesPerMin(n.messagesPerMin);let o=Di.default.createServer(s=>{let i=new Ni(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=>{o.listen(u,()=>{let p=o.address().port;s(p)})},l=u=>{u?.code==="EADDRINUSE"?o.close(()=>(0,xi.sleep)(50).then(()=>a(e))):i(u)};o.on("error",l),o.once("listening",()=>{o.off("error",l)}),a(e),this.server=o})}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 n;e?.forceDrainTimeoutMs!==-1&&(n=setTimeout(()=>{for(let o of this.connections)o.close().catch(console.error)},e?.forceDrainTimeoutMs??Zp)),this.server.close(o=>{if(o){r(o);return}n&&clearTimeout(n),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 Li=require("node:fs");var ed=new h("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,n)=>{if(n.generateExample?r=rd():n.file&&(r=(0,Li.readFileSync)(n.file,"utf8")),!r)throw new Error("Missing HL7 message body");let o=new ki({host:e,port:Number.parseInt(t,10),encoding:n.encoding});try{let s=await o.sendAndWait(Mt.Hl7Message.parse(r));console.log(s.toString().replaceAll("\r",`
|
|
20
20
|
`))}finally{await o.close()}}),td=new h("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{await new Mi(n=>{n.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
|
|
21
21
|
`)),n.send(o.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),Lt=new h("hl7");y(Lt,ed);y(Lt,td);function rd(){let e=(0,Mt.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
|
|
22
22
|
EVN|A01|${e}||
|
|
23
23
|
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|
|
|
24
|
-
PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var Ui=require("node:fs"),_i=require("node:os"),Fi=require("node:path");var ji=new h("set"),Bi=new h("remove"),qi=new h("list"),Wi=new h("describe"),ve=new h("profile");y(ve,ji);y(ve,Bi);y(ve,qi);y(ve,Wi);ji.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{et(e,t)});Bi.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new
|
|
24
|
+
PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var Ui=require("node:fs"),_i=require("node:os"),Fi=require("node:path");var ji=new h("set"),Bi=new h("remove"),qi=new h("list"),Wi=new h("describe"),ve=new h("profile");y(ve,ji);y(ve,Bi);y(ve,qi);y(ve,Wi);ji.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{et(e,t)});Bi.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new H(e).setObject("options",void 0),console.log(`${e} profile removed`)});qi.description("List all profiles saved").action(async()=>{let e=(0,Fi.resolve)((0,_i.homedir)(),".medplum"),t=(0,Ui.readdirSync)(e),r=[];t.forEach(n=>{let o=n.split(".")[0],i=new H(o).getObject("options");i&&r.push({profileName:o,profile:i})}),console.log(r)});Wi.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=Tn(e);console.log(t)});var Gi=require("commander");var Ki=new h("list"),Vi=new h("current"),Hi=new h("switch"),Ji=new h("invite"),Pe=new h("project");y(Pe,Ki);y(Pe,Vi);y(Pe,Hi);y(Pe,Ji);Ki.description("List of current projects").action(async e=>{let t=await R(e);nd(t)});function nd(e){let r=e.getLogins().map(n=>`${n.project.display} (${n.project.reference})`).join(`
|
|
25
25
|
|
|
26
26
|
`);console.log(r)}Vi.description("Project you are currently on").action(async e=>{let r=(await R(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});Hi.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await R(t);await od(r,e)});Ji.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 Gi.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,n)=>{let o=await R(n),s=o.getActiveLogin();if(!s)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!s?.project?.reference)throw new Error("No current project to invite user to");let i=s.project.reference.split("/")[1],a={resourceType:n.role,firstName:e,lastName:t,email:r,sendEmail:!!n.sendEmail,admin:!!n.admin};await sd(i,a,o)});async function od(e,t){let n=e.getLogins().find(o=>o.project.reference?.includes(t));if(!n)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(n),console.log(`Switched to project ${t}
|
|
27
27
|
`)}async function sd(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 Xi=require("@medplum/core");var Mr=new h("delete"),Lr=new h("get"),Ur=new h("patch"),_r=new h("post"),Fr=new h("put");Mr.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await R(t);ee(await r.delete(He(r,e)))});Lr.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await R(t),n=await r.get(He(r,e));t.asTransaction?ee((0,Xi.convertToTransactionBundle)(n)):ee(n)});Ur.arguments("<url> <body>").action(async(e,t,r)=>{let n=await R(r);ee(await n.patch(He(n,e),jr(t)))});_r.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let n=await R(r),o=r.preferAsync?{Prefer:"respond-async"}:void 0;ee(await n.post(He(n,e),jr(t),void 0,{headers:o}))});Fr.arguments("<url> <body>").action(async(e,t,r)=>{let n=await R(r);ee(await n.put(He(n,e),jr(t)))});function jr(e){if(e)try{return JSON.parse(e)}catch{return e}}function He(e,t){return["admin/","auth/","fhir/R4"].some(n=>t.startsWith(n))?t:e.fhirUrl(t).toString()}async function Yi(e){let t=new h("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>",'OAuth scope (e.g., "openid offline_access")').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 Je.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,Zt),y(t,er),y(t,tr),y(t,Lr),y(t,_r),y(t,Ur),y(t,Fr),y(t,Mr),y(t,Pe),y(t,kt),y(t,We),y(t,oe),y(t,Ir),y(t,Cr),y(t,Tr),y(t,ve),y(t,mi()),y(t,Lt),y(t,Nr);try{await t.parseAsync(e)}catch(r){Qi(r)}}function Qi(e){let t=1,r=!0;if(e instanceof Je.CommanderError&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){Br(e,!!process.env.VERBOSE);let n=e.cause;if(process.env.VERBOSE)if(Array.isArray(n))for(let o of n)Br(o,!0);else n instanceof Error&&Br(n,!0)}process.exit(t)}function Br(e,t=!1){if(t){console.error(e);return}e instanceof Je.CommanderError?process.stderr.write(`${(0,Ie.normalizeErrorString)(e)}
|
|
28
28
|
`):process.stderr.write(`Error: ${(0,Ie.normalizeErrorString)(e)}
|
|
29
|
-
`)}async function Zi(){zi.
|
|
29
|
+
`)}async function Zi(){(0,zi.existsSync)(".env")&&process.loadEnvFile(),await Yi(process.argv)}Zi().catch(e=>{console.error("Unhandled error:",(0,Ie.normalizeErrorString)(e)),process.exit(1)});0&&(module.exports={handleError,main,run});
|
|
30
30
|
//# sourceMappingURL=index.cjs.map
|