medplum 5.1.7 → 5.1.9

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 io=Object.create;var Qt=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&&Qt(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?Qt(r,"default",{value:e,enumerable:!0}):r,e));var Ee=require("@medplum/core"),We=require("commander"),wr=z(require("dotenv"),1),ae=require("@medplum/core"),rt=require("commander"),yr=require("@medplum/core"),Er=require("@medplum/core"),ie=require("node:fs"),vr=require("node:os"),Rt=require("node:path"),se=require("@medplum/core"),Sr=require("commander"),br=require("node:buffer"),Ar=z(require("node:util"),1),Rr=z(require("node:crypto"),1),Tr=z(require("node:util"),1),Lr=require("node:crypto"),kr=require("node:crypto"),xe=require("node:crypto"),st=z(require("node:crypto"),1),Dr=require("node:util"),Se=require("node:crypto"),$e=require("node:crypto"),le=require("node:fs"),ne=require("node:path"),Ur=require("node:util/types"),_r=require("tar"),Q=require("@medplum/core"),zr=require("node:child_process"),qr=require("node:http"),Yr=require("node:os"),ce=require("@aws-sdk/client-cloudformation"),it=require("@aws-sdk/client-cloudfront"),ss=require("@aws-sdk/client-ecs"),os=require("@aws-sdk/client-s3"),Pe=require("@aws-sdk/client-ssm"),at=require("@aws-sdk/client-sts"),nt=require("@medplum/core"),is=z(require("node-fetch"),1),as=require("node:fs"),ns=z(require("node:readline"),1),fe=require("@aws-sdk/client-acm"),ut=require("@aws-sdk/client-cloudfront"),pt=require("@aws-sdk/client-sts"),gs=require("@medplum/core"),je=require("node:crypto"),ws=require("node:fs"),Es=require("@aws-sdk/client-s3"),Y=require("@medplum/core"),vs=z(require("fast-glob"),1),Vt=z(require("node-fetch"),1),q=require("node:fs"),Ss=require("node:os"),he=require("node:path"),bs=require("node:stream/promises"),dt=require("@aws-sdk/client-s3"),As=require("node:child_process"),Cs=require("@medplum/core"),ft=require("node:fs"),Xt=require("node:path"),Ls=require("node:readline"),gt=require("@medplum/core"),De=z(require("node:assert"),1),Ds=require("node:net"),G=require("@medplum/core"),Ct=z(require("iconv-lite"),1),an=require("@medplum/core"),Us=require("@medplum/core"),_s=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,Mt=Object.defineProperty,ho=Object.getOwnPropertyDescriptor,mo=Object.getOwnPropertyNames,fo=Object.getPrototypeOf,go=Object.prototype.hasOwnProperty,wo=(e,t,r)=>t in e?Mt(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&&Mt(e,o,{get:()=>t[o],enumerable:!(s=ho(t,o))||s.enumerable});return e},pr=(e,t,r)=>(r=e!=null?po(fo(e)):{},yo(t||!e||!e.__esModule?Mt(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*$")}),Dt=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}),dr=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=Dt(),{compareIdentifiers:n}=dr(),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}),Ut=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=Ut(),s=(o,i)=>o.sort((a,c)=>r(a,c,i));t.exports=s}),Oo=A((e,t)=>{"use strict";var r=Ut(),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}),_t=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}),mr=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}),jt=A((e,t)=>{"use strict";var r=Z(),s=(o,i,a)=>r(o,i,a)<=0;t.exports=s}),fr=A((e,t)=>{"use strict";var r=hr(),s=mr(),o=Ze(),i=xt(),a=_t(),c=jt(),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}),Co=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}),Lo=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 k=new Map,C=I.map(D=>new c(D,this.options));for(let D of C){if(T(D))return[D];k.set(D.value,D)}k.size>1&&k.has("")&&k.delete("");let M=[...k.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=Lo(),i=new o,a=Dt(),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,k)=>{n("tilde",y,E,b,v,I,k);let C;return U(b)?C="":U(v)?C=`>=${b}.0.0 <${+b+1}.0.0-0`:U(I)?C=`>=${b}.${v}.0 <${b}.${+v+1}.0-0`:k?(n("replaceTilde pr",k),C=`>=${b}.${v}.${I}-${k} <${b}.${+v+1}.0-0`):C=`>=${b}.${v}.${I} <${b}.${+v+1}.0-0`,n("tilde return",C),C})},_=(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,k,C)=>{n("caret",y,b,v,I,k,C);let M;return U(v)?M="":U(I)?M=`>=${v}.0.0${E} <${+v+1}.0.0-0`:U(k)?v==="0"?M=`>=${v}.${I}.0${E} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.0${E} <${+v+1}.0.0-0`:C?(n("replaceCaret pr",C),v==="0"?I==="0"?M=`>=${v}.${I}.${k}-${C} <${v}.${I}.${+k+1}-0`:M=`>=${v}.${I}.${k}-${C} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.${k}-${C} <${+v+1}.0.0-0`):(n("no pr"),v==="0"?I==="0"?M=`>=${v}.${I}.${k}${E} <${v}.${I}.${+k+1}-0`:M=`>=${v}.${I}.${k}${E} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.${k} <${+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,k,C)=>{n("xRange",y,E,b,v,I,k,C);let M=U(v),D=M||U(I),ge=D||U(k),Oe=ge;return b==="="&&Oe&&(b=""),C=w.includePrerelease?"-0":"",M?b===">"||b==="<"?E="<0.0.0-0":E="*":b&&Oe?(D&&(I=0),k=0,b===">"?(b=">=",D?(v=+v+1,I=0,k=0):(I=+I+1,k=0)):b==="<="&&(b="<",D?v=+v+1:I=+I+1),b==="<"&&(C="-0"),E=`${b+v}.${I}.${k}${C}`):D?E=`>=${v}.0.0${C} <${+v+1}.0.0-0`:ge&&(E=`>=${v}.${I}.0${C} <${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,k,C,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)?C="":U(D)?C=`<${+M+1}.0.0-0`:U(ge)?C=`<${M}.${+D+1}.0-0`:Oe?C=`<=${M}.${D}.${ge}-${Oe}`:y?C=`<${M}.${D}.${+ge+1}-0`:C=`<=${C}`,`${S} ${C}`.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=Dt(),{safeRe:i,t:a}=Fe(),c=fr(),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}),Ft=A((e,t)=>{"use strict";var r=J(),s=et(),{ANY:o}=s,i=ee(),a=tt(),c=Ze(),n=_t(),f=jt(),l=xt(),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=Ft(),s=(o,i,a)=>r(o,i,">",a);t.exports=s}),jo=A((e,t)=>{"use strict";var r=Ft(),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}),gr=A((e,t)=>{"use strict";var r=Fe(),s=Ye(),o=J(),i=dr(),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=Ut(),j=No(),W=Oo(),U=Ze(),oe=_t(),V=hr(),_=mr(),H=xt(),$=jt(),Ne=fr(),wt=Co(),yt=et(),Et=ee(),vt=tt(),y=ko(),w=Mo(),S=Do(),E=Uo(),b=_o(),v=Ft(),I=xo(),k=jo(),C=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:k,intersects:C,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 Er.ClientStorage{constructor(e){super(),B(this,"dirName"),B(this,"fileName"),this.dirName=(0,Rt.resolve)((0,vr.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 yr.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,Zt=new TextDecoder,rn=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=>br.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 Ir=class extends Be{constructor(){super(...arguments),B(this,"code","ERR_JWT_INVALID")}};B(Ir,"code","ERR_JWT_INVALID");var er,tr,Vo=class extends(tr=Be,er=Symbol.asyncIterator,tr){constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),B(this,er),B(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};B(Vo,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var $r=e=>Ar.types.isKeyObject(e),Xo=Rr.webcrypto,zo=Xo,Wt=e=>Tr.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 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(!Ce(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(!Ce(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(!Ce(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(!Ce(e.algorithm,"Ed25519"))throw te("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Ce(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 Pr(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)=>Pr("Key must be ",e,...t);function Nr(e,t,...r){return Pr(`Key for the ${e} algorithm must be `,t,...r)}var Or=e=>$r(e)||Wt(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 Cr(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 Cr(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(Wt(e))r=Lr.KeyObject.from(e);else if($r(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,rr=(e,t)=>{let r;try{e instanceof kr.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(!Or(t))throw new TypeError(Nr(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(!Or(t))throw new TypeError(Nr(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 Mr(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 sn=Mr.bind(void 0,!1),ui=Mr.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");rr(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");rr(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(Wt(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,Dr.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=Zt.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=Zt.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"),!Cr(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 Ir("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}};function de(e){console.log(JSON.stringify(e,null,2))}async function xr(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:Ci(s)});console.log("Updating bot...");let a=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+a.meta?.versionId)}async function jr(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 Fr(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 xr(e,l,f),await jr(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,_r.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 sr(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function Ci(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 Wr(e,t){let r=new He(e),s={name:e,...t};return r.setObject("options",s),s}function Li(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 Sr.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,Ur.isPromise)(i)&&await i}finally{e.resetOptionDefaults()}}}var Hr=new R("status").aliases(["info","list","ls"]),Br=new R("ping"),Kr=new R("push"),Gr=new R("reload-config"),Jr=new R("upgrade"),Te=new R("agent");P(Te,Hr);P(Te,Br);P(Te,Kr);P(Te,Gr);P(Te,Jr);Hr.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 Ht({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"}}})});Br.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 Vr(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})}});Kr.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 Vr(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)});Gr.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 Ht({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Jr.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 Ht({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:s=>({id:s.agent.id,name:s.agent.name,version:t.agentVersion??"latest"})})});async function Ht({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(`
2
+ "use strict";var no=Object.create;var Zt=Object.defineProperty;var co=Object.getOwnPropertyDescriptor;var lo=Object.getOwnPropertyNames;var uo=Object.getPrototypeOf,po=Object.prototype.hasOwnProperty;var ho=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of lo(t))!po.call(e,o)&&o!==r&&Zt(e,o,{get:()=>t[o],enumerable:!(s=co(t,o))||s.enumerable});return e};var z=(e,t,r)=>(r=e!=null?no(uo(e)):{},ho(t||!e||!e.__esModule?Zt(r,"default",{value:e,enumerable:!0}):r,e));var Ee=require("@medplum/core"),We=require("commander"),yr=z(require("dotenv"),1),ae=require("@medplum/core"),rt=require("commander"),Er=require("@medplum/core"),vr=require("@medplum/core"),ie=require("node:fs"),Sr=require("node:os"),Rt=require("node:path"),se=require("@medplum/core"),Ir=require("commander"),br=require("node:buffer"),$r=z(require("node:util"),1),Tr=z(require("node:crypto"),1),Pr=z(require("node:util"),1),kr=require("node:crypto"),Mr=require("node:crypto"),xe=require("node:crypto"),st=z(require("node:crypto"),1),Ur=require("node:util"),Se=require("node:crypto"),$e=require("node:crypto"),le=require("node:fs"),ne=require("node:path"),_r=require("node:util/types"),xr=require("tar"),Q=require("@medplum/core"),qr=require("node:child_process"),Yr=require("node:http"),Qr=require("node:os"),ce=require("@aws-sdk/client-cloudformation"),it=require("@aws-sdk/client-cloudfront"),os=require("@aws-sdk/client-ecs"),is=require("@aws-sdk/client-s3"),Pe=require("@aws-sdk/client-ssm"),at=require("@aws-sdk/client-sts"),nt=require("@medplum/core"),as=z(require("node-fetch"),1),ns=require("node:fs"),cs=z(require("node:readline"),1),fe=require("@aws-sdk/client-acm"),ut=require("@aws-sdk/client-cloudfront"),pt=require("@aws-sdk/client-sts"),ws=require("@medplum/core"),je=require("node:crypto"),ys=require("node:fs"),vs=require("@aws-sdk/client-s3"),Y=require("@medplum/core"),Ss=z(require("fast-glob"),1),Vt=z(require("node-fetch"),1),q=require("node:fs"),Is=require("node:os"),he=require("node:path"),bs=require("node:stream/promises"),dt=require("@aws-sdk/client-s3"),$s=require("node:child_process"),Xt=require("@medplum/core"),ft=require("node:fs"),zt=require("node:path"),Ls=require("node:readline"),ks=require("node:stream"),Ms=require("node:stream/promises"),gt=require("@medplum/core"),De=z(require("node:assert"),1),_s=require("node:net"),G=require("@medplum/core"),Ct=z(require("iconv-lite"),1),cn=require("@medplum/core"),xs=require("@medplum/core"),js=z(require("node:net"),1),Hs=require("node:fs"),Bs=require("node:fs"),Ks=require("node:os"),Gs=require("node:path"),qs=require("commander"),to=require("@medplum/core"),mo=Object.create,Mt=Object.defineProperty,fo=Object.getOwnPropertyDescriptor,go=Object.getOwnPropertyNames,wo=Object.getPrototypeOf,yo=Object.prototype.hasOwnProperty,Eo=(e,t,r)=>t in e?Mt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),vo=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of go(t))!yo.call(e,o)&&o!==r&&Mt(e,o,{get:()=>t[o],enumerable:!(s=fo(t,o))||s.enumerable});return e},dr=(e,t,r)=>(r=e!=null?mo(wo(e)):{},vo(t||!e||!e.__esModule?Mt(r,"default",{value:e,enumerable:!0}):r,e)),B=(e,t,r)=>Eo(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*$")}),Dt=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}),hr=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=Dt(),{compareIdentifiers:n}=hr(),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}),be=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}),So=A((e,t)=>{"use strict";var r=be(),s=(o,i)=>{let a=r(o,i);return a?a.version:null};t.exports=s}),Io=A((e,t)=>{"use strict";var r=be(),s=(o,i)=>{let a=r(o.trim().replace(/^[=v]+/,""),i);return a?a.version:null};t.exports=s}),bo=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}),Ao=A((e,t)=>{"use strict";var r=be(),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}),$o=A((e,t)=>{"use strict";var r=J(),s=(o,i)=>new r(o,i).major;t.exports=s}),Ro=A((e,t)=>{"use strict";var r=J(),s=(o,i)=>new r(o,i).minor;t.exports=s}),To=A((e,t)=>{"use strict";var r=J(),s=(o,i)=>new r(o,i).patch;t.exports=s}),Po=A((e,t)=>{"use strict";var r=be(),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}),No=A((e,t)=>{"use strict";var r=Z(),s=(o,i,a)=>r(i,o,a);t.exports=s}),Oo=A((e,t)=>{"use strict";var r=Z(),s=(o,i)=>r(o,i,!0);t.exports=s}),Ut=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}),Co=A((e,t)=>{"use strict";var r=Ut(),s=(o,i)=>o.sort((a,c)=>r(a,c,i));t.exports=s}),Lo=A((e,t)=>{"use strict";var r=Ut(),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}),_t=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=Z(),s=(o,i,a)=>r(o,i,a)===0;t.exports=s}),fr=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}),jt=A((e,t)=>{"use strict";var r=Z(),s=(o,i,a)=>r(o,i,a)<=0;t.exports=s}),gr=A((e,t)=>{"use strict";var r=mr(),s=fr(),o=Ze(),i=xt(),a=_t(),c=jt(),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}),ko=A((e,t)=>{"use strict";var r=J(),s=be(),{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}),Mo=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(I=>!T(I[0])),this.set.length===0)this.set=[E];else if(this.set.length>1){for(let I of this.set)if(I.length===1&&O(I[0])){this.set=[I];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 I=this.options.loose,v=I?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 b=w.split(" ").map(D=>W(D,this.options)).join(" ").split(/\s+/).map(D=>yt(D,this.options));I&&(b=b.filter(D=>(n("loose invalid filter",D,this.options),!!D.match(l[u.COMPARATORLOOSE])))),n("range list",b);let k=new Map,C=b.map(D=>new c(D,this.options));for(let D of C){if(T(D))return[D];k.set(D.value,D)}k.size>1&&k.has("")&&k.delete("");let M=[...k.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(I=>j(I,S)&&E.every(v=>I.every(b=>v.intersects(b,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=Mo(),i=new o,a=Dt(),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(),I=E.pop();for(;S&&E.length;)S=E.every(v=>I.intersects(v,w)),I=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,I,v,b,k)=>{n("tilde",y,E,I,v,b,k);let C;return U(I)?C="":U(v)?C=`>=${I}.0.0 <${+I+1}.0.0-0`:U(b)?C=`>=${I}.${v}.0 <${I}.${+v+1}.0-0`:k?(n("replaceTilde pr",k),C=`>=${I}.${v}.${b}-${k} <${I}.${+v+1}.0-0`):C=`>=${I}.${v}.${b} <${I}.${+v+1}.0-0`,n("tilde return",C),C})},_=(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,(I,v,b,k,C)=>{n("caret",y,I,v,b,k,C);let M;return U(v)?M="":U(b)?M=`>=${v}.0.0${E} <${+v+1}.0.0-0`:U(k)?v==="0"?M=`>=${v}.${b}.0${E} <${v}.${+b+1}.0-0`:M=`>=${v}.${b}.0${E} <${+v+1}.0.0-0`:C?(n("replaceCaret pr",C),v==="0"?b==="0"?M=`>=${v}.${b}.${k}-${C} <${v}.${b}.${+k+1}-0`:M=`>=${v}.${b}.${k}-${C} <${v}.${+b+1}.0-0`:M=`>=${v}.${b}.${k}-${C} <${+v+1}.0.0-0`):(n("no pr"),v==="0"?b==="0"?M=`>=${v}.${b}.${k}${E} <${v}.${b}.${+k+1}-0`:M=`>=${v}.${b}.${k}${E} <${v}.${+b+1}.0-0`:M=`>=${v}.${b}.${k} <${+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,I,v,b,k,C)=>{n("xRange",y,E,I,v,b,k,C);let M=U(v),D=M||U(b),ge=D||U(k),Oe=ge;return I==="="&&Oe&&(I=""),C=w.includePrerelease?"-0":"",M?I===">"||I==="<"?E="<0.0.0-0":E="*":I&&Oe?(D&&(b=0),k=0,I===">"?(I=">=",D?(v=+v+1,b=0,k=0):(b=+b+1,k=0)):I==="<="&&(I="<",D?v=+v+1:b=+b+1),I==="<"&&(C="-0"),E=`${I+v}.${b}.${k}${C}`):D?E=`>=${v}.0.0${C} <${+v+1}.0.0-0`:ge&&(E=`>=${v}.${b}.0${C} <${v}.${+b+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,I,v,b,k,C,M,D,ge,Oe)=>(U(E)?S="":U(I)?S=`>=${E}.0.0${y?"-0":""}`:U(v)?S=`>=${E}.${I}.0${y?"-0":""}`:b?S=`>=${S}`:S=`>=${S}${y?"-0":""}`,U(M)?C="":U(D)?C=`<${+M+1}.0.0-0`:U(ge)?C=`<${M}.${+D+1}.0-0`:Oe?C=`<=${M}.${D}.${ge}-${Oe}`:y?C=`<${M}.${D}.${+ge+1}-0`:C=`<=${C}`,`${S} ${C}`.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 I=y[E].semver;if(I.major===w.major&&I.minor===w.minor&&I.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=Dt(),{safeRe:i,t:a}=Fe(),c=gr(),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}),Do=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}),Uo=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}),_o=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}),xo=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}),jo=A((e,t)=>{"use strict";var r=ee(),s=(o,i)=>{try{return new r(o,i).range||"*"}catch{return null}};t.exports=s}),Ft=A((e,t)=>{"use strict";var r=J(),s=et(),{ANY:o}=s,i=ee(),a=tt(),c=Ze(),n=_t(),f=jt(),l=xt(),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}),Fo=A((e,t)=>{"use strict";var r=Ft(),s=(o,i,a)=>r(o,i,">",a);t.exports=s}),Wo=A((e,t)=>{"use strict";var r=Ft(),s=(o,i,a)=>r(o,i,"<",a);t.exports=s}),Ho=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}),Bo=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}}),Ko=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}),wr=A((e,t)=>{"use strict";var r=Fe(),s=Ye(),o=J(),i=hr(),a=be(),c=So(),n=Io(),f=bo(),l=Ao(),u=$o(),d=Ro(),m=To(),g=Po(),h=Z(),N=No(),T=Oo(),O=Ut(),j=Co(),W=Lo(),U=Ze(),oe=_t(),V=mr(),_=fr(),H=xt(),$=jt(),Ne=gr(),wt=ko(),yt=et(),Et=ee(),vt=tt(),y=Do(),w=Uo(),S=_o(),E=xo(),I=jo(),v=Ft(),b=Fo(),k=Wo(),C=Ho(),M=Bo(),D=Ko();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:I,outside:v,gtr:b,ltr:k,intersects:C,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 vr.ClientStorage{constructor(e){super(),B(this,"dirName"),B(this,"fileName"),this.dirName=(0,Rt.resolve)((0,Sr.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}=Go(e,s),d=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await Jo(e.baseUrl,d);let m=new Er.MedplumClient({fetch:d,baseUrl:i,tokenUrl:n,fhirUrlPath:a,authorizeUrl:f,storage:s,onUnauthenticated:Vo,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 Go(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 Jo(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 Vo(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var Me=new TextEncoder,er=new TextDecoder,on=2**32;function Xo(...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=>br.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 Ar=class extends Be{constructor(){super(...arguments),B(this,"code","ERR_JWT_INVALID")}};B(Ar,"code","ERR_JWT_INVALID");var tr,rr,zo=class extends(rr=Be,tr=Symbol.asyncIterator,rr){constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),B(this,tr),B(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};B(zo,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Rr=e=>$r.types.isKeyObject(e),qo=Tr.webcrypto,Yo=qo,Wt=e=>Pr.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 It(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 Zo(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 ei(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Ce(e.algorithm,"HMAC"))throw te("HMAC");let s=parseInt(t.slice(2),10);if(It(e.algorithm.hash)!==s)throw te(`SHA-${s}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Ce(e.algorithm,"RSASSA-PKCS1-v1_5"))throw te("RSASSA-PKCS1-v1_5");let s=parseInt(t.slice(2),10);if(It(e.algorithm.hash)!==s)throw te(`SHA-${s}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Ce(e.algorithm,"RSA-PSS"))throw te("RSA-PSS");let s=parseInt(t.slice(2),10);if(It(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(!Ce(e.algorithm,"Ed25519"))throw te("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Ce(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")}Zo(e,r)}function Nr(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)=>Nr("Key must be ",e,...t);function Or(e,t,...r){return Nr(`Key for the ${e} algorithm must be `,t,...r)}var Cr=e=>Rr(e)||Wt(e),ve=["KeyObject"];(globalThis.CryptoKey||Yo?.CryptoKey)&&ve.push("CryptoKey");var ti=(...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},ri=ti;function si(e){return typeof e=="object"&&e!==null}function Lr(e){if(!si(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 Lr(e)&&typeof e.kty=="string"}function oi(e){return e.kty!=="oct"&&typeof e.d=="string"}function ii(e){return e.kty!=="oct"&&typeof e.d>"u"}function ai(e){return Ke(e)&&e.kty==="oct"&&typeof e.k=="string"}var ni=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")}},ci=(e,t)=>{let r;if(Wt(e))r=kr.KeyObject.from(e);else if(Rr(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:ni(s)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},li=ci,sr=(e,t)=>{let r;try{e instanceof Mr.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},ui=(e,t,r,s)=>{if(!(t instanceof Uint8Array)){if(s&&Ke(t)){if(ai(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(!Cr(t))throw new TypeError(Or(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"`)}},pi=(e,t,r,s)=>{if(s&&Ke(t))switch(r){case"sign":if(oi(t)&&Pt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(ii(t)&&Pt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Cr(t))throw new TypeError(Or(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 Dr(e,t,r,s){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?ui(t,r,s,e):pi(t,r,s,e)}var an=Dr.bind(void 0,!1),di=Dr.bind(void 0,!0);function hi(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 mi=hi;function fi(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 gi=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function wi(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");sr(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");sr(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=li(t),c=gi.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 yi(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 Ei(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(Wt(t))return ei(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 vi=(0,Ur.promisify)(st.sign),Si=async(e,t,r)=>{let s=Ei(e,t,"sign");if(e.startsWith("HS")){let o=st.createHmac(yi(e),s);return o.update(r),o.digest()}return vi(fi(e),r,wi(e,s))},Ii=Si,ue=e=>Math.floor(e.getTime()/1e3),bi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,bt=e=>{let t=bi.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},Ai=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(!ri(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=mi(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');di(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=Xo(c,Me.encode("."),a),f=await Ii(i,e,n),l={signature:St(f),payload:""};return o&&(l.payload=er.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=er.decode(c)),l}},$i=class{constructor(e){B(this,"_flattened"),this._flattened=new Ai(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 Ri=class{constructor(e={}){if(B(this,"_payload"),!Lr(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)+bt(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)+bt(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)+bt(e))}:this._payload={...this._payload,iat:pe("setIssuedAt",e)},this}},Ti=class extends Ri{constructor(){super(...arguments),B(this,"_protectedHeader")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let r=new $i(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 Ar("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}};function de(e){console.log(JSON.stringify(e,null,2))}async function jr(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:ki(s)});console.log("Updating bot...");let a=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+a.meta?.versionId)}async function Fr(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 Wr(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 jr(e,l,f),await Fr(e,l,f),console.log(`Success! Bot created: ${f.id}`),a&&Oi(l)}function Pi(e){let t=new RegExp("^"+Ci(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 Ni(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 Oi(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 Ci(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Li(e){let t=0,r=0;return(0,xr.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 or(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function ki(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 Hr(e,t){let r=new He(e),s={name:e,...t};return r.setObject("options",s),s}function Mi(e){return new He(e).getObject("options")}async function Di(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 Ui(e,t){let r=(0,$e.createPrivateKey)((0,le.readFileSync)((0,ne.resolve)(t.privateKeyPath))),s=await new Ti({}).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 Ir.Command{action(e){let t=_i(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 _i(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,_r.isPromise)(i)&&await i}finally{e.resetOptionDefaults()}}}var Br=new R("status").aliases(["info","list","ls"]),Kr=new R("ping"),Gr=new R("push"),Jr=new R("reload-config"),Vr=new R("upgrade"),Te=new R("agent");P(Te,Br);P(Te,Kr);P(Te,Gr);P(Te,Jr);P(Te,Vr);Br.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 Ht({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let s=Fi(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"}}})});Kr.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 Xr(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})}});Gr.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 Xr(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)});Jr.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 Ht({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Vr.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 Ht({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:s=>({id:s.agent.id,name:s.agent.name,version:t.agentVersion??"latest"})})});async function Ht({operation:e,agentIds:t,options:r,params:s={},parseSuccessfulResponse:o}){let i=Hi(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=xi(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 Vr(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{Xr(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 Xr(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function Xr(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 Qr=Q.MEDPLUM_CLI_CLIENT_ID,Zr="http://localhost:9615",es=new R("login"),ts=new R("whoami"),rs=new R("token");es.action(async e=>{let t=e.profile??"default",r=Wr(t,e),s=await x(e,!1);await Wi(s,r)});ts.action(async e=>{let t=await x(e);Ki(t)});rs.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,qr.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:Qr,redirectUri:Zr});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,Yr.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,zr.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",Qr),t.searchParams.set("redirect_uri",Zr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Bi(t.toString())}var Le="\x1B[0m",Ji="\x1B[1m",Vi="\x1B[31m",Xi="\x1B[32m",zi="\x1B[33m",qi="\x1B[34m",_e={red:e=>`${Vi}${e}${Le}`,green:e=>`${Xi}${e}${Le}`,yellow:e=>`${zi}${e}${Le}`,blue:e=>`${qi}${e}${Le}`,bold:e=>`${Ji}${e}${Le}`},or=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>_e.bold(r)),Yi=pr(gr(),1),ct;function cs(){ct=ns.default.createInterface({input:process.stdin,output:process.stdout})}function ls(){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 Xr(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{zr(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 xi(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(ji(r.resource))}return t}function ji(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 Fi(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=Wi(i,a);r[i]=c}return r}function Wi(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 Hi(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 zr(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function zr(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 Zr=Q.MEDPLUM_CLI_CLIENT_ID,es="http://localhost:9615",ts=new R("login"),rs=new R("whoami"),ss=new R("token");ts.action(async e=>{let t=e.profile??"default",r=Hr(t,e),s=await x(e,!1);await Bi(s,r)});rs.action(async e=>{let t=await x(e);Ji(t)});ss.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 Bi(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Vi(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 Di(e,t);break;case"jwt-assertion":await Ui(e,t);break}}async function Ki(e){let t=(0,Yr.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:Zr,redirectUri:es});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 Gi(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,qr.exec)(r,(i,a,c)=>{if(i){o(i);return}if(c){o(new Error("Could not open browser: "+c));return}s()})})}function Ji(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 Vi(e){await Ki(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Zr),t.searchParams.set("redirect_uri",es),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Gi(t.toString())}var Le="\x1B[0m",Xi="\x1B[1m",zi="\x1B[31m",qi="\x1B[32m",Yi="\x1B[33m",Qi="\x1B[34m",_e={red:e=>`${zi}${e}${Le}`,green:e=>`${qi}${e}${Le}`,yellow:e=>`${Yi}${e}${Le}`,blue:e=>`${Qi}${e}${Le}`,bold:e=>`${Xi}${e}${Le}`},ir=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>_e.bold(r)),Zi=dr(wr(),1),ct;function ls(){ct=cs.default.createInterface({input:process.stdin,output:process.stdout})}function us(){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+")":"")+" ",s=>{r(s||t.toString())})})}async function Bt(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 Bt(e,t.map(s=>s.toString()),r.toString()),10)}async function be(e){return(await Bt(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"}),on=new ss.ECSClient({}),Kt=new os.S3Client({}),Zi="medplum:environment";async function us(){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 Gt(e){let t=await us();for(let r of t){let s=r.StackName,o=await ps(s);if(o?.tag===e)return o}}async function ps(e){let t={};if(await ir(qe,e,t),await qe.config.region()!=="us-east-1")try{await ir(new ce.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function ir(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 ds(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 hs(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 ms(e){let t=(await(await(0,is.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 fs(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,as.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 Jt(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 Gt(e);if(!t)throw await Jt(e),new Error(`Stack not found: ${e}`);ds(t)}var ia=e=>`${e}DomainName`,ys=e=>`${e}SslCertArn`;async function aa(){let e={apiPort:8103,region:"us-east-1"};cs(),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,ws.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 ms())[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[ys(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 fs(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(""),ls()}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 ar(e);if(e!=="us-east-1"){let r=await ar("us-east-1");t.push(...r)}return t}async function ar(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 "${ys(s)}" setting.`),"TODO";let a=await ua(r,o);return p("Certificate ARN: "+a),a}async function ua(e,t){try{let r=await Bt("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,gs.normalizeErrorString)(o));return}}async function da(){let e=await us();for(let t of e){let r=t.StackName,s=await ps(r);s&&(ds(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 Gt(e);if(!s)throw await Jt(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)}Is(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 hs(s.appDistribution.PhysicalResourceId),console.log("Done")}async function ma(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Vt.default)(r)).json()}async function fa(e,t){let r=(await ma(e,t)).dist.tarball,s=(0,q.mkdtempSync)((0,he.join)((0,Ss.tmpdir)(),"tarball-"));try{let o=await(0,Vt.default)(r),i=Oi(s);return await(0,bs.pipeline)(o.body,i),(0,he.join)(s,"package","dist")}catch(o){throw(0,q.rmSync)(s,{recursive:!0,force:!0}),o}}function Is(e,t){for(let r of(0,q.readdirSync)(e,{withFileTypes:!0})){let s=(0,he.join)(e,r.name);r.isDirectory()?Is(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=vs.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 Kt.send(new Es.PutObjectCommand(o))}async function va(e,t){if(!Re(e,t))throw lt(e,t),new Error(`Config not found: ${e}`);let r=await Gt(e);if(!r)throw await Jt(e),new Error(`Stack not found: ${e}`);await nr("App",r.appBucket,r.appDistribution,r.appOriginAccessIdentity,t),await nr("Storage",r.storageBucket,r.storageDistribution,r.storageOriginAccessIdentity,t),console.log("Done")}async function nr(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 hs(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Sa(e){let t=await Kt.send(new dt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function ba(e,t){await Kt.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{cs();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 fs(r.region,`/medplum/${r.name}/`,s)}finally{ls()}}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=pr(gr(),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 cr(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}`,Ca(e,s),await r.startAsyncRequest("/admin/super/migrate"),c=await cr(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 cr(e,t){let r=await ms(e),s=r[0];return r.filter(o=>o===s||o===t||Ot.gte(o,Ot.inc(e,"minor"))).pop()}function Ca(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,As.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 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(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(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 Bt(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 Bt(e,t.map(s=>s.toString()),r.toString()),10)}async function Ie(e){return(await Bt(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({}),ea=new it.CloudFrontClient({region:"us-east-1"}),nn=new os.ECSClient({}),Kt=new is.S3Client({}),ta="medplum:environment";async function ps(){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 Gt(e){let t=await ps();for(let r of t){let s=r.StackName,o=await ds(s);if(o?.tag===e)return o}}async function ds(e){let t={};if(await ar(qe,e,t),await qe.config.region()!=="us-east-1")try{await ar(new ce.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function ar(e,t,r){let s=new ce.DescribeStacksCommand({StackName:t}),o=(await e.send(s))?.Stacks?.[0],i=o?.Tags?.find(c=>c.Key===ta);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)ra(c,r)}}function ra(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 hs(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: ${sa(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 sa(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function ms(e){let t=await ea.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 fs(e){let t=(await(await(0,as.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)=>Zi.compare(s,r)),e?t.slice(0,t.indexOf(e)):t}async function gs(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 oa(s,a);n!==void 0&&n!==c&&(p(`Parameter "${a}" exists with different value.`),await Nt(`Do you want to overwrite "${a}"?`)),await ia(s,a,c)}}async function oa(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 ia(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,ns.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 Jt(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 aa(e){let t=await Gt(e);if(!t)throw await Jt(e),new Error(`Stack not found: ${e}`);hs(t)}var na=e=>`${e}DomainName`,Es=e=>`${e}SslCertArn`;async function ca(){let e={apiPort:8103,region:"us-east-1"};ls(),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 la(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,ys.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 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 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 fs())[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 ha(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 ua(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 pa(e,c,f,l);e[Es(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 Ie("Do you want to store these values in AWS Parameter Store?"))await gs(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(""),us()}async function la(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 ua(e){let t=await nr(e);if(e!=="us-east-1"){let r=await nr("us-east-1");t.push(...r)}return t}async function nr(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 pa(e,t,r,s){let o=e[na(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 Ie("Do you want to request a new certificate?"))return p(`Please add your certificate ARN to the config file in the "${Es(s)}" setting.`),"TODO";let a=await da(r,o);return p("Certificate ARN: "+a),a}async function da(e,t){try{let r=await Bt("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 ha(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,ws.normalizeErrorString)(o));return}}async function ma(){let e=await ps();for(let t of e){let r=t.StackName,s=await ds(r);s&&(hs(s),console.log(""))}}async function fa(e,t){let r=Re(e,t);if(!r)throw lt(e,t),new Error(`Config not found: ${e}`);let s=await Gt(e);if(!s)throw await Jt(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 wa("@medplum/app",a)}As(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 Ea(i,o.PhysicalResourceId,t),s.appDistribution?.PhysicalResourceId&&!t.dryrun&&await ms(s.appDistribution.PhysicalResourceId),console.log("Done")}async function ga(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Vt.default)(r)).json()}async function wa(e,t){let r=(await ga(e,t)).dist.tarball,s=(0,q.mkdtempSync)((0,he.join)((0,Is.tmpdir)(),"tarball-"));try{let o=await(0,Vt.default)(r),i=Li(s);return await(0,bs.pipeline)(o.body,i),(0,he.join)(s,"package","dist")}catch(o){throw(0,q.rmSync)(s,{recursive:!0,force:!0}),o}}function As(e,t){for(let r of(0,q.readdirSync)(e,{withFileTypes:!0})){let s=(0,he.join)(e,r.name);r.isDirectory()?As(s,t):r.isFile()&&s.endsWith(".js")&&ya(s,t)}}function ya(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 Ea(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 va({rootDir:e,bucketName:t,fileNamePattern:o[0],contentType:o[1],cached:o[2],dryrun:r.dryrun})}async function va(e){let t=Ss.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Sa((0,he.join)(e.rootDir,r),e)}async function Sa(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 Kt.send(new vs.PutObjectCommand(o))}async function Ia(e,t){if(!Re(e,t))throw lt(e,t),new Error(`Config not found: ${e}`);let r=await Gt(e);if(!r)throw await Jt(e),new Error(`Stack not found: ${e}`);await cr("App",r.appBucket,r.appDistribution,r.appOriginAccessIdentity,t),await cr("Storage",r.storageBucket,r.storageDistribution,r.storageOriginAccessIdentity,t),console.log("Done")}async function cr(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 ba(i);if($a(c,i,a))throw new Error(`${e} bucket already has policy statement`);Ra(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 Aa(i,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await ms(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function ba(e){let t=await Kt.send(new dt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Aa(e,t){await Kt.send(new dt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function $a(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 Ra(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 Ta(e,t){try{ls();let r=Re(e,t);if(!r)throw lt(e,t),new Error(`Config not found: ${e}`);let s=Ni(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 Ie("Do you want to proceed?")){console.log(_e.red(`Run Aborted, please ensure ${o} is present and try again.`));return}}Pa(r,s),Oa(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 Ie("Do you want to store these values in AWS Parameter Store?"))&&await gs(r.region,`/medplum/${r.name}/`,s)}finally{us()}}function Pa(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(Na(e,t))throw new Error(r)}function Na(e,t){return e!==void 0&&t!==void 0&&e!==t}function Oa(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=dr(wr(),1);async function Ca(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 La(r,s),c=await lr(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}`,ka(e,s),await r.startAsyncRequest("/admin/super/migrate"),c=await lr(c)}}async function La(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 lr(e,t){let r=await fs(e),s=r[0];return r.filter(o=>o===s||o===t||Ot.gte(o,Ot.inc(e,"minor"))).pop()}function ka(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,$s.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 Ma(){let e=new R("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(ca),e.command("list").description("List Medplum AWS CloudFormation stacks").action(ma),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(aa),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(ir(`Update the AWS Parameter Store config values.
8
8
 
9
9
  Configuration values come from a file named **medplum.<tag>.config.server.json** where **<tag>** is the Medplum stack tag.
10
10
 
11
- `+_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($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 $s=new R("save"),Rs=new R("deploy"),Ts=new R("create"),ht=new R("bot");P(ht,$s);P(ht,Rs);P(ht,Ts);var Ps=new R("save-bot"),Ns=new R("deploy-bot"),Os=new R("create-bot");$s.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e)});Rs.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e,!0)});Ts.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 Fr(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 xr(e,n,f),a++,r&&(await jr(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:
11
+ `+_e.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",ir("File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.")).option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--yes","Automatically confirm the update").action(Ta),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(Ca)),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(fa),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(Ia),e}var Rs=new R("save"),Ts=new R("deploy"),Ps=new R("create"),ht=new R("bot");P(ht,Rs);P(ht,Ts);P(ht,Ps);var Ns=new R("save-bot"),Os=new R("deploy-bot"),Cs=new R("create-bot");Rs.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e)});Ts.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e,!0)});Ps.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 Wr(i,e,t,r,s,o.runtimeVersion,!!o.writeConfig)});async function mt(e,t,r=!1){let s=Pi(t),o=[],i=[],a=0,c=0;for(let n of s)try{let f=await e.readResource("Bot",n.id);await jr(e,n,f),a++,r&&(await Fr(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:o})}Ps.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e)});Ns.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e,!0)});Os.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,s,o)=>{let i=await x(o);await Fr(i,e,t,r,s)});var ks=new R("export"),Ms=new R("import"),zt=new R("bulk");P(zt,ks);P(zt,Ms);ks.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,Xt.resolve)(o??"",l);(0,ft.writeFile)(`${u}`,await f.text(),()=>{console.log(`${u} is created`)})})});Ms.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,Xt.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 lr(o,r),o=[])}o.length>0&&await lr(o,r)}async function lr(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let s of r.entry??Cs.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=sr()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=sr())}),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,L=(e,t,r)=>xa(e,typeof t!="symbol"?t+"":t,r),xs=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"),L(this,"connection"),L(this,"message"),this.connection=e,this.message=t}},Fa=class extends Event{constructor(e,t){super("enhancedAckSent"),L(this,"connection"),L(this,"message"),this.connection=e,this.message=t}},Ue=class extends Event{constructor(e){super("error"),L(this,"error"),this.error=e}},Lt=class extends Event{constructor(e){super("warning"),L(this,"error"),this.error=e}},kt=class extends Event{constructor(){super("close")}},ur="utf-8",Wa=5e3,Ha=60*1e3,js=class extends xs{constructor(e,t=ur,r,s={}){super(),L(this,"socket"),L(this,"encoding"),L(this,"enhancedMode"),L(this,"messagesPerMin"),L(this,"gracefulCloseTimeoutMs"),L(this,"chunks",[]),L(this,"pendingMessages",new Map),L(this,"responseQueue",[]),L(this,"lastMessageDispatchedTime",0),L(this,"responseQueueProcessing",!1),L(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=s.messagesPerMin,this.gracefulCloseTimeoutMs=s.gracefulCloseTimeoutMs??Wa,e.on("data",o=>{if(this.closing){this.dispatchEvent(new Lt(new G.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}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 kt)}),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 Lt(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=Ct.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=Ha/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=Ct.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.closing=!0,this.socket.end(),this.drainPendingMessages(),await new Promise(e=>{let t=setTimeout(()=>{this.socket.destroy()},this.gracefulCloseTimeoutMs);this.socket.once("close",()=>{clearTimeout(t),e()})}))}drainPendingMessages(){if(!this.pendingMessages.size)return;let e=this.pendingMessages.size;for(let t of this.pendingMessages.values())t.timer&&clearTimeout(t.timer),t.reject(new 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??ur}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}},Ba=class extends xs{constructor(e){super(),L(this,"options"),L(this,"host"),L(this,"port"),L(this,"encoding"),L(this,"connection"),L(this,"keepAlive"),L(this,"socket"),L(this,"connectTimeout"),L(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,Ds.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 kt)}),e.addEventListener("error",t=>{this.dispatchEvent(new Ue(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new Lt(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 kt);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},Ka=1e4,Ga=class{constructor(e){L(this,"handler"),L(this,"server"),L(this,"encoding"),L(this,"enhancedMode"),L(this,"messagesPerMin"),L(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=_s.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,Us.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??Ka)),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}},Ja=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=Xa():s.file&&(r=(0,Fs.readFileSync)(s.file,"utf8")),!r)throw new Error("Missing HL7 message body");let o=new Ba({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()}}),Va=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 Ga(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)}),qt=new R("hl7");P(qt,Ja);P(qt,Va);function Xa(){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})}Ns.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e)});Os.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e,!0)});Cs.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,s,o)=>{let i=await x(o);await Wr(i,e,t,r,s)});var Ds=new R("export"),Us=new R("import"),qt=new R("bulk");P(qt,Ds);P(qt,Us);Ds.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),a=await i.bulkExport(t,r,s,{pollStatusOnAccepted:!0});for(let{type:c,url:n}of a.output??Xt.EMPTY){let f=new URL(n),l=`${c}_${f.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",u=(0,zt.resolve)(o??"",l),d=await i.downloadResponse(n);if(!d.ok)throw new Error(`Download failed: ${d.status} ${d.statusText}`);if(!d.body)throw new Error("Download response missing body");let m=ks.Readable.fromWeb(d.body);await(0,Ms.pipeline)(m,(0,ft.createWriteStream)(u)),console.log(`${u} is created`)}});Us.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,zt.resolve)(o??process.cwd(),e),a=await x(t);await Da(i,Number.parseInt(r,10),a,s)});async function Da(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=Ua(c,s);o.push({resource:n,request:{method:"POST",url:n.resourceType}}),o.length%t===0&&(await ur(o,r),o=[])}o.length>0&&await ur(o,r)}async function ur(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let s of r.entry??Xt.EMPTY)de(s.response)}function Ua(e,t){let r=JSON.parse(e);return t?_a(r):r}function _a(e){return e.resourceType==="ExplanationOfBenefit"?xa(e):e}function xa(e){return e.provider||(e.provider=or()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=or())}),e}var ja=Object.defineProperty,Fa=(e,t,r)=>t in e?ja(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,L=(e,t,r)=>Fa(e,typeof t!="symbol"?t+"":t,r),Fs=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Wa=class extends Event{constructor(e,t){super("message"),L(this,"connection"),L(this,"message"),this.connection=e,this.message=t}},Ha=class extends Event{constructor(e,t){super("enhancedAckSent"),L(this,"connection"),L(this,"message"),this.connection=e,this.message=t}},Ue=class extends Event{constructor(e){super("error"),L(this,"error"),this.error=e}},Lt=class extends Event{constructor(e){super("warning"),L(this,"error"),this.error=e}},kt=class extends Event{constructor(){super("close")}},pr="utf-8",Ba=5e3,Ka=60*1e3,Ws=class extends Fs{constructor(e,t=pr,r,s={}){super(),L(this,"socket"),L(this,"encoding"),L(this,"enhancedMode"),L(this,"messagesPerMin"),L(this,"gracefulCloseTimeoutMs"),L(this,"chunks",[]),L(this,"pendingMessages",new Map),L(this,"responseQueue",[]),L(this,"lastMessageDispatchedTime",0),L(this,"responseQueueProcessing",!1),L(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=s.messagesPerMin,this.gracefulCloseTimeoutMs=s.gracefulCloseTimeoutMs??Ba,e.on("data",o=>{if(this.closing){this.dispatchEvent(new Lt(new G.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(o);let i=this.parseMessages();for(let a of i)this.responseQueue.push(new Wa(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 kt)}),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 Ha(this,i)));let a=o.message.getSegment("MSA")?.getField(2)?.toString();if(!a)return;let c=this.getPendingMessage(a);if(!c){this.dispatchEvent(new Lt(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.timer&&clearTimeout(c.timer),c.resolve(o.message),this.deletePendingMessage(a)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Ct.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=Ka/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=Ct.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.deletePendingMessage(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.setPendingMessage(o,{message:e,resolve:r,reject:s,returnAck:t?.returnAck??G.ReturnAckCategory.APPLICATION,timer:i}),this.sendImpl(e)})}async close(){this.isClosed()||(this.closing=!0,this.socket.end(),this.drainPendingMessages(),await new Promise(e=>{let t=setTimeout(()=>{this.socket.destroy()},this.gracefulCloseTimeoutMs);this.socket.once("close",()=>{clearTimeout(t),e()})}))}drainPendingMessages(){if(!this.pendingMessages.size)return;let e=this.pendingMessages.size;for(let t of this.pendingMessages.values())t.timer&&clearTimeout(t.timer),t.reject(new 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??pr}getEncoding(){return this.encoding}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}getPendingMessageCount(){return this.pendingMessages.size}getPendingMessage(e){return this.pendingMessages.get(e)}setPendingMessage(e,t){this.pendingMessages.set(e,t)}deletePendingMessage(e){this.pendingMessages.delete(e)}},Ga=class extends Fs{constructor(e){super(),L(this,"options"),L(this,"host"),L(this,"port"),L(this,"encoding"),L(this,"connection"),L(this,"keepAlive"),L(this,"socket"),L(this,"connectTimeout"),L(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,_s.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=this.createConnection(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 kt)}),e.addEventListener("error",t=>{this.dispatchEvent(new Ue(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new Lt(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)}createConnection(e,t,r,s){return new Ws(e,t,r,s)}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 kt);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},Ja=1e4,Va=class{constructor(e){L(this,"handler"),L(this,"server"),L(this,"encoding"),L(this,"enhancedMode"),L(this,"messagesPerMin"),L(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=js.default.createServer(i=>{let a=new Ws(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,xs.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??Ja)),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}},Xa=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=qa():s.file&&(r=(0,Hs.readFileSync)(s.file,"utf8")),!r)throw new Error("Missing HL7 message body");let o=new Ga({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()}}),za=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 Va(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)}),Yt=new R("hl7");P(Yt,Xa);P(Yt,za);function qa(){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 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)=>{Wr(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=Li(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);za(t)});function za(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 Js=new R("set"),Vs=new R("remove"),Xs=new R("list"),zs=new R("describe"),Ge=new R("profile");P(Ge,Js);P(Ge,Vs);P(Ge,Xs);P(Ge,zs);Js.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)=>{Hr(e,t)});Vs.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`)});Xs.description("List all profiles saved").action(async()=>{let e=(0,Gs.resolve)((0,Ks.homedir)(),".medplum"),t=(0,Bs.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)});zs.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=Mi(e);console.log(t)});var Ys=new R("list"),Qs=new R("current"),Zs=new R("switch"),eo=new R("invite"),Je=new R("project");P(Je,Ys);P(Je,Qs);P(Je,Zs);P(Je,eo);Ys.description("List of current projects").action(async e=>{let t=await x(e);Ya(t)});function Ya(e){let t=e.getLogins().map(r=>`${r.project.display} (${r.project.reference})`).join(`
20
20
 
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 qa(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 Ya(a,c,o)});async function qa(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 Ya(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),Yt(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),Yt(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),Yt(t)))});function Yt(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(Ee.MEDPLUM_VERSION),t.configureHelp({showGlobalOptions:!0}),P(t,es),P(t,ts),P(t,rs),P(t,to),P(t,so),P(t,ro),P(t,oo),P(t,eo),P(t,Je),P(t,zt),P(t,ht),P(t,Te),P(t,Ps),P(t,Ns),P(t,Os),P(t,Ge),P(t,La()),P(t,qt);try{await t.parseAsync(e)}catch(r){Za(r)}}function Za(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)}
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})`)});Zs.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await x(t);await Qa(r,e)});eo.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 qs.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 Za(a,c,o)});async function Qa(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 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 ro=new R("delete"),so=new R("get"),oo=new R("patch"),io=new R("post"),ao=new R("put");ro.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await x(t);de(await r.delete(Ve(r,e)))});so.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,to.convertToTransactionBundle)(s)):de(s)});oo.arguments("<url> <body>").action(async(e,t,r)=>{let s=await x(r);de(await s.patch(Ve(s,e),Qt(t)))});io.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}))});ao.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 en(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,ts),P(t,rs),P(t,ss),P(t,so),P(t,io),P(t,oo),P(t,ao),P(t,ro),P(t,Je),P(t,qt),P(t,ht),P(t,Te),P(t,Ns),P(t,Os),P(t,Cs),P(t,Ge),P(t,Ma()),P(t,Yt);try{await t.parseAsync(e)}catch(r){tn(r)}}function tn(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
23
  `):process.stderr.write(`Error: ${(0,Ee.normalizeErrorString)(e)}
24
- `)}async function en(){wr.default.config({quiet:!0}),await Qa(process.argv)}en().catch(e=>{console.error("Unhandled error:",(0,Ee.normalizeErrorString)(e)),process.exit(1)});
24
+ `)}async function rn(){yr.default.config({quiet:!0}),await en(process.argv)}rn().catch(e=>{console.error("Unhandled error:",(0,Ee.normalizeErrorString)(e)),process.exit(1)});
25
25
  //# sourceMappingURL=index.cjs.map