medplum 5.0.13 → 5.0.14

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,22 +1,22 @@
1
1
  #!/usr/bin/env node
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,EMPTY as zo,isOk as qo,isUUID as Yo}from"@medplum/core";import{Option as ft}from"commander";import{MedplumClient as Qo}from"@medplum/core";import{ClientStorage as Zo}from"@medplum/core";import{existsSync as Rt,mkdirSync as es,readFileSync as ts,writeFileSync as rs}from"node:fs";import{homedir as os}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 as}from"commander";import{Buffer as ns}from"node:buffer";import*as or from"node:util";import*as ir from"node:crypto";import*as ar from"node:util";import{KeyObject as ys}from"node:crypto";import{KeyObject as $s}from"node:crypto";import{constants as kt,KeyObject as Cs}from"node:crypto";import*as Fe from"node:crypto";import{promisify as Ds}from"node:util";import{KeyObject as Mt,createSecretKey as Dt}from"node:crypto";import{createHmac as Js,createPrivateKey as Vs,randomBytes as Xs}from"node:crypto";import{existsSync as zs,readFileSync as dr,writeFileSync as hr}from"node:fs";import{basename as mr,extname as qs,resolve as wt}from"node:path";import{isPromise as Ys}from"node:util/types";import{extract as Qs}from"tar";import{ContentType as Ne,getDisplayString as mi,MEDPLUM_CLI_CLIENT_ID as fi,normalizeErrorString as gi}from"@medplum/core";import{exec as wi}from"node:child_process";import{createServer as yi}from"node:http";import{platform as Ei}from"node:os";import{CloudFormationClient as Lr,DescribeStackResourcesCommand as Li,DescribeStacksCommand as Ci,paginateListStacks as ki}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as Mi,CreateInvalidationCommand as Di}from"@aws-sdk/client-cloudfront";import{ECSClient as _i}from"@aws-sdk/client-ecs";import{S3Client as Ui}from"@aws-sdk/client-s3";import{GetParameterCommand as xi,PutParameterCommand as ji,SSMClient as Fi}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as Wi,STSClient as Hi}from"@aws-sdk/client-sts";import{EMPTY as Bi,normalizeErrorString as Ki}from"@medplum/core";import Gi from"node-fetch";import{readdirSync as Ji}from"node:fs";import Vi from"node:readline";import{ACMClient as Fr,ListCertificatesCommand as ta,RequestCertificateCommand as ra}from"@aws-sdk/client-acm";import{CloudFrontClient as oa,CreatePublicKeyCommand as sa}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as ia,STSClient as aa}from"@aws-sdk/client-sts";import{normalizeErrorString as na}from"@medplum/core";import{generateKeyPairSync as ca,randomUUID as jt}from"node:crypto";import{existsSync as la}from"node:fs";import{PutObjectCommand as ya}from"@aws-sdk/client-s3";import{ContentType as Y}from"@medplum/core";import Ea from"fast-glob";import Hr from"node-fetch";import{createReadStream as va,mkdtempSync as Sa,readdirSync as ba,readFileSync as Ia,rmSync as Aa,writeFileSync as $a}from"node:fs";import{tmpdir as Ra}from"node:os";import{join as Me,sep as Ta}from"node:path";import{pipeline as Pa}from"node:stream/promises";import{GetBucketPolicyCommand as _a,PutBucketPolicyCommand as Ua}from"@aws-sdk/client-s3";import{spawnSync as Va}from"node:child_process";import{EMPTY as Qa}from"@medplum/core";import{createReadStream as Za,writeFile as en}from"node:fs";import{resolve as qr}from"node:path";import{createInterface as tn}from"node:readline";import{formatHl7DateTime as nn,Hl7Message as cn}from"@medplum/core";import Le from"node:assert";import{connect as ln}from"node:net";import{Hl7Message as un,OperationOutcomeError as Ee,ReturnAckCategory as Kt,sleep as pn,validationError as dn}from"@medplum/core";import Gt from"iconv-lite";import"@medplum/core";import{sleep as hn}from"@medplum/core";import mn from"node:net";import{readFileSync as In}from"node:fs";import{readdirSync as Tn}from"node:fs";import{homedir as Pn}from"node:os";import{resolve as Nn}from"node:path";import{Option as On}from"commander";import{convertToTransactionBundle as Mn}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),De=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}=De(),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}=De(),{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}),Mo=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}),Do=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(D=>W(D,this.options)).join(" ").split(/\s+/).map(D=>Ve(D,this.options));b&&(I=I.filter(D=>(n("loose invalid filter",D,this.options),!!D.match(l[u.COMPARATORLOOSE])))),n("range list",I);let C=new Map,L=I.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 M=[...C.values()];return i.set(S,M),M}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=Do(),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}=De(),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 M;return _(v)?M="":_(I)?M=`>=${v}.0.0${E} <${+v+1}.0.0-0`:_(C)?v==="0"?M=`>=${v}.${I}.0${E} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.0${E} <${+v+1}.0.0-0`:L?(n("replaceCaret pr",L),v==="0"?I==="0"?M=`>=${v}.${I}.${C}-${L} <${v}.${I}.${+C+1}-0`:M=`>=${v}.${I}.${C}-${L} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.${C}-${L} <${+v+1}.0.0-0`):(n("no pr"),v==="0"?I==="0"?M=`>=${v}.${I}.${C}${E} <${v}.${I}.${+C+1}-0`:M=`>=${v}.${I}.${C}${E} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.${C} <${+v+1}.0.0-0`),n("caret return",M),M})},$=(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 M=_(v),D=M||_(I),se=D||_(C),fe=se;return b==="="&&fe&&(b=""),L=w.includePrerelease?"-0":"",M?b===">"||b==="<"?E="<0.0.0-0":E="*":b&&fe?(D&&(I=0),C=0,b===">"?(b=">=",D?(v=+v+1,I=0,C=0):(I=+I+1,C=0)):b==="<="&&(b="<",D?v=+v+1:I=+I+1),b==="<"&&(L="-0"),E=`${b+v}.${I}.${C}${L}`):D?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,M,D,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":""}`,_(M)?L="":_(D)?L=`<${+M+1}.0.0-0`:_(se)?L=`<${M}.${+D+1}.0-0`:fe?L=`<=${M}.${D}.${se}-${fe}`:y?L=`<${M}.${D}.${+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=De(),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=Mo(),Ve=xe(),Xe=z(),ze=je(),y=_o(),w=Uo(),S=xo(),E=jo(),b=Fo(),v=mt(),I=Wo(),C=Ho(),L=Bo(),M=Ko(),D=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:M,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}}),Ie=class extends Zo{constructor(e){super(),B(this,"dirName"),B(this,"fileName"),this.dirName=Tt(os(),".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(ts(this.fileName,"utf8"))}writeFile(e){Rt(this.dirName)||es(this.dirName),rs(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}=ss(e,o),d=e.fetch??fetch,m=new Qo({fetch:d,baseUrl:i,tokenUrl:n,fhirUrlPath:a,authorizeUrl:f,storage:o,onUnauthenticated:is,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 ss(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 is(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var ve=new TextEncoder,Nt=new TextDecoder,Yn=2**32;function cs(...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=>ns.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,ls=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(ls,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var sr=e=>or.types.isKeyObject(e),us=ir.webcrypto,ps=us,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 ds(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function hs(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 ms(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=ds(t);if(e.algorithm.namedCurve!==o)throw q(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}hs(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||ps?.CryptoKey)&&ce.push("CryptoKey");var fs=(...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},gs=fs;function ws(e){return typeof e=="object"&&e!==null}function ur(e){if(!ws(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 Es(e){return e.kty!=="oct"&&typeof e.d=="string"}function vs(e){return e.kty!=="oct"&&typeof e.d>"u"}function Ss(e){return $e(e)&&e.kty==="oct"&&typeof e.k=="string"}var bs=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(gt(e))r=ys.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:bs(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},As=Is,Ct=(e,t)=>{let r;try{e instanceof $s?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},Rs=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&$e(t)){if(Ss(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"`)}},Ts=(e,t,r,o)=>{if(o&&$e(t))switch(r){case"sign":if(Es(t)&&st(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(vs(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)?Rs(t,r,o,e):Ts(t,r,o,e)}var ec=pr.bind(void 0,!1),Ps=pr.bind(void 0,!0);function Ns(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 Os=Ns;function Ls(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 ks=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Ms(e,t){let r,o,s;if(t instanceof Cs)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=As(t),c=ks.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 _s(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 Mt)return t;if(gt(t))return ms(t,e,r),Mt.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 xs=Ds(Fe.sign),js=async(e,t,r)=>{let o=Us(e,t,"sign");if(e.startsWith("HS")){let s=Fe.createHmac(_s(e),o);return s.update(r),s.digest()}return xs(Ls(e),r,Ms(e,o))},Fs=js,ee=e=>Math.floor(e.getTime()/1e3),Ws=/^(\+|\-)? ?(\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=Ws.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},Hs=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(!gs(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=Os(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');Ps(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=cs(c,ve.encode("."),a),f=await Fs(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}},Bs=class{constructor(e){B(this,"_flattened"),this._flattened=new Hs(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 Ks=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}},Gs=class extends Ks{constructor(){super(...arguments),B(this,"_protectedHeader")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let r=new Bs(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:si(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&&ti(l)}function Zs(e){let t=new RegExp("^"+ri(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 ei(e){let t=We(oe(e,{server:!0}));if(t)return JSON.parse(t)}function We(e){let t=wt(e);return zs(t)?dr(t,"utf8"):""}function ti(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 ri(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function oi(e){let t=0,r=0;return Qs({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 si(e){let t=qs(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 ii(e){return new Ie(e).getObject("options")}async function ai(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=Js("sha256",t.clientSecret).update(c).digest("base64url"),f=`${c}.${n}`;await e.startJwtBearerLogin(t.clientId,f,t.scope??"")}async function ni(e,t){let r=Vs(dr(wt(t.privateKeyPath))),o=await new Gs({}).setProtectedHeader({typ:"JWT",alg:tr.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Xs(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 as{action(e){let t=ci(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 ci(e,t){return async r=>{let o=e.registeredArguments.length,s=r.slice(0,o);s[o]=e.optsWithGlobals();try{let i=t(...s);Ys(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=pi(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=hi(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=li(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 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(`
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,EMPTY as zo,isOk as qo,isUUID as Yo}from"@medplum/core";import{Option as ft}from"commander";import{MedplumClient as Qo}from"@medplum/core";import{ClientStorage as Zo}from"@medplum/core";import{existsSync as Rt,mkdirSync as es,readFileSync as ts,writeFileSync as rs}from"node:fs";import{homedir as os}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 as}from"commander";import{Buffer as ns}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 $s}from"node:crypto";import{constants as kt,KeyObject as Cs}from"node:crypto";import*as Fe from"node:crypto";import{promisify as Ds}from"node:util";import{KeyObject as Mt,createSecretKey as Dt}from"node:crypto";import{createHmac as Js,createPrivateKey as Vs,randomBytes as Xs}from"node:crypto";import{existsSync as zs,readFileSync as dr,writeFileSync as hr}from"node:fs";import{basename as mr,extname as qs,resolve as yt}from"node:path";import{isPromise as Ys}from"node:util/types";import{extract as Qs}from"tar";import{ContentType as Ne,getDisplayString as mi,MEDPLUM_CLI_CLIENT_ID as fi,normalizeErrorString as gi}from"@medplum/core";import{exec as yi}from"node:child_process";import{createServer as wi}from"node:http";import{platform as Ei}from"node:os";import{CloudFormationClient as Lr,DescribeStackResourcesCommand as Li,DescribeStacksCommand as Ci,paginateListStacks as ki}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as Mi,CreateInvalidationCommand as Di}from"@aws-sdk/client-cloudfront";import{ECSClient as _i}from"@aws-sdk/client-ecs";import{S3Client as Ui}from"@aws-sdk/client-s3";import{GetParameterCommand as xi,PutParameterCommand as ji,SSMClient as Fi}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as Wi,STSClient as Hi}from"@aws-sdk/client-sts";import{EMPTY as Bi,normalizeErrorString as Ki}from"@medplum/core";import Gi from"node-fetch";import{readdirSync as Ji}from"node:fs";import Vi from"node:readline";import{ACMClient as Fr,ListCertificatesCommand as ta,RequestCertificateCommand as ra}from"@aws-sdk/client-acm";import{CloudFrontClient as oa,CreatePublicKeyCommand as sa}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as ia,STSClient as aa}from"@aws-sdk/client-sts";import{normalizeErrorString as na}from"@medplum/core";import{generateKeyPairSync as ca,randomUUID as jt}from"node:crypto";import{existsSync as la}from"node:fs";import{PutObjectCommand as wa}from"@aws-sdk/client-s3";import{ContentType as Y}from"@medplum/core";import Ea from"fast-glob";import Hr from"node-fetch";import{createReadStream as va,mkdtempSync as Sa,readdirSync as ba,readFileSync as Ia,rmSync as Aa,writeFileSync as $a}from"node:fs";import{tmpdir as Ra}from"node:os";import{join as Me,sep as Ta}from"node:path";import{pipeline as Pa}from"node:stream/promises";import{GetBucketPolicyCommand as _a,PutBucketPolicyCommand as Ua}from"@aws-sdk/client-s3";import{spawnSync as Va}from"node:child_process";import{EMPTY as Qa}from"@medplum/core";import{createReadStream as Za,writeFile as en}from"node:fs";import{resolve as qr}from"node:path";import{createInterface as tn}from"node:readline";import{formatHl7DateTime as nn,Hl7Message as cn}from"@medplum/core";import Le from"node:assert";import{connect as ln}from"node:net";import{Hl7Message as un,OperationOutcomeError as Ee,ReturnAckCategory as Kt,sleep as pn,validationError as dn}from"@medplum/core";import Gt from"iconv-lite";import"@medplum/core";import{sleep as hn}from"@medplum/core";import mn from"node:net";import{readFileSync as In}from"node:fs";import{readdirSync as Tn}from"node:fs";import{homedir as Pn}from"node:os";import{resolve as Nn}from"node:path";import{Option as On}from"commander";import{convertToTransactionBundle as Mn}from"@medplum/core";var fo=Object.create,ct=Object.defineProperty,go=Object.getOwnPropertyDescriptor,yo=Object.getOwnPropertyNames,wo=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 yo(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(wo(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),De=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}=De(),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}=De(),{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}),Mo=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}),Do=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(y,S){if(S=a(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(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 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 b=this.options.loose,v=b?l[u.HYPHENRANGELOOSE]:l[u.HYPHENRANGE];y=y.replace(v,Xe(this.options.includePrerelease)),n("hyphen replace",y),y=y.replace(l[u.COMPARATORTRIM],d),n("comparator trim",y),y=y.replace(l[u.TILDETRIM],m),n("tilde trim",y),y=y.replace(l[u.CARETTRIM],g),n("caret trim",y);let I=y.split(" ").map(D=>W(D,this.options)).join(" ").split(/\s+/).map(D=>Ve(D,this.options));b&&(I=I.filter(D=>(n("loose invalid filter",D,this.options),!!D.match(l[u.COMPARATORLOOSE])))),n("range list",I);let C=new Map,L=I.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 M=[...C.values()];return i.set(S,M),M}intersects(y,S){if(!(y instanceof Ce))throw new TypeError("a Range is required");return this.set.some(E=>j(E,S)&&y.set.some(b=>j(b,S)&&E.every(v=>b.every(I=>v.intersects(I,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(ze(this.set[S],y,this.options))return!0;return!1}};t.exports=o;var s=Do(),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}=De(),T=w=>w.value==="<0.0.0-0",O=w=>w.value==="",j=(w,y)=>{let S=!0,E=w.slice(),b=E.pop();for(;S&&E.length;)S=E.every(v=>b.intersects(v,y)),b=E.pop();return S},W=(w,y)=>(w=w.replace(l[u.BUILD],""),n("comp",w,y),w=U(w,y),n("caret",w),w=Z(w,y),n("tildes",w),w=$(w,y),n("xrange",w),w=Je(w,y),n("stars",w),w),_=w=>!w||w.toLowerCase()==="x"||w==="*",Z=(w,y)=>w.trim().split(/\s+/).map(S=>J(S,y)).join(" "),J=(w,y)=>{let S=y.loose?l[u.TILDELOOSE]:l[u.TILDE];return w.replace(S,(E,b,v,I,C)=>{n("tilde",w,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=(w,y)=>w.trim().split(/\s+/).map(S=>H(S,y)).join(" "),H=(w,y)=>{n("caret",w,y);let S=y.loose?l[u.CARETLOOSE]:l[u.CARET],E=y.includePrerelease?"-0":"";return w.replace(S,(b,v,I,C,L)=>{n("caret",w,b,v,I,C,L);let M;return _(v)?M="":_(I)?M=`>=${v}.0.0${E} <${+v+1}.0.0-0`:_(C)?v==="0"?M=`>=${v}.${I}.0${E} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.0${E} <${+v+1}.0.0-0`:L?(n("replaceCaret pr",L),v==="0"?I==="0"?M=`>=${v}.${I}.${C}-${L} <${v}.${I}.${+C+1}-0`:M=`>=${v}.${I}.${C}-${L} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.${C}-${L} <${+v+1}.0.0-0`):(n("no pr"),v==="0"?I==="0"?M=`>=${v}.${I}.${C}${E} <${v}.${I}.${+C+1}-0`:M=`>=${v}.${I}.${C}${E} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.${C} <${+v+1}.0.0-0`),n("caret return",M),M})},$=(w,y)=>(n("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,b,v,I,C,L)=>{n("xRange",w,E,b,v,I,C,L);let M=_(v),D=M||_(I),se=D||_(C),fe=se;return b==="="&&fe&&(b=""),L=y.includePrerelease?"-0":"",M?b===">"||b==="<"?E="<0.0.0-0":E="*":b&&fe?(D&&(I=0),C=0,b===">"?(b=">=",D?(v=+v+1,I=0,C=0):(I=+I+1,C=0)):b==="<="&&(b="<",D?v=+v+1:I=+I+1),b==="<"&&(L="-0"),E=`${b+v}.${I}.${C}${L}`):D?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=(w,y)=>(n("replaceStars",w,y),w.trim().replace(l[u.STAR],"")),Ve=(w,y)=>(n("replaceGTE0",w,y),w.trim().replace(l[y.includePrerelease?u.GTE0PRE:u.GTE0],"")),Xe=w=>(y,S,E,b,v,I,C,L,M,D,se,fe)=>(_(E)?S="":_(b)?S=`>=${E}.0.0${w?"-0":""}`:_(v)?S=`>=${E}.${b}.0${w?"-0":""}`:I?S=`>=${S}`:S=`>=${S}${w?"-0":""}`,_(M)?L="":_(D)?L=`<${+M+1}.0.0-0`:_(se)?L=`<${M}.${+D+1}.0-0`:fe?L=`<=${M}.${D}.${se}-${fe}`:w?L=`<${M}.${D}.${+se+1}-0`:L=`<=${L}`,`${S} ${L}`.trim()),ze=(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(n(w[E].semver),w[E].semver!==c.ANY&&w[E].semver.prerelease.length>0){let b=w[E].semver;if(b.major===y.major&&b.minor===y.minor&&b.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(" "),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=De(),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=Mo(),Ve=xe(),Xe=z(),ze=je(),w=_o(),y=Uo(),S=xo(),E=jo(),b=Fo(),v=mt(),I=Wo(),C=Ho(),L=Bo(),M=Ko(),D=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:w,maxSatisfying:y,minSatisfying:S,minVersion:E,validRange:b,outside:v,gtr:I,ltr:C,intersects:L,simplifyRange:M,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}}),Ie=class extends Zo{constructor(e){super(),B(this,"dirName"),B(this,"fileName"),this.dirName=Tt(os(),".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(ts(this.fileName,"utf8"))}writeFile(e){Rt(this.dirName)||es(this.dirName),rs(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}=ss(e,o),d=e.fetch??fetch,m=new Qo({fetch:d,baseUrl:i,tokenUrl:n,fhirUrlPath:a,authorizeUrl:f,storage:o,onUnauthenticated:is,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 ss(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 is(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var ve=new TextEncoder,Nt=new TextDecoder,Yn=2**32;function cs(...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=>ns.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,ls=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(ls,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var sr=e=>or.types.isKeyObject(e),us=ir.webcrypto,ps=us,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 ds(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function hs(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 ms(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=ds(t);if(e.algorithm.namedCurve!==o)throw q(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}hs(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||ps?.CryptoKey)&&ce.push("CryptoKey");var fs=(...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},gs=fs;function ys(e){return typeof e=="object"&&e!==null}function ur(e){if(!ys(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 Es(e){return e.kty!=="oct"&&typeof e.d=="string"}function vs(e){return e.kty!=="oct"&&typeof e.d>"u"}function Ss(e){return $e(e)&&e.kty==="oct"&&typeof e.k=="string"}var bs=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(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:bs(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},As=Is,Ct=(e,t)=>{let r;try{e instanceof $s?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},Rs=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&$e(t)){if(Ss(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"`)}},Ts=(e,t,r,o)=>{if(o&&$e(t))switch(r){case"sign":if(Es(t)&&st(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(vs(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)?Rs(t,r,o,e):Ts(t,r,o,e)}var ec=pr.bind(void 0,!1),Ps=pr.bind(void 0,!0);function Ns(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 Os=Ns;function Ls(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 ks=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Ms(e,t){let r,o,s;if(t instanceof Cs)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=As(t),c=ks.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 _s(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 Mt)return t;if(gt(t))return ms(t,e,r),Mt.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 xs=Ds(Fe.sign),js=async(e,t,r)=>{let o=Us(e,t,"sign");if(e.startsWith("HS")){let s=Fe.createHmac(_s(e),o);return s.update(r),s.digest()}return xs(Ls(e),r,Ms(e,o))},Fs=js,ee=e=>Math.floor(e.getTime()/1e3),Ws=/^(\+|\-)? ?(\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=Ws.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},Hs=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(!gs(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=Os(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');Ps(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=cs(c,ve.encode("."),a),f=await Fs(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}},Bs=class{constructor(e){B(this,"_flattened"),this._flattened=new Hs(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 Ks=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}},Gs=class extends Ks{constructor(){super(...arguments),B(this,"_protectedHeader")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let r=new Bs(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:si(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 yr(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&&ti(l)}function Zs(e){let t=new RegExp("^"+ri(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(yt(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 ei(e){let t=We(oe(e,{server:!0}));if(t)return JSON.parse(t)}function We(e){let t=yt(e);return zs(t)?dr(t,"utf8"):""}function ti(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 ri(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function oi(e){let t=0,r=0;return Qs({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 si(e){let t=qs(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?qe.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?qe.TYPESCRIPT:qe.TEXT}function wr(e,t){let r=new Ie(e),o={name:e,...t};return r.setObject("options",o),o}function ii(e){return new Ie(e).getObject("options")}async function ai(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=Js("sha256",t.clientSecret).update(c).digest("base64url"),f=`${c}.${n}`;await e.startJwtBearerLogin(t.clientId,f,t.scope??"")}async function ni(e,t){let r=Vs(dr(yt(t.privateKeyPath))),o=await new Gs({}).setProtectedHeader({typ:"JWT",alg:tr.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Xs(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 as{action(e){let t=ci(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 ci(e,t){return async r=>{let o=e.registeredArguments.length,s=r.slice(0,o);s[o]=e.optsWithGlobals();try{let i=t(...s);Ys(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 wt({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=pi(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 wt({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 wt({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});async function wt({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:s}){let i=hi(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=li(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 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 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 li(e){let t=[];for(let r of e.entry??zo){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(ui(r.resource))}return t}function ui(e){let t=e.parameter?.find(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 pi(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=di(i,a);r[i]=c}return r}function di(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 hi(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(!Yo(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=fi,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 vi(o,r)});Nr.action(async e=>{let t=await x(e);Ii(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 vi(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Ai(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 ai(e,t);break;case"jwt-assertion":await ni(e,t);break}}async function Si(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 a=await e.processCode(i,{clientId:Rr,redirectUri:Tr});o.writeHead(200,{"Content-Type":Ne.TEXT}),o.end(`Signed in as ${mi(a)}. You may close this window.`)}catch(a){o.writeHead(400,{"Content-Type":Ne.TEXT}),o.end(`Error: ${gi(a)}`)}finally{t.close(),process.exit(0)}else o.writeHead(404,{"Content-Type":Ne.TEXT}),o.end("Not found")}).listen(9615)}async function bi(e){let t=Ei(),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)=>{wi(r,(i,a,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 Ai(e){await Si(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 bi(t.toString())}var we="\x1B[0m",$i="\x1B[1m",Ri="\x1B[31m",Ti="\x1B[32m",Pi="\x1B[33m",Ni="\x1B[34m",Se={red:e=>`${Ri}${e}${we}`,green:e=>`${Ti}${e}${we}`,yellow:e=>`${Pi}${e}${we}`,blue:e=>`${Ni}${e}${we}`,bold:e=>`${$i}${e}${we}`},Ut=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>Se.bold(r)),Oi=Vt(Qt(),1),He;function Cr(){He=Vi.createInterface({input:process.stdin,output:process.stdout})}function kr(){He.close()}function p(e){He.write(e+`
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 li(e){let t=[];for(let r of e.entry??zo){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(ui(r.resource))}return t}function ui(e){let t=e.parameter?.find(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 pi(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=di(i,a);r[i]=c}return r}function di(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 hi(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(!Yo(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=fi,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=wr(t,e),o=await x(e,!1);await vi(o,r)});Nr.action(async e=>{let t=await x(e);Ii(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 vi(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Ai(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 ai(e,t);break;case"jwt-assertion":await ni(e,t);break}}async function Si(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 ${mi(a)}. You may close this window.`)}catch(a){o.writeHead(400,{"Content-Type":Ne.TEXT}),o.end(`Error: ${gi(a)}`)}finally{t.close(),process.exit(0)}else o.writeHead(404,{"Content-Type":Ne.TEXT}),o.end("Not found")}).listen(9615)}async function bi(e){let t=Ei(),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)=>{yi(r,(i,a,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 Ai(e){await Si(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 bi(t.toString())}var ye="\x1B[0m",$i="\x1B[1m",Ri="\x1B[31m",Ti="\x1B[32m",Pi="\x1B[33m",Ni="\x1B[34m",Se={red:e=>`${Ri}${e}${ye}`,green:e=>`${Ti}${e}${ye}`,yellow:e=>`${Pi}${e}${ye}`,blue:e=>`${Ni}${e}${ye}`,bold:e=>`${$i}${e}${ye}`},Ut=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>Se.bold(r)),Oi=Vt(Qt(),1),He;function Cr(){He=Vi.createInterface({input:process.stdin,output:process.stdout})}function kr(){He.close()}function p(e){He.write(e+`
5
5
  `)}function F(e){p(`
6
6
  `+e+`
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({}),Xi=new Mi({region:"us-east-1"}),Ic=new _i({}),vt=new Ui({}),zi="medplum:environment";async function Mr(){let e=[],t=ki({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)for(let o of r.StackSummaries??Bi)e.push(o);return e}async function St(e){let t=await Mr();for(let r of t){let o=r.StackName,s=await Dr(o);if(s?.tag===e)return s}}async function Dr(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 Ci({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(c=>c.Key===zi);if(!i)return;let a=await e.send(new Li({StackName:t}));if(a.StackResources){e===ke&&(r.stack=s,r.tag=i.Value);for(let c of a.StackResources)qi(c,r)}}function qi(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: ${Yi(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 Yi(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Ur(e){let t=await Xi.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 Gi("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)=>Oi.compare(o,r)),e?t.slice(0,t.indexOf(e)):t}async function jr(e,t,r){let o=new Fi({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 Zi(o,a,c)}}async function Qi(e,t){let r=new xi({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Zi(e,t,r){let o=new ji({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=Ji(".",{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 Hi,r=new Wi({}),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",Ki(t))}}async function ea(e){let t=await St(e);if(!t)throw await bt(e),new Error(`Stack not found: ${e}`);_r(t)}var ua=e=>`${e}DomainName`,Wr=e=>`${e}SslCertArn`;async function pa(){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 da(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`);la(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 ga(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 ha(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 ma(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 da(e){try{let t=new aa({region:e}),r=new ia({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function ha(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 ta({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function ma(e,t,r,o){let s=e[ua(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 fa(r,s);return p("Certificate ARN: "+a),a}async function fa(e,t){try{let r=await Et("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new Fr({region:e}),s=new ra({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 ga(e,t){let r=jt(),o=ca("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new oa({region:e}).send(new sa({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: ",na(s));return}}async function wa(){let e=await Mr();for(let t of e){let r=t.StackName,o=await Dr(r);o&&(_r(o),console.log(""))}}async function Na(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 La("@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 ka(i,s.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Ur(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Oa(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Hr(r)).json()}async function La(e,t){let r=(await Oa(e,t)).dist.tarball,o=Sa(Me(Ra(),"tarball-"));try{let s=await Hr(r),i=oi(o);return await Pa(s.body,i),Me(o,"package","dist")}catch(s){throw Aa(o,{recursive:!0,force:!0}),s}}function Br(e,t){for(let r of ba(e,{withFileTypes:!0})){let o=Me(e,r.name);r.isDirectory()?Br(o,t):r.isFile()&&o.endsWith(".js")&&Ca(o,t)}}function Ca(e,t){let r=Ia(e,"utf-8");for(let[o,s]of Object.entries(t))r=r.replaceAll(`__${o}__`,s);$a(e,r)}async function ka(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 Ma({rootDir:e,bucketName:t,fileNamePattern:s[0],contentType:s[1],cached:s[2],dryrun:r.dryrun})}async function Ma(e){let t=Ea.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Da(Me(e.rootDir,r),e)}async function Da(e,t){let r=va(e),o=e.substring(t.rootDir.length+1).split(Ta).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 ya(s))}async function xa(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 ja(i);if(Wa(c,i,a))throw new Error(`${e} bucket already has policy statement`);Ha(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 Fa(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 ja(e){let t=await vt.send(new _a({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Fa(e,t){await vt.send(new Ua({Bucket:e,Policy:JSON.stringify(t)}))}function Wa(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 Ha(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 Ba(e,t){try{Cr();let r=de(e,t);if(!r)throw Be(e,t),new Error(`Config not found: ${e}`);let o=ei(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}}Ka(r,o),Ja(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 Ka(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(Ga(e,t))throw new Error(r)}function Ga(e,t){return e!==void 0&&t!==void 0&&e!==t}function Ja(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 Xa(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 za(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}`,qa(e,o),await r.startAsyncRequest("/admin/super/migrate"),c=await Ht(c)}}async function za(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 qa(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=Va(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 Ya(){let e=new R("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(pa),e.command("list").description("List Medplum AWS CloudFormation stacks").action(wa),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(ea),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 we(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({}),Xi=new Mi({region:"us-east-1"}),Ic=new _i({}),vt=new Ui({}),zi="medplum:environment";async function Mr(){let e=[],t=ki({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)for(let o of r.StackSummaries??Bi)e.push(o);return e}async function St(e){let t=await Mr();for(let r of t){let o=r.StackName,s=await Dr(o);if(s?.tag===e)return s}}async function Dr(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 Ci({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(c=>c.Key===zi);if(!i)return;let a=await e.send(new Li({StackName:t}));if(a.StackResources){e===ke&&(r.stack=s,r.tag=i.Value);for(let c of a.StackResources)qi(c,r)}}function qi(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: ${Yi(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 Yi(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Ur(e){let t=await Xi.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 Gi("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)=>Oi.compare(o,r)),e?t.slice(0,t.indexOf(e)):t}async function jr(e,t,r){let o=new Fi({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 Zi(o,a,c)}}async function Qi(e,t){let r=new xi({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Zi(e,t,r){let o=new ji({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=Ji(".",{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 Hi,r=new Wi({}),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",Ki(t))}}async function ea(e){let t=await St(e);if(!t)throw await bt(e),new Error(`Stack not found: ${e}`);_r(t)}var ua=e=>`${e}DomainName`,Wr=e=>`${e}SslCertArn`;async function pa(){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 da(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`);la(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 we("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 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"),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 we("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 we("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 we("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 ga(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 ha(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 ma(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 da(e){try{let t=new aa({region:e}),r=new ia({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function ha(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 ta({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function ma(e,t,r,o){let s=e[ua(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 fa(r,s);return p("Certificate ARN: "+a),a}async function fa(e,t){try{let r=await Et("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new Fr({region:e}),s=new ra({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 ga(e,t){let r=jt(),o=ca("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new oa({region:e}).send(new sa({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: ",na(s));return}}async function ya(){let e=await Mr();for(let t of e){let r=t.StackName,o=await Dr(r);o&&(_r(o),console.log(""))}}async function Na(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 La("@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 ka(i,s.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Ur(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Oa(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Hr(r)).json()}async function La(e,t){let r=(await Oa(e,t)).dist.tarball,o=Sa(Me(Ra(),"tarball-"));try{let s=await Hr(r),i=oi(o);return await Pa(s.body,i),Me(o,"package","dist")}catch(s){throw Aa(o,{recursive:!0,force:!0}),s}}function Br(e,t){for(let r of ba(e,{withFileTypes:!0})){let o=Me(e,r.name);r.isDirectory()?Br(o,t):r.isFile()&&o.endsWith(".js")&&Ca(o,t)}}function Ca(e,t){let r=Ia(e,"utf-8");for(let[o,s]of Object.entries(t))r=r.replaceAll(`__${o}__`,s);$a(e,r)}async function ka(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 Ma({rootDir:e,bucketName:t,fileNamePattern:s[0],contentType:s[1],cached:s[2],dryrun:r.dryrun})}async function Ma(e){let t=Ea.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Da(Me(e.rootDir,r),e)}async function Da(e,t){let r=va(e),o=e.substring(t.rootDir.length+1).split(Ta).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 wa(s))}async function xa(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 ja(i);if(Wa(c,i,a))throw new Error(`${e} bucket already has policy statement`);Ha(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 Fa(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 ja(e){let t=await vt.send(new _a({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Fa(e,t){await vt.send(new Ua({Bucket:e,Policy:JSON.stringify(t)}))}function Wa(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 Ha(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 Ba(e,t){try{Cr();let r=de(e,t);if(!r)throw Be(e,t),new Error(`Config not found: ${e}`);let o=ei(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}}Ka(r,o),Ja(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 Ka(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(Ga(e,t))throw new Error(r)}function Ga(e,t){return e!==void 0&&t!==void 0&&e!==t}function Ja(e,t){e.apiPort&&(t.port=e.apiPort),e.baseUrl&&(t.baseUrl=e.baseUrl),e.appDomainName&&(t.appBaseUrl=`https://${e.appDomainName}/`),e.storageDomainName&&(t.storageBaseUrl=`https://${e.storageDomainName}/binary/`)}var at=Vt(Qt(),1);async function Xa(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 za(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}`,qa(e,o),await r.startAsyncRequest("/admin/super/migrate"),c=await Ht(c)}}async function za(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 qa(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=Va(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 Ya(){let e=new R("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(pa),e.command("list").description("List Medplum AWS CloudFormation stacks").action(ya),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(ea),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(Ba),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(Xa)),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(Na),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(xa),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=Zs(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:
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(Ba),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(Xa)),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(Na),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(xa),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 yr(i,e,t,r,o,s.runtimeVersion,!!s.writeConfig)});async function Ge(e,t,r=!1){let o=Zs(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})}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);en(`${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 rn(i,Number.parseInt(r,10),a,o)});async function rn(e,t,r,o){let s=[],i=Za(e),a=tn({input:i});for await(let c of a){let n=on(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){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let o of r.entry??Qa)re(o.response)}function on(e,t){let r=JSON.parse(e);return t?sn(r):r}function sn(e){return e.resourceType==="ExplanationOfBenefit"?an(e):e}function an(e){return e.provider||(e.provider=_t()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=_t())}),e}var fn=Object.defineProperty,gn=(e,t,r)=>t in e?fn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,k=(e,t,r)=>gn(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)}},wn=class extends Event{constructor(e,t){super("message"),k(this,"connection"),k(this,"message"),this.connection=e,this.message=t}},yn=class extends Event{constructor(e,t){super("enhancedAckSent"),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")}},Jt="utf-8",En=60*1e3,eo=class extends Zr{constructor(e,t=Jt,r,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 wn(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=>{let i;this.enhancedMode==="standard"?i=s.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(i=s.message.buildAck({ackCode:"AA"})),i&&(this.send(i),this.dispatchEvent(new yn(this,i)));let a=s.message.getSegment("MSA")?.getField(2)?.toString();if(!a)return;let c=this.pendingMessages.get(a);if(!c){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 '${a}' but there was no pending message with this control ID`}]})));return}let n=s.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();n&&(c.returnAck===Kt.APPLICATION&&n==="CA"||(c.resolve(s.message),this.pendingMessages.delete(a)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Gt.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=En/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await pn(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=Gt.decode(s,this.encoding),a=un.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(dn("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.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}},vn=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=ln({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)}},Sn=1e4,bn=class{constructor(e){k(this,"handler"),k(this,"server"),k(this,"encoding"),k(this,"enhancedMode"),k(this,"messagesPerMin"),k(this,"connections",new Set),this.handler=e}async start(e,t,r,o){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),o?.messagesPerMin!==void 0&&this.setMessagesPerMin(o.messagesPerMin);let s=mn.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 hn(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??Sn)),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}},An=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=Rn():o.file&&(r=In(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let s=new vn({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await s.sendAndWait(cn.parse(r));console.log(i.toString().replaceAll("\r",`
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 yr(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);en(`${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 rn(i,Number.parseInt(r,10),a,o)});async function rn(e,t,r,o){let s=[],i=Za(e),a=tn({input:i});for await(let c of a){let n=on(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){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let o of r.entry??Qa)re(o.response)}function on(e,t){let r=JSON.parse(e);return t?sn(r):r}function sn(e){return e.resourceType==="ExplanationOfBenefit"?an(e):e}function an(e){return e.provider||(e.provider=_t()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=_t())}),e}var fn=Object.defineProperty,gn=(e,t,r)=>t in e?fn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,k=(e,t,r)=>gn(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)}},yn=class extends Event{constructor(e,t){super("message"),k(this,"connection"),k(this,"message"),this.connection=e,this.message=t}},wn=class extends Event{constructor(e,t){super("enhancedAckSent"),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")}},Jt="utf-8",En=60*1e3,eo=class extends Zr{constructor(e,t=Jt,r,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 yn(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=>{let i;this.enhancedMode==="standard"?i=s.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(i=s.message.buildAck({ackCode:"AA"})),i&&(this.send(i),this.dispatchEvent(new wn(this,i)));let a=s.message.getSegment("MSA")?.getField(2)?.toString();if(!a)return;let c=this.pendingMessages.get(a);if(!c){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 '${a}' but there was no pending message with this control ID`}]})));return}let n=s.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();n&&(c.returnAck===Kt.APPLICATION&&n==="CA"||(c.resolve(s.message),this.pendingMessages.delete(a)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Gt.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=En/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await pn(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=Gt.decode(s,this.encoding),a=un.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(dn("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.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}},vn=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=ln({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)}},Sn=1e4,bn=class{constructor(e){k(this,"handler"),k(this,"server"),k(this,"encoding"),k(this,"enhancedMode"),k(this,"messagesPerMin"),k(this,"connections",new Set),this.handler=e}async start(e,t,r,o){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),o?.messagesPerMin!==void 0&&this.setMessagesPerMin(o.messagesPerMin);let s=mn.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 hn(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??Sn)),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}},An=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=Rn():o.file&&(r=In(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let s=new vn({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await s.sendAndWait(cn.parse(r));console.log(i.toString().replaceAll("\r",`
15
15
  `))}finally{await s.close()}}),$n=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 bn(r=>{r.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
16
16
  `)),r.send(o.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),At=new R("hl7");P(At,An);P(At,$n);function Rn(){let e=nn(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 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=Nn(Pn(),".medplum"),t=Tn(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=ii(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);Ln(t)});function Ln(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)=>{wr(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=Nn(Pn(),".medplum"),t=Tn(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=ii(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);Ln(t)});function Ln(e){let t=e.getLogins().map(r=>`${r.project.display} (${r.project.reference})`).join(`
20
20
 
21
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 Cn(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 On("-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 kn(a,c,s)});async function Cn(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
22
  `)}async function kn(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(Mn(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 Dn(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,Ya()),P(t,At);try{await t.parseAsync(e)}catch(r){_n(r)}}function _n(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)}