medplum 5.2.4 → 5.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +13 -13
- package/dist/cjs/index.cjs.map +3 -3
- package/dist/esm/index.mjs +13 -13
- package/dist/esm/index.mjs.map +3 -3
- package/package.json +3 -3
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Pn=Object.create;var cr=Object.defineProperty;var On=Object.getOwnPropertyDescriptor;var Nn=Object.getOwnPropertyNames;var Cn=Object.getPrototypeOf,Ln=Object.prototype.hasOwnProperty;var Dn=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Nn(t))!Ln.call(e,n)&&n!==r&&cr(e,n,{get:()=>t[n],enumerable:!(o=On(t,n))||o.enumerable});return e};var pe=(e,t,r)=>(r=e!=null?Pn(Cn(e)):{},Dn(t||!e||!e.__esModule?cr(r,"default",{value:e,enumerable:!0}):r,e));var ve=require("@medplum/core"),_e=require("commander"),xr=require("node:fs"),re=require("@medplum/core"),Fe=require("commander"),jr=require("@medplum/core"),_r=require("@medplum/core"),se=require("node:fs"),Fr=require("node:os"),_t=require("node:path"),J=require("@medplum/core"),Wr=require("commander"),be=require("node:crypto"),ue=require("node:fs"),ae=require("node:path"),Jr=require("node:util/types"),Vr=require("tar"),Z=require("@medplum/core"),ao=require("node:child_process"),lo=require("node:http"),co=require("node:os"),uo=require("node:util"),le=require("@aws-sdk/client-cloudformation"),ct=require("@aws-sdk/client-cloudfront"),wo=require("@aws-sdk/client-ecs"),yo=require("@aws-sdk/client-s3"),Ie=require("@aws-sdk/client-ssm"),ut=require("@aws-sdk/client-sts"),pt=require("@medplum/core"),Eo=require("node:fs"),vo=pe(require("node:readline"),1),we=require("@aws-sdk/client-acm"),ht=require("@aws-sdk/client-cloudfront"),mt=require("@aws-sdk/client-sts"),Oo=require("@medplum/core"),Ue=require("node:crypto"),No=require("node:fs"),Lo=require("@aws-sdk/client-s3"),Q=require("@medplum/core"),Do=pe(require("fast-glob"),1),q=require("node:fs"),Mo=require("node:os"),fe=require("node:path"),ko=require("node:stream"),Uo=require("node:stream/promises"),gt=require("@aws-sdk/client-s3"),jo=require("node:util"),_o=require("node:child_process"),X=require("@medplum/core"),Et=require("node:fs"),nr=require("node:path"),Jo=require("node:readline"),Vo=require("node:stream"),Xo=require("node:stream/promises"),qe=pe(require("fast-glob"),1),sr=require("node:events"),qo=require("node:fs"),vt=require("node:fs/promises"),$e=require("node:path"),Qo=require("node:stream"),St=require("@medplum/core"),De=pe(require("node:assert"),1),rn=pe(require("node:net"),1),H=require("@medplum/core"),Gt=pe(require("iconv-lite"),1),Xa=require("@medplum/core"),on=require("@medplum/core"),nn=pe(require("node:net"),1),ln=require("node:fs"),cn=require("node:fs"),un=require("node:os"),pn=require("node:path"),gn=require("commander"),Sn=require("@medplum/core"),Tn=require("@medplum/core"),Re=require("node:fs"),Qe=require("node:path"),Mn=Object.create,Jt=Object.defineProperty,kn=Object.getOwnPropertyDescriptor,Un=Object.getOwnPropertyNames,xn=Object.getPrototypeOf,jn=Object.prototype.hasOwnProperty,Or=e=>{throw TypeError(e)},_n=(e,t,r)=>t in e?Jt(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}},Fn=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Un(t))!jn.call(e,n)&&n!==r&&Jt(e,n,{get:()=>t[n],enumerable:!(o=kn(t,n))||o.enumerable});return e},Nr=(e,t,r)=>(r=e!=null?Mn(xn(e)):{},Fn(t||!e||!e.__esModule?Jt(r,"default",{value:e,enumerable:!0}):r,e)),z=(e,t,r)=>_n(e,typeof t!="symbol"?t+"":t,r),Cr=(e,t,r)=>t.has(e)||Or("Cannot "+r),ur=(e,t,r)=>(Cr(e,t,"read from private field"),r?r.call(e):t.get(e)),Wn=(e,t,r)=>t.has(e)?Or("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Bn=(e,t,r,o)=>(Cr(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}),je=$((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 _=m(I),W=g++;i(E,W,I),u[E]=W,a[W]=I,f[W]=_,s[W]=new RegExp(I,N?"g":void 0),l[W]=new RegExp(_,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*$")}),Vt=$((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}),Lr=$((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}=je(),l=Vt(),{compareIdentifiers:a}=Lr(),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}),Gn=$((e,t)=>{"use strict";var r=he(),o=(n,i)=>{let s=r(n,i);return s?s.version:null};t.exports=o}),Hn=$((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}),Kn=$((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}),Jn=$((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}),Vn=$((e,t)=>{"use strict";var r=K(),o=(n,i)=>new r(n,i).major;t.exports=o}),Xn=$((e,t)=>{"use strict";var r=K(),o=(n,i)=>new r(n,i).minor;t.exports=o}),zn=$((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}),Qn=$((e,t)=>{"use strict";var r=ee(),o=(n,i)=>r(n,i,!0);t.exports=o}),Xt=$((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}),Zn=$((e,t)=>{"use strict";var r=Xt(),o=(n,i)=>n.sort((s,l)=>r(s,l,i));t.exports=o}),ei=$((e,t)=>{"use strict";var r=Xt(),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}),zt=$((e,t)=>{"use strict";var r=ee(),o=(n,i,s)=>r(n,i,s)<0;t.exports=o}),Dr=$((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}),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}),kr=$((e,t)=>{"use strict";var r=Dr(),o=Mr(),n=rt(),i=Yt(),s=zt(),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}),ti=$((e,t)=>{"use strict";var r=K(),o=he(),{safeRe:n,t:i}=je(),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}),ri=$((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}),oi=$((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 Ye{constructor(w,S){if(S=s(S),w instanceof Ye)return w.loose===!!S.loose&&w.includePrerelease===!!S.includePrerelease?w:new Ye(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,Tt(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(j=>ne(j,this.options)).join(" ").split(/\s+/).map(j=>Rt(j,this.options));O&&(A=A.filter(j=>(a("loose invalid filter",j,this.options),!!j.match(u[c.COMPARATORLOOSE])))),a("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 Ye))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 f(w,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(Pt(this.set[S],w,this.options))return!0;return!1}};t.exports=o;var n=oi(),i=new n,s=Vt(),l=ot(),a=tt(),f=K(),{safeRe:u,src:g,t:c,comparatorTrimReplace:d,tildeTrimReplace:m,caretTrimReplace:p}=je(),{FLAG_INCLUDE_PRERELEASE:E,FLAG_LOOSE:I}=xe(),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},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=At(y,w),a("xrange",y),y=$t(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=>bt(S,w)).join(" "),bt=(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})},At=(y,w)=>(a("replaceXRanges",y,w),y.split(/\s+/).map(S=>It(S,w)).join(" ")),It=(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),j=D||C(A),ye=j||C(L),Pe=ye;return O==="="&&Pe&&(O=""),k=w.includePrerelease?"-0":"",D?O===">"||O==="<"?b="<0.0.0-0":b="*":O&&Pe?(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`:ye&&(b=`>=${v}.${A}.0${k} <${v}.${+A+1}.0-0`),a("xRange return",b),b})},$t=(y,w)=>(a("replaceStars",y,w),y.trim().replace(u[c.STAR],"")),Rt=(y,w)=>(a("replaceGTE0",y,w),y.trim().replace(u[w.includePrerelease?c.GTE0PRE:c.GTE0],"")),Tt=y=>(w,S,b,O,v,A,L,k,D,j,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(j)?k=`<${+D+1}.0.0-0`:C(ye)?k=`<${D}.${+j+1}.0-0`:Pe?k=`<=${D}.${j}.${ye}-${Pe}`:y?k=`<${D}.${j}.${+ye+1}-0`:k=`<=${k}`,`${S} ${k}`.trim()),Pt=(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=Vt(),{safeRe:i,t:s}=je(),l=kr(),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}),ni=$((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}),ii=$((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}),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=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}),li=$((e,t)=>{"use strict";var r=te(),o=(n,i)=>{try{return new r(n,i).range||"*"}catch{return null}};t.exports=o}),Qt=$((e,t)=>{"use strict";var r=K(),o=ot(),{ANY:n}=o,i=te(),s=nt(),l=rt(),a=zt(),f=qt(),u=Yt(),g=(c,d,m,p)=>{c=new r(c,p),d=new i(d,p);let E,I,N,_,W;switch(m){case">":E=l,I=f,N=a,_=">",W=">=";break;case"<":E=a,I=u,N=l,_="<",W="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(s(c,d,p))return!1;for(let Y=0;Y<d.set.length;++Y){let ne=d.set[Y],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===_||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}),ci=$((e,t)=>{"use strict";var r=Qt(),o=(n,i,s)=>r(n,i,">",s);t.exports=o}),ui=$((e,t)=>{"use strict";var r=Qt(),o=(n,i,s)=>r(n,i,"<",s);t.exports=o}),pi=$((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}),di=$((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}}),fi=$((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 _=u(I,N,p);if(E=E||_!==null,_)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 _;if(I&&N&&(_=s(I.semver,N.semver,p),_>0||_===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,Y,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(Y=c(N,P,p),Y===P&&Y!==N)return!1}else if(N.operator==="<="&&!P.test(N.semver))return!1}if(!P.operator&&(N||I)&&_!==0)return!1}return!(I&&ne&&!N&&_!==0||N&&C&&!I&&_!==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}),Ur=$((e,t)=>{"use strict";var r=je(),o=xe(),n=K(),i=Lr(),s=he(),l=Gn(),a=Hn(),f=Kn(),u=Jn(),g=Vn(),c=Xn(),d=zn(),m=Yn(),p=ee(),E=qn(),I=Qn(),N=Xt(),_=Zn(),W=ei(),Y=rt(),ne=zt(),C=Dr(),x=Mr(),B=Yt(),P=qt(),Te=kr(),bt=ti(),At=ri(),It=ot(),$t=te(),Rt=nt(),Tt=ni(),Pt=ii(),y=si(),w=ai(),S=li(),b=Qt(),O=ci(),v=ui(),A=pi(),L=di(),k=fi();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:_,rsort:W,gt:Y,lt:ne,eq:C,neq:x,gte:B,lte:P,cmp:Te,coerce:bt,truncate:At,Comparator:It,Range:$t,satisfies:Rt,toComparators:Tt,maxSatisfying:Pt,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 _r.ClientStorage{constructor(e){super(),z(this,"dirName"),z(this,"fileName"),this.dirName=(0,_t.resolve)((0,Fr.homedir)(),".medplum"),this.fileName=(0,_t.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")}};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}=hi(e,o),c=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await mi(e.baseUrl,c);let d=new jr.MedplumClient({fetch:c,baseUrl:i,tokenUrl:a,fhirUrlPath:s,authorizeUrl:f,storage:o,onUnauthenticated:gi,verbose:e.verbose});return t&&(l?d.setAccessToken(l):u&&g&&(d.setBasicAuth(u,g),n?.authType!=="basic"&&await d.startClientLogin(u,g))),d}function hi(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 mi(e,t){try{let r=new URL("healthcheck",e).toString(),o=await t(r);if(!o.ok)throw new Error(`Healthcheck returned status ${o.status}`);if((await o.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${o}`)}}function gi(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var it=new TextEncoder,wi=new TextDecoder,Ka=new TextDecoder("utf-8",{fatal:!0}),Ja=2**32;function yi(...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 Ei=/[^\x00-\x7f]/;function Ot(e){if(typeof e=="string"&&e.length>=128){if(Ei.test(e))throw new TypeError("non-ASCII string encountered in encode()");return it.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 vi(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 Si(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 st=class extends Be{constructor(){super(...arguments),z(this,"code","ERR_JOSE_NOT_SUPPORTED")}};z(st,"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 Br=class extends Be{constructor(){super(...arguments),z(this,"code","ERR_JWT_INVALID")}};z(Br,"code","ERR_JWT_INVALID");var pr,dr,bi=class extends(dr=Be,pr=Symbol.asyncIterator,dr){constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),z(this,pr,async function*(){}),z(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};z(bi,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var Ai="The input to be decoded is not correctly encoded.";function Ii(e){try{return Si(typeof e=="string"?e:wi.decode(e),!0)}catch(t){throw new TypeError(Ai,{cause:t})}}function Ve(e){return vi(typeof e=="string"?it.encode(e):e,!0)}function Zt(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 $i(...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 Ri(e,t){if(e!==void 0)throw new TypeError(`${t} can only be called once`)}var Ti={__proto__:null,b64:!0};function Pi(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 Oi(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 st(`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 Ni(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 fr(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(!Zt(o))throw new e("JOSE Header is not a JSON object");return[o,r]}var Ci=e=>e[Symbol.toStringTag],Li=(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 Di(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(Zt(t)){if(s=Bi(t),typeof s.kty!="string")throw hr(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(Li(e,s,r),s.kty==="oct")return Ii(s.k);if(!Object.isFrozen(t)){let{key_ops:u}=t;Array.isArray(u)&&Object.freeze(u),Object.freeze(t)}}else{if(!Ui(t))throw hr(o,t,n);let u=n?"secret":i?"private":"public";if(t.type!==u&&(n||["secret","public","private"].includes(t.type)))throw new TypeError(`${Ci(t)} instances must be of type "${u}" for the ${o} algorithm`);if(Gr(t))return t;if(l=t,l.type==="secret")return l.export()}Nt||=new WeakMap;let a=t,f=Nt.get(a);if(f?.[o])return f[o];if(f||Nt.set(a,f={}),l&&typeof l.toCryptoKey=="function"){let u=l.type==="public",g=Mi[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 Gi(e,s)}var Nt,Mi={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"},Gr=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},ki=e=>e?.[Symbol.toStringTag]==="KeyObject",Ui=e=>Gr(e)||ki(e);function xi(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 hr(e,t,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(xi(`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 _i(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 Fi(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 Wi(e){return{__proto__:null,...e}}function Bi(e){let t=Wi(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 Gi(e,t,r){if(!e.kty.includes(t.kty))throw new st('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 Hi(e,t,r,o=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,o,[r])),Fi(e,t,r),e}function Ki(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var Ge=[["verify"],["sign"]];function Ct(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 Lt(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Ge}}function mr(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Ge}}function Dt(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Ge}}var Ji=Ki({HS256:Ct(256),HS384:Ct(384),HS512:Ct(512),RS256:Ee(256),RS384:Ee(384),RS512:Ee(512),PS256:Ee(256,32),PS384:Ee(384,48),PS512:Ee(512,64),ES256:Lt("P-256",256),ES384:Lt("P-384",384),ES512:Lt("P-521",512),EdDSA:mr(),Ed25519:mr(),"ML-DSA-44":Dt(44),"ML-DSA-65":Dt(65),"ML-DSA-87":Dt(87)});function Vi(e){let t=typeof e=="string"?Ji[e]:void 0;if(!t)throw new st(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}var Ze=e=>Math.floor(e.getTime()/1e3),Xi={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},zi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Mt(){throw new TypeError("Invalid time period format")}function Hr(e){typeof e!="string"&&Mt();let t=zi.exec(e);(!t||t[4]&&t[1])&&Mt();let r=parseFloat(t[2]),o=Math.round(r*Xi[t[3][0].toLowerCase()]);return Number.isFinite(o)||Mt(),t[1]==="-"||t[4]==="ago"?-o:o}function Ft(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function kt(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 Ut(e,t){return typeof e=="number"?Ft(t,e):e instanceof Date?Ft(t,Ze(e)):Ze(new Date)+Hr(e)}var Kr;function ce(e){return Kr.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 it.encode(JSON.stringify(t))}var Qi=class{constructor(e={}){if(!Zt(e))throw new TypeError("JWT Claims Set MUST be an object");(Kr||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return kt("iss",e),ce(this).iss=e,this}setSubject(e){return kt("sub",e),ce(this).sub=e,this}setAudience(e){return Yi(e),ce(this).aud=e,this}setJti(e){return kt("jti",e),ce(this).jti=e,this}setNotBefore(e){return ce(this).nbf=Ut(e,"setNotBefore"),this}setExpirationTime(e){return ce(this).exp=Ut(e,"setExpirationTime"),this}setIssuedAt(e){let t=ce(this);return e===void 0?t.iat=Ze(new Date):typeof e=="string"?t.iat=Ft("setIssuedAt",Ze(new Date)+Hr(e)):t.iat=Ut(e,"setIssuedAt"),this}};async function Zi(e,t,r){let[o,n,i,s]=e,l="";if(n!==void 0){let I=fr(ie,n);n=I[0],l=Ve(I[1])}if(i!==void 0&&(i=fr(ie,i)[0]),!n&&!i)throw new ie("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!$i(n,i))throw new ie("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let a={...n,...i};Pi(ie,n);let f=Ni(n,Oi(ie,Ti,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=Vi(u),c="",d=o,m;if(f){let I=e[4];I?(c=I[0]??=Ve(o),d=I[1]??=Ot(c)):(c=Ve(o),m=it.encode(`${l}.${c}`))}m??=yi(Ot(l),Ot("."),d);let p=await Hi(await Di(g,t,"sign"),g.subtle,"sign");g.minRsaBits&&_i(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 es(e,t,r,o,n){let[i]=await Zi([e,t,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var ts=Qi,Le,rs=class extends ts{constructor(){super(...arguments),Wn(this,Le)}setProtectedHeader(e){return Ri(ur(this,Le),"setProtectedHeader"),Bn(this,Le,e),this}async sign(e,t){return es(qi(this),ur(this,Le),t?.crit,e,()=>{throw new Br("JWTs MUST NOT use unencoded payload")})}};Le=new WeakMap;function de(e){console.log(JSON.stringify(e,null,2))}async function Xr(e,t,r){let o=t.source,n=at(o);if(!n)return;console.log("Saving source code...");let i=await e.createAttachment({data:n,filename:(0,ae.basename)(o),contentType:ls(o)});console.log("Updating bot...");let s=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+s.meta?.versionId)}async function zr(e,t,r){let o=t.dist??t.source,n=at(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 Xr(e,u,f),await zr(e,u,f),console.log(`Success! Bot created: ${f.id}`),s&&is(u)}function os(e){let t=new RegExp("^"+ss(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=at(r);if(o)return JSON.parse(o)}function ns(e){let t=at(me(e,{server:!0}));if(t)return JSON.parse(t)}function at(e){let t=(0,ae.resolve)(e);return(0,ue.existsSync)(t)?(0,ue.readFileSync)(t,"utf8"):""}function is(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 ss(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function as(e){let t=0,r=0;return(0,Vr.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 gr(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function ls(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 cs(e){return new We(e).getObject("options")}async function us(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 ps(e,t){let r=(0,be.createPrivateKey)((0,ue.readFileSync)((0,ae.resolve)(t.privateKeyPath))),o=await new rs({}).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 Wr.Command{action(e){let t=ds(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 ds(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,Jr.isPromise)(i)&&await i}finally{e.resetOptionDefaults()}}}var Qr=new R("status").aliases(["info","list","ls"]),Zr=new R("ping"),eo=new R("push"),to=new R("reload-config"),ro=new R("upgrade"),oo=new R("stats"),ge=new R("agent");T(ge,Qr);T(ge,Zr);T(ge,eo);T(ge,to);T(ge,ro);T(ge,oo);Qr.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 lt({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=io(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"}}})});Zr.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 no(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})}});eo.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 no(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)});to.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 lt({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});ro.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 lt({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});oo.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 lt({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:o}=io(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(),fs(r[o])}})});var wr=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function yr(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function Er(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 fs(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 wr)r[s]=yr(e.stats[s]);let o=new Set([...wr,"channelStats","clientStats"]);for(let[s,l]of Object.entries(e.stats))o.has(s)||(r[s]=yr(l));console.table(r);let n=Er(e.stats.channelStats);n.length&&(console.info("Channel Stats:"),console.table(n));let i=Er(e.stats.clientStats);i.length&&(console.info("Client Stats:"),console.table(i))}async function lt({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:n,renderSuccessfulRows:i}){let s=ws(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=hs(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(`
|
|
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
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
|
|
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
5
|
`)}function F(e){h(`
|
|
6
6
|
`+e+`
|
|
7
|
-
`)}function V(e,t=""){return new Promise(r=>{dt.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function er(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 er(e,t.map(o=>o.toString()),r.toString()),10)}async function Se(e){return(await er(e,["y","n"])).toLowerCase()==="y"}async function Wt(e){if(!await Se(e))throw h("Exiting..."),new Error("User cancelled")}var et=new le.CloudFormationClient({}),Ns=new ct.CloudFrontClient({region:"us-east-1"}),Va=new wo.ECSClient({}),tr=new yo.S3Client({}),Cs="medplum:environment";async function Ao(){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??pt.EMPTY)e.push(o);return e}async function rr(e){let t=await Ao();for(let r of t){let o=r.StackName,n=await Io(o);if(n?.tag===e)return n}}async function Io(e){let t={};if(await Sr(et,e,t),await et.config.region()!=="us-east-1")try{await Sr(new le.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Sr(e,t,r){let o=new le.DescribeStacksCommand({StackName:t}),n=(await e.send(o))?.Stacks?.[0],i=n?.Tags?.find(l=>l.Key===Cs);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)Ls(l,r)}}function Ls(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 $o(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: ${Ds(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 Ds(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Ro(e){let t=await Ns.send(new ct.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function To(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)=>Os.compare(o,r)),e?t.slice(0,t.indexOf(e)):t}async function Po(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 Ms(o,s);a!==void 0&&a!==l&&(h(`Parameter "${s}" exists with different value.`),await Wt(`Do you want to overwrite "${s}"?`)),await ks(o,s,l)}}async function Ms(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 ks(e,t,r){let o=new Ie.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function ft(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,Eo.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 or(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new ut.STSClient,r=new ut.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,pt.normalizeErrorString)(t))}}async function Us(e){let t=await rr(e);if(!t)throw await or(e),new Error(`Stack not found: ${e}`);$o(t)}var xs=e=>`${e}DomainName`,Co=e=>`${e}SslCertArn`;async function js(){let e={apiPort:8103,region:"us-east-1"};So(),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 _s(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 Wt("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,No.existsSync)(r)&&(h("Config file already exists."),await Wt("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 To())[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 Gs(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 Fs(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 Ws(e,l,f,u);e[Co(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 Po(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(""),bo()}async function _s(e){try{let t=new mt.STSClient({region:e}),r=new mt.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Fs(e){let t=await br(e);if(e!=="us-east-1"){let r=await br("us-east-1");t.push(...r)}return t}async function br(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 Ws(e,t,r,o){let n=e[xs(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 "${Co(o)}" setting.`),"TODO";let s=await Bs(r,n);return h("Certificate ARN: "+s),s}async function Bs(e,t){try{let r=await er("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 Gs(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 ht.CloudFrontClient({region:e}).send(new ht.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,Oo.normalizeErrorString)(n));return}}async function Hs(){let e=await Ao();for(let t of e){let r=t.StackName,o=await Io(r);o&&($o(o),console.log(""))}}async function Ks(e,t){let r=Ae(e,t);if(!r)throw ft(e,t),new Error(`Config not found: ${e}`);let o=await rr(e);if(!o)throw await or(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 Vs("@medplum/app",s)}xo(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 zs(i,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Ro(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Js(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await fetch(r)).json()}async function Vs(e,t){let r=(await Js(e,t)).dist.tarball,o=(0,q.mkdtempSync)((0,fe.join)((0,Mo.tmpdir)(),"tarball-"));try{let n=await fetch(r);if(!n.body)throw new Error("Received empty response body");let i=as(o);return await(0,Uo.pipeline)(ko.Readable.fromWeb(n.body),i),(0,fe.join)(o,"package","dist")}catch(n){throw(0,q.rmSync)(o,{recursive:!0,force:!0}),n}}function xo(e,t){for(let r of(0,q.readdirSync)(e,{withFileTypes:!0})){let o=(0,fe.join)(e,r.name);r.isDirectory()?xo(o,t):r.isFile()&&o.endsWith(".js")&&Xs(o,t)}}function Xs(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 zs(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=Do.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,q.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 tr.send(new Lo.PutObjectCommand(n))}async function Qs(e,t){if(!Ae(e,t))throw ft(e,t),new Error(`Config not found: ${e}`);let r=await rr(e);if(!r)throw await or(e),new Error(`Stack not found: ${e}`);try{await Ar("App",r.appBucket,r.appDistribution,r.appOriginAccessIdentity,t)}catch(o){console.error(`Error updating App bucket policy: ${o.message}`)}try{await Ar("Storage",r.storageBucket,r.storageDistribution,r.storageOriginAccessIdentity,t)}catch(o){console.error(`Error updating Storage bucket policy: ${o.message}`)}console.log("Done")}async function Ar(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 Zs(i),a=ta(l,i,s);a||ra(l,i,s);let f=e==="Storage"&&n.guarddutyMalwareProtection&&oa(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 ea(i,l),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Ro(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Zs(e){let t=await tr.send(new gt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function ea(e,t){await tr.send(new gt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function ta(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 ra(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}function oa(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&&Ir(m,"s3:GetObject")&&Ir(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 Ir(e,t){return e.Action===t?!0:Array.isArray(e.Action)&&e.Action.includes(t)}async function na(e,t){try{So();let r=Ae(e,t);if(!r)throw ft(e,t),new Error(`Config not found: ${e}`);let o=ns(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}}ia(r,o),aa(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 Po(r.region,`/medplum/${r.name}/`,o)}finally{bo()}}function ia(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(sa(e,t))throw new Error(r)}function sa(e,t){return e!==void 0&&t!==void 0&&e!==t}function aa(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 Bt=Nr(Ur(),1);async function la(e,t){let r=await U(t),o=Ae(e,t);if(!o)throw console.log(`Configuration file ${me(e)} not found`),ft(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),i=o.serverImage.slice(0,n),s=await ca(r,o),l=await $r(s);for(;l;){if(t.toVersion&&Bt.gt(l,t.toVersion)){console.log(`Skipping update to v${l}`);break}console.log(`Performing update to v${l}`),o.serverImage=`${i}:${l}`,ua(e,o),await r.startAsyncRequest("/admin/super/migrate"),l=await $r(l)}}async function ca(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 $r(e,t){let r=await To(e),o=r[0];return r.filter(n=>n===o||n===t||Bt.gte(n,Bt.inc(e,"minor"))).pop()}function ua(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,_o.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 pa(){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(Hs),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Us),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(vr(`Update the AWS Parameter Store config values.
|
|
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.
|
|
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]",
|
|
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:
|
|
12
12
|
|
|
13
13
|
${i.join(`
|
|
14
|
-
`)}`,{cause:n})}
|
|
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
15
|
`)),await Ce(e,Buffer.from(`Content-Type: application/dicom\r
|
|
16
16
|
`)),await Ce(e,Buffer.from(`\r
|
|
17
|
-
`)),await
|
|
17
|
+
`)),await Aa(o,e),await Ce(e,Buffer.from(`\r
|
|
18
18
|
`));await Ce(e,Buffer.from(`--${r}--\r
|
|
19
|
-
`)),e.end()}catch(o){throw e.destroy(o),o}}var Ia=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(ga)).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 Sa(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 Qo.PassThrough,u=Aa(f,s,l),g=n.post("/dicomweb/studies",f,a);await u;let c=await g;console.log("STOW-RS response received",c)}}),tn=new R("dicomweb");T(tn,Ia);var $a=Object.defineProperty,Ra=(e,t,r)=>t in e?$a(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,M=(e,t,r)=>Ra(e,typeof t!="symbol"?t+"":t,r),sn=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Ta=class extends Event{constructor(e,t){super("message"),M(this,"connection"),M(this,"message"),this.connection=e,this.message=t}},Pa=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}},Ht=class extends Event{constructor(e){super("warning"),M(this,"error"),this.error=e}},Kt=class extends Event{constructor(){super("close")}},Pr="utf-8",Oa=5e3,Na=60*1e3,an=class extends sn{constructor(e,t=Pr,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??Oa,e.on("data",n=>{if(this.closing){this.dispatchEvent(new Ht(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 Ta(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 Kt)}),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 Pa(this,i)));let s=n.message.getSegment("MSA")?.getField(2)?.toString();if(!s)return;let l=this.getPendingMessage(s);if(!l){this.dispatchEvent(new Ht(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=Gt.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=Na/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=Gt.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??Pr}getEncoding(){return this.encoding}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}getPendingMessageCount(){return this.pendingMessages.size}getPendingMessage(e){return this.pendingMessages.get(e)}setPendingMessage(e,t){this.pendingMessages.set(e,t)}deletePendingMessage(e){this.pendingMessages.delete(e)}},Ca=class extends sn{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=rn.default.connect({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.registerSocketTimeoutListener(e)),this.registerSocketConnectListener(e),this.registerSocketErrorListener(e),this.registerSocketCloseListener(e),e.promise}registerSocketTimeoutListener(e){(0,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 Kt)}),e.addEventListener("error",t=>{this.dispatchEvent(new Me(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new Ht(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 an(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 Kt);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},La=1e4,Da=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=nn.default.createServer(i=>{let s=new an(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,on.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??La)),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}},Ma=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=Ua():o.file&&(r=(0,ln.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new Ca({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await n.sendAndWait(St.Hl7Message.parse(r));console.log(i.toString().replaceAll("\r",`
|
|
20
|
-
`))}finally{await n.close()}}),
|
|
21
|
-
`)),r.send(o.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),
|
|
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|
|
|
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
|
|
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(`
|
|
25
25
|
|
|
26
|
-
`);console.log(t)}
|
|
27
|
-
`)}async function
|
|
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
28
|
`):process.stderr.write(`Error: ${(0,ve.normalizeErrorString)(e)}
|
|
29
|
-
`)}async function
|
|
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)});
|
|
30
30
|
//# sourceMappingURL=index.cjs.map
|