medplum 5.1.28 → 5.1.29

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