medplum 5.1.4 → 5.1.5

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