medplum 5.2.5 → 5.2.7

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