medplum 5.1.29 → 5.1.30

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,7 +1,7 @@
1
1
  #!/usr/bin/env node
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(`
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,{__proto__:null,[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=typeof e=="string"?Zs[e]:void 0;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
- `),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+`
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,t);break;case"basic":e.setBasicAuth(t.clientId,t.clientSecret);break;case"client-credentials":e.setBasicAuth(t.clientId,t.clientSecret),await e.startClientLogin(t.clientId,t.clientSecret);break;case"jwt-bearer":await 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,t){await $i(e);let r=new URL(e.getAuthorizeUrl());r.searchParams.set("client_id",In),r.searchParams.set("redirect_uri",$n),r.searchParams.set("scope",t.scope??"openid offline_access"),r.searchParams.set("response_type","code"),r.searchParams.set("prompt","login"),await Ri(r.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
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.
@@ -24,7 +24,7 @@ PID|1|12345|12345^^^HOSP^MR|123456|DOE^JOHN^MIDDLE^SUFFIX|19800101|M|||123 STREE
24
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(`
25
25
 
26
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)}
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>",'OAuth scope (e.g., "openid offline_access")').option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new 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
28
  `):process.stderr.write(`Error: ${(0,Ae.normalizeErrorString)(e)}
29
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)});
30
30
  //# sourceMappingURL=index.cjs.map