medplum 4.3.13 → 5.0.10

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